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
ab1ff95724b4b85f954869805e68acdcbd0b9974
23,861
cpp
C++
fennel/exec/ExecStreamGraph.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
14
2015-07-21T06:31:22.000Z
2020-05-13T14:18:33.000Z
fennel/exec/ExecStreamGraph.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
1
2020-05-04T23:08:51.000Z
2020-05-04T23:08:51.000Z
fennel/exec/ExecStreamGraph.cpp
alexavila150/luciddb
e3125564eb18238677e6efb384b630cab17bb472
[ "Apache-2.0" ]
22
2015-01-03T14:27:36.000Z
2021-09-14T02:09:13.000Z
/* // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI 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. */ #include "fennel/common/CommonPreamble.h" #include "fennel/exec/ExecStreamGraphImpl.h" #include "fennel/exec/ExecStream.h" #include "fennel/exec/ExecStreamBufAccessor.h" #include "fennel/exec/ExecStreamScheduler.h" #include "fennel/exec/DynamicParam.h" #include "fennel/exec/ExecStreamGovernor.h" #include "fennel/segment/Segment.h" #include "fennel/exec/ScratchBufferExecStream.h" #include "fennel/common/Backtrace.h" #include "fennel/txn/LogicalTxn.h" #include <boost/bind.hpp> #include <boost/graph/strong_components.hpp> #include <boost/graph/topological_sort.hpp> #include <boost/graph/graphviz.hpp> FENNEL_BEGIN_CPPFILE("$Id$"); SharedExecStreamGraph ExecStreamGraph::newExecStreamGraph() { return SharedExecStreamGraph( new ExecStreamGraphImpl(), ClosableObjectDestructor()); } ExecStreamGraph::ExecStreamGraph() : pScheduler(NULL), pDynamicParamManager(new DynamicParamManager()) { } ExecStreamGraph::~ExecStreamGraph() { } ExecStreamGraphImpl::ExecStreamGraphImpl() : filteredGraph( graphRep, boost::get(boost::edge_weight, graphRep)) { isPrepared = false; isOpen = false; doDataflowClose = false; allowDummyTxnId = false; } void ExecStreamGraphImpl::setTxn(SharedLogicalTxn pTxnInit) { pTxn = pTxnInit; } void ExecStreamGraphImpl::setErrorTarget(SharedErrorTarget pErrorTargetInit) { pErrorTarget = pErrorTargetInit; } void ExecStreamGraphImpl::setScratchSegment( SharedSegment pScratchSegmentInit) { pScratchSegment = pScratchSegmentInit; } void ExecStreamGraphImpl::setResourceGovernor( SharedExecStreamGovernor pResourceGovernorInit) { pResourceGovernor = pResourceGovernorInit; } SharedLogicalTxn ExecStreamGraphImpl::getTxn() { return pTxn; } TxnId ExecStreamGraphImpl::getTxnId() { if (pTxn) { return pTxn->getTxnId(); } assert(allowDummyTxnId); return FIRST_TXN_ID; } void ExecStreamGraphImpl::enableDummyTxnId(bool enabled) { allowDummyTxnId = enabled; } SharedExecStreamGovernor ExecStreamGraphImpl::getResourceGovernor() { return pResourceGovernor; } ExecStreamGraphImpl::Vertex ExecStreamGraphImpl::newVertex() { if (freeVertices.size() > 0) { Vertex ret = freeVertices.back(); freeVertices.pop_back(); return ret; } return boost::add_vertex(graphRep); } void ExecStreamGraphImpl::freeVertex(Vertex v) { boost::clear_vertex(v, graphRep); boost::get(boost::vertex_data, graphRep)[v].reset(); freeVertices.push_back(v); } int ExecStreamGraphImpl::getStreamCount() { return boost::num_vertices(graphRep) - freeVertices.size(); } ExecStreamGraphImpl::Vertex ExecStreamGraphImpl::addVertex(SharedExecStream pStream) { Vertex v = newVertex(); boost::put(boost::vertex_data, graphRep, v, pStream); if (pStream) { // Note that pStream can be null for an exterior node in a farrago // graph. Guard against duplicating a stream name. const std::string& name = pStream->getName(); if (name.length() == 0) { permFail("cannot add nameless stream to graph " << this); } if (findStream(name)) { permFail("cannot add stream " << name << " to graph " << this); } pStream->id = v; pStream->pGraph = this; streamMap[name] = pStream->getStreamId(); } return v; } void ExecStreamGraphImpl::addStream( SharedExecStream pStream) { (void) addVertex(pStream); } void ExecStreamGraphImpl::removeStream(ExecStreamId id) { Vertex v = boost::vertices(graphRep).first[id]; SharedExecStream pStream = getStreamFromVertex(v); permAssert(pStream->pGraph == this); permAssert(pStream->id == id); streamMap.erase(pStream->getName()); removeFromStreamOutMap(pStream); sortedStreams.clear(); // invalidate list: recreated on demand freeVertex(v); // stream is now detached from any graph, and not usable. pStream->pGraph = 0; pStream->id = 0; } void ExecStreamGraphImpl::removeFromStreamOutMap(SharedExecStream p) { int outCt = getOutputCount(p->getStreamId()); if (outCt > 0) { std::string name = p->getName(); // assumes map key pairs <name, index> sort lexicographically, so // <name, *> is contiguous. EdgeMap::iterator startNameRange = streamOutMap.find(std::make_pair(name, 0)); EdgeMap::iterator endNameRange = streamOutMap.find(std::make_pair(name, outCt - 1)); streamOutMap.erase(startNameRange, endNameRange); } } // Deletes all edges and puts all vertices on the free list; // almost like removeStream() on all vertices, // but doesn't affect the ExecStream which no longer belongs to this graph. void ExecStreamGraphImpl::clear() { FgVertexIterPair verts = boost::vertices(graphRep); while (verts.first != verts.second) { Vertex v = *verts.first; freeVertex(v); ++verts.first; } streamMap.clear(); streamOutMap.clear(); sortedStreams.clear(); needsClose = isOpen = isPrepared = false; } void ExecStreamGraphImpl::addDataflow( ExecStreamId producerId, ExecStreamId consumerId, bool isImplicit) { Edge newEdge = boost::add_edge(producerId, consumerId, graphRep).first; boost::put( boost::edge_weight, graphRep, newEdge, isImplicit ? 0 : 1); } void ExecStreamGraphImpl::addOutputDataflow( ExecStreamId producerId) { Vertex consumerId = newVertex(); Edge newEdge = boost::add_edge(producerId, consumerId, graphRep).first; boost::put( boost::edge_weight, graphRep, newEdge, 1); } void ExecStreamGraphImpl::addInputDataflow( ExecStreamId consumerId) { Vertex producerId = newVertex(); Edge newEdge = boost::add_edge(producerId, consumerId, graphRep).first; boost::put( boost::edge_weight, graphRep, newEdge, 1); } int ExecStreamGraphImpl::getDataflowCount() { return boost::num_edges(graphRep); } void ExecStreamGraphImpl::mergeFrom(ExecStreamGraph& src) { if (ExecStreamGraphImpl *p = dynamic_cast<ExecStreamGraphImpl*>(&src)) { mergeFrom(*p); return; } permFail("unknown subtype of ExecStreamGraph"); } void ExecStreamGraphImpl::mergeFrom( ExecStreamGraph& src, std::vector<ExecStreamId> const& nodes) { if (ExecStreamGraphImpl *p = dynamic_cast<ExecStreamGraphImpl*>(&src)) { mergeFrom(*p, nodes); return; } permFail("unknown subtype of ExecStreamGraph"); } void ExecStreamGraphImpl::mergeFrom(ExecStreamGraphImpl& src) { // Since the identity of the added graph SRC will be lost, at this time both // graphs must be prepared, and must both be open or both be closed. permAssert(isPrepared && src.isPrepared); permAssert(isOpen == src.isOpen); // map a source vertex ID to the ID of the copied target vertex std::map<Vertex, Vertex> vmap; // copy the nodes (with attached streams) FgVertexIterPair verts = boost::vertices(src.graphRep); for (; verts.first != verts.second; ++verts.first) { Vertex vsrc = *verts.first; SharedExecStream pStream = src.getStreamFromVertex(vsrc); Vertex vnew = addVertex(pStream); vmap[vsrc] = vnew; } // copy the edges (with attached buffers, which stay bound to the adjacent // streams) FgEdgeIterPair edges = boost::edges(src.graphRep); for (; edges.first != edges.second; ++edges.first) { Edge esrc = *edges.first; SharedExecStreamBufAccessor pBuf = src.getSharedBufAccessorFromEdge(esrc); std::pair<Edge, bool> x = boost::add_edge( vmap[boost::source(esrc, src.graphRep)], // image of source node vmap[boost::target(esrc, src.graphRep)], // image of target node pBuf, graphRep); boost::put( boost::edge_weight, graphRep, x.first, boost::get(boost::edge_weight, src.graphRep, esrc)); assert(x.second); } src.clear(); // source is empty sortedStreams.clear(); // invalid now } // merges a subgraph, viz the induced subgraph of a set of NODES of SRC void ExecStreamGraphImpl::mergeFrom( ExecStreamGraphImpl& src, std::vector<ExecStreamId> const& nodes) { // both graphs must be prepared, and must both be open or both be closed. permAssert(isPrepared && src.isPrepared); permAssert(isOpen == src.isOpen); // map a source vertex ID to the ID of the copied target vertex std::map<Vertex, Vertex> vmap; // Copy the nodes (with attached streams) int nnodes = nodes.size(); for (int i = 0; i < nnodes; i++) { Vertex vsrc = boost::vertices(src.graphRep).first[nodes[i]]; SharedExecStream pStream = src.getStreamFromVertex(vsrc); Vertex vnew = addVertex(pStream); vmap[vsrc] = vnew; } // Copy the internal edges (with attached buffers, which stay bound to the // adjacent streams). It suffices to scan the outbound edges. The external // edges are abandoned. if (nnodes > 1) { // (when only 1 node, no internal edges) for (int i = 0; i < nnodes; i++) { // Find all outbound edges E (U,V) in the source subgraph Vertex u = boost::vertices(src.graphRep).first[nodes[i]]; for (FgOutEdgeIterPair edges = boost::out_edges(u, src.graphRep); edges.first != edges.second; ++edges.first) { // an edge e (u, v) in the source graph Edge e = *edges.first; assert(u == boost::source(e, src.graphRep)); Vertex v = boost::target(e, src.graphRep); // V is in the subgraph iff v is a key in the map vmap[] if (vmap.find(v) != vmap.end()) { SharedExecStreamBufAccessor pBuf = src.getSharedBufAccessorFromEdge(e); std::pair<Edge, bool> x = boost::add_edge( vmap[u], vmap[v], pBuf, graphRep); assert(x.second); boost::put( boost::edge_weight, graphRep, x.first, boost::get(boost::edge_weight, src.graphRep, e)); } } } } // delete the copied subgraph from SRC for (int i = 0; i < nnodes; i++) { Vertex v = boost::vertices(src.graphRep).first[nodes[i]]; SharedExecStream pStream = src.getStreamFromVertex(v); src.streamMap.erase(pStream->getName()); src.removeFromStreamOutMap(pStream); src.freeVertex(v); } src.sortedStreams.clear(); // invalidate sortedStreams.clear(); // invalidate } SharedExecStream ExecStreamGraphImpl::findStream( std::string name) { StreamMapConstIter pPair = streamMap.find(name); if (pPair == streamMap.end()) { SharedExecStream nullStream; return nullStream; } else { return getStreamFromVertex(pPair->second); } } SharedExecStream ExecStreamGraphImpl::findLastStream( std::string name, uint iOutput) { EdgeMap::const_iterator pPair = streamOutMap.find(std::make_pair(name, iOutput)); if (pPair == streamOutMap.end()) { return findStream(name); } else { return getStreamFromVertex(pPair->second); } } void ExecStreamGraphImpl::interposeStream( std::string name, uint iOutput, ExecStreamId interposedId) { SharedExecStream pLastStream = findLastStream(name, iOutput); permAssert(pLastStream.get()); streamOutMap[std::make_pair(name, iOutput)] = interposedId; addDataflow( pLastStream->getStreamId(), interposedId, false); } void ExecStreamGraphImpl::sortStreams() { std::vector<Vertex> sortedVertices; boost::topological_sort( graphRep, std::back_inserter(sortedVertices)); sortedStreams.resize(sortedVertices.size()); // boost::topological_sort produces an ordering from consumers to // producers, but we want the oppposite ordering, hence // sortedStreams.rbegin() below std::transform( sortedVertices.begin(), sortedVertices.end(), sortedStreams.rbegin(), boost::bind(&ExecStreamGraphImpl::getStreamFromVertex,this,_1)); // now filter out the null vertices representing inputs and outputs sortedStreams.erase( std::remove( sortedStreams.begin(), sortedStreams.end(), SharedExecStream()), sortedStreams.end()); } void ExecStreamGraphImpl::prepare(ExecStreamScheduler &scheduler) { isPrepared = true; sortStreams(); // create buffer accessors for all explicit dataflow edges EdgeIterPair edges = boost::edges(filteredGraph); for (; edges.first != edges.second; edges.first++) { SharedExecStreamBufAccessor pBufAccessor = scheduler.newBufAccessor(); boost::put(boost::edge_data, graphRep, *(edges.first), pBufAccessor); } // bind buffer accessors to streams std::for_each( sortedStreams.begin(), sortedStreams.end(), boost::bind( &ExecStreamGraphImpl::bindStreamBufAccessors,this,_1)); } void ExecStreamGraphImpl::bindStreamBufAccessors(SharedExecStream pStream) { std::vector<SharedExecStreamBufAccessor> bufAccessors; // bind the input buffers (explicit dataflow only) InEdgeIterPair inEdges = boost::in_edges( pStream->getStreamId(), filteredGraph); for (; inEdges.first != inEdges.second; ++(inEdges.first)) { SharedExecStreamBufAccessor pBufAccessor = getSharedBufAccessorFromEdge(*(inEdges.first)); bufAccessors.push_back(pBufAccessor); } pStream->setInputBufAccessors(bufAccessors); bufAccessors.clear(); // bind the output buffers (explicit dataflow only) OutEdgeIterPair outEdges = boost::out_edges( pStream->getStreamId(), filteredGraph); for (; outEdges.first != outEdges.second; ++(outEdges.first)) { SharedExecStreamBufAccessor pBufAccessor = getSharedBufAccessorFromEdge(*(outEdges.first)); bufAccessors.push_back(pBufAccessor); pBufAccessor->setProvision(pStream->getOutputBufProvision()); } pStream->setOutputBufAccessors(bufAccessors); } void ExecStreamGraphImpl::open() { permAssert(!isOpen); isOpen = true; needsClose = true; // clear all buffer accessors EdgeIterPair edges = boost::edges(filteredGraph); for (; edges.first != edges.second; edges.first++) { ExecStreamBufAccessor &bufAccessor = getBufAccessorFromEdge(*(edges.first)); bufAccessor.clear(); } // open streams in dataflow order (from producers to consumers) if (sortedStreams.empty()) { // in case removeStream() was called after prepare sortStreams(); } std::for_each( sortedStreams.begin(), sortedStreams.end(), boost::bind(&ExecStreamGraphImpl::openStream,this,_1)); } void ExecStreamGraphImpl::openStream(SharedExecStream pStream) { if (pErrorTarget) { pStream->initErrorSource(pErrorTarget, pStream->getName()); } pStream->open(false); } void ExecStreamGraphImpl::closeImpl() { isOpen = false; if (sortedStreams.empty()) { // in case prepare was never called sortStreams(); } if (doDataflowClose) { std::for_each( sortedStreams.begin(), sortedStreams.end(), boost::bind(&ClosableObject::close,_1)); } else { std::for_each( sortedStreams.rbegin(), sortedStreams.rend(), boost::bind(&ClosableObject::close,_1)); } std::for_each( sortedStreams.begin(), sortedStreams.end(), boost::bind(&ErrorSource::disableTarget,_1)); pDynamicParamManager->deleteAllParams(); SharedExecStreamGovernor pGov = getResourceGovernor(); if (pGov) { pGov->returnResources(*this); } pTxn.reset(); // release any scratch memory if (pScratchSegment) { pScratchSegment->deallocatePageRange(NULL_PAGE_ID, NULL_PAGE_ID); } pErrorTarget.reset(); } SharedExecStream ExecStreamGraphImpl::getStream(ExecStreamId id) { Vertex v = boost::vertices(graphRep).first[id]; return getStreamFromVertex(v); } uint ExecStreamGraphImpl::getInputCount( ExecStreamId streamId) { Vertex streamVertex = boost::vertices(graphRep).first[streamId]; return boost::in_degree(streamVertex, filteredGraph); } uint ExecStreamGraphImpl::getOutputCount( ExecStreamId streamId) { Vertex streamVertex = boost::vertices(graphRep).first[streamId]; return boost::out_degree(streamVertex, filteredGraph); } ExecStreamGraphImpl::Edge ExecStreamGraphImpl::getInputEdge( ExecStreamId streamId, uint iInput) { Vertex streamVertex = boost::vertices(graphRep).first[streamId]; InEdgeIter pEdge = boost::in_edges(streamVertex, filteredGraph).first; for (int i = 0; i < iInput; ++i) { ++pEdge; } return *pEdge; } SharedExecStream ExecStreamGraphImpl::getStreamInput( ExecStreamId streamId, uint iInput) { Edge inputEdge = getInputEdge(streamId, iInput); Vertex inputVertex = boost::source(inputEdge, graphRep); return getStreamFromVertex(inputVertex); } SharedExecStreamBufAccessor ExecStreamGraphImpl::getStreamInputAccessor( ExecStreamId streamId, uint iInput) { Edge inputEdge = getInputEdge(streamId, iInput); return getSharedBufAccessorFromEdge(inputEdge); } ExecStreamGraphImpl::Edge ExecStreamGraphImpl::getOutputEdge( ExecStreamId streamId, uint iOutput) { Vertex streamVertex = boost::vertices(graphRep).first[streamId]; OutEdgeIter pEdge = boost::out_edges(streamVertex, filteredGraph).first; for (int i = 0; i < iOutput; ++i) { ++pEdge; } return *pEdge; } SharedExecStream ExecStreamGraphImpl::getStreamOutput( ExecStreamId streamId, uint iOutput) { Edge outputEdge = getOutputEdge(streamId, iOutput); Vertex outputVertex = boost::target(outputEdge, graphRep); return getStreamFromVertex(outputVertex); } SharedExecStreamBufAccessor ExecStreamGraphImpl::getStreamOutputAccessor( ExecStreamId streamId, uint iOutput) { Edge outputEdge = getOutputEdge(streamId, iOutput); return getSharedBufAccessorFromEdge(outputEdge); } std::vector<SharedExecStream> ExecStreamGraphImpl::getSortedStreams() { permAssert(isPrepared); if (sortedStreams.empty()) { sortStreams(); } return sortedStreams; } bool ExecStreamGraphImpl::isAcyclic() { int numVertices = boost::num_vertices(graphRep); // if # strong components is < # vertices, then there must be at least // one cycle std::vector<int> component(numVertices); int nStrongComps = boost::strong_components(graphRep, &component[0]); return (nStrongComps >= numVertices); } class ExecStreamGraphImpl::DotGraphRenderer { public: void operator()(std::ostream &out) const { out << "graph [bgcolor=gray, rankdir=BT]" << std::endl; out << "node [shape=record, style=filled, " << "fillcolor=white, fontsize=10.0]" << std::endl; out << "edge [fontsize=10.0]" << std::endl; } }; class ExecStreamGraphImpl::DotEdgeRenderer { ExecStreamGraphImpl &graph; public: DotEdgeRenderer(ExecStreamGraphImpl &graphInit) : graph(graphInit) { } void operator()( std::ostream &out, ExecStreamGraphImpl::Edge const &edge) const { SharedExecStreamBufAccessor pAccessor = graph.getSharedBufAccessorFromEdge(edge); int weight = boost::get( boost::edge_weight, graph.getFullGraphRep(), edge); out << "[label=\""; if (pAccessor) { out << ExecStreamBufState_names[pAccessor->getState()]; } out << "\""; if (!weight) { out << "style=\"dotted\""; } out << "]"; } }; class ExecStreamGraphImpl::DotVertexRenderer { ExecStreamGraphImpl &graph; public: DotVertexRenderer(ExecStreamGraphImpl &graphInit) : graph(graphInit) { } void operator()(std::ostream &out, ExecStreamId const &streamId) const { SharedExecStream pStream = graph.getStream(streamId); out << "[label=\"{"; if (pStream) { out << streamId; out << "|"; if (dynamic_cast<ScratchBufferExecStream *>(pStream.get())) { out << "MEMBUF"; } else { Backtrace::writeDemangled(out, typeid(*pStream).name()); out << "|"; out << pStream->getName(); } } else { out << "SINK"; } out << "}\"]"; } }; void ExecStreamGraphImpl::renderGraphviz(std::ostream &dotStream) { boost::write_graphviz( dotStream, graphRep, DotVertexRenderer(*this), DotEdgeRenderer(*this), DotGraphRenderer()); } void ExecStreamGraphImpl::closeProducers(ExecStreamId streamId) { FgInEdgeIterPair inEdges = boost::in_edges(streamId, graphRep); for (; inEdges.first != inEdges.second; ++(inEdges.first)) { Edge edge = *(inEdges.first); // move streamId upstream streamId = boost::source(edge, graphRep); // close the producers of this stream before closing the stream // itself, but only if it's possible to early close the stream SharedExecStream pStream = getStreamFromVertex(streamId); if (!pStream->canEarlyClose()) { continue; } closeProducers(streamId); pStream->close(); } } void ExecStreamGraphImpl::declareDynamicParamWriter( ExecStreamId streamId, DynamicParamId dynamicParamId) { DynamicParamInfo &info = dynamicParamMap[dynamicParamId]; info.writerStreamIds.push_back(streamId); } void ExecStreamGraphImpl::declareDynamicParamReader( ExecStreamId streamId, DynamicParamId dynamicParamId) { DynamicParamInfo &info = dynamicParamMap[dynamicParamId]; info.readerStreamIds.push_back(streamId); } const std::vector<ExecStreamId> &ExecStreamGraphImpl::getDynamicParamWriters( DynamicParamId dynamicParamId) { DynamicParamInfo &info = dynamicParamMap[dynamicParamId]; return info.writerStreamIds; } const std::vector<ExecStreamId> &ExecStreamGraphImpl::getDynamicParamReaders( DynamicParamId dynamicParamId) { DynamicParamInfo &info = dynamicParamMap[dynamicParamId]; return info.readerStreamIds; } FENNEL_END_CPPFILE("$Id$"); // End ExecStreamGraph.cpp
29.938519
80
0.655672
[ "shape", "vector", "transform" ]
ab21083c9325732f7427b211a22664af52bfd1e6
3,289
cc
C++
chrome/browser/extensions/api/signedin_devices/signedin_devices_api_unittest.cc
MIPS/external-chromium_org
e31b3128a419654fd14003d6117caa8da32697e7
[ "BSD-3-Clause" ]
2
2017-03-21T23:19:25.000Z
2019-02-03T05:32:47.000Z
chrome/browser/extensions/api/signedin_devices/signedin_devices_api_unittest.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/api/signedin_devices/signedin_devices_api_unittest.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2013 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 <string> #include <vector> #include "base/guid.h" #include "base/message_loop/message_loop.h" #include "chrome/browser/extensions/api/signedin_devices/signedin_devices_api.h" #include "chrome/browser/extensions/test_extension_prefs.h" #include "chrome/browser/sync/glue/device_info.h" #include "chrome/browser/sync/profile_sync_service_mock.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_manifest_constants.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using extensions::Extension; using extensions::TestExtensionPrefs; using browser_sync::DeviceInfo; using testing::Return; namespace extensions { TEST(SignedinDevicesAPITest, GetSignedInDevices) { ProfileSyncServiceMock pss_mock; base::MessageLoop message_loop_; TestExtensionPrefs extension_prefs( message_loop_.message_loop_proxy().get()); // Add a couple of devices and make sure we get back public ids for them. std::string extension_name = "test"; scoped_refptr<Extension> extension_test = extension_prefs.AddExtension(extension_name); DeviceInfo device_info1( base::GenerateGUID(), "abc Device", "XYZ v1", "XYZ SyncAgent v1", sync_pb::SyncEnums_DeviceType_TYPE_LINUX); DeviceInfo device_info2( base::GenerateGUID(), "def Device", "XYZ v2", "XYZ SyncAgent v2", sync_pb::SyncEnums_DeviceType_TYPE_LINUX); std::vector<DeviceInfo*> devices; devices.push_back(&device_info1); devices.push_back(&device_info2); EXPECT_CALL(pss_mock, GetAllSignedInDevicesMock()). WillOnce(Return(&devices)); ScopedVector<DeviceInfo> output1 = GetAllSignedInDevices( extension_test.get()->id(), &pss_mock, extension_prefs.prefs()); std::string public_id1 = device_info1.public_id(); std::string public_id2 = device_info2.public_id(); EXPECT_FALSE(public_id1.empty()); EXPECT_FALSE(public_id2.empty()); EXPECT_NE(public_id1, public_id2); // Now clear output1 so its destructor will not destroy the pointers for // |device_info1| and |device_info2|. output1.weak_clear(); // Add a third device and make sure the first 2 ids are retained and a new // id is generated for the third device. DeviceInfo device_info3( base::GenerateGUID(), "def Device", "jkl v2", "XYZ SyncAgent v2", sync_pb::SyncEnums_DeviceType_TYPE_LINUX); devices.push_back(&device_info3); EXPECT_CALL(pss_mock, GetAllSignedInDevicesMock()). WillOnce(Return(&devices)); ScopedVector<DeviceInfo> output2 = GetAllSignedInDevices( extension_test.get()->id(), &pss_mock, extension_prefs.prefs()); EXPECT_EQ(device_info1.public_id(), public_id1); EXPECT_EQ(device_info2.public_id(), public_id2); std::string public_id3 = device_info3.public_id(); EXPECT_FALSE(public_id3.empty()); EXPECT_NE(public_id3, public_id1); EXPECT_NE(public_id3, public_id2); // Now clear output2 so that its destructor does not destroy the // |DeviceInfo| pointers. output2.weak_clear(); } } // namespace extensions
32.245098
80
0.742475
[ "vector" ]
ab21a40728884e541a5d6a359f18907fb92ec9f6
15,422
cpp
C++
keypoints_descriptors_test/keypoints_descriptors_test.cpp
oleg-Shipitko/pcl_examples
bc7f6e86da625affeb3e42cdfb3a771e69205f7d
[ "BSD-2-Clause" ]
null
null
null
keypoints_descriptors_test/keypoints_descriptors_test.cpp
oleg-Shipitko/pcl_examples
bc7f6e86da625affeb3e42cdfb3a771e69205f7d
[ "BSD-2-Clause" ]
null
null
null
keypoints_descriptors_test/keypoints_descriptors_test.cpp
oleg-Shipitko/pcl_examples
bc7f6e86da625affeb3e42cdfb3a771e69205f7d
[ "BSD-2-Clause" ]
1
2020-07-16T16:07:51.000Z
2020-07-16T16:07:51.000Z
// STL #include <iostream> // PCL #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/common/io.h> #include <pcl/filters/filter.h> #include <pcl/keypoints/sift_keypoint.h> #include <pcl/keypoints/impl/sift_keypoint.hpp> #include <pcl/features/normal_3d.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/keypoints/iss_3d.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/pcd_io.h> #include <pcl/io/io.h> #include <boost/thread/thread.hpp> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/filters/passthrough.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/filters/extract_indices.h> #include <pcl/ModelCoefficients.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/common/common.h> #include <pcl/registration/sample_consensus_prerejective.h> #include <pcl/registration/icp.h> #include <pcl/common/time.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/features/fpfh.h> #include <pcl/console/print.h> #include <pcl/features/vfh.h> #include <pcl/common/intersections.h> #include <Eigen/Core> #include <pcl/sample_consensus/sac_model_parallel_line.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/segmentation/region_growing_rgb.h> #include <pcl/surface/convex_hull.h> #include <pcl/keypoints/harris_3d.h> #include <pcl/features/usc.h> // Standatrd libraries #include <iostream> #include <vector> #include <string> #include <stack> double computeCloudResolution(const pcl::PointCloud<pcl::PointNormal>::ConstPtr& cloud) { double resolution = 0.0; int numberOfPoints = 0; int nres; std::vector<int> indices(2); std::vector<float> squaredDistances(2); pcl::search::KdTree<pcl::PointNormal> tree; tree.setInputCloud(cloud); for (size_t i = 0; i < cloud->size(); ++i) { if (! pcl_isfinite((*cloud)[i].x)) continue; // Considering the second neighbor since the first is the point itself. nres = tree.nearestKSearch(i, 2, indices, squaredDistances); if (nres == 2) { resolution += sqrt(squaredDistances[1]); ++numberOfPoints; } } if (numberOfPoints != 0) resolution /= numberOfPoints; return resolution; } int main(int, char** argv) { //**********************LOAD FILES FROM DISK********************************************** std::string box_filename = argv[1]; std::cout << "Reading " << box_filename << std::endl; pcl::PointCloud<pcl::PointXYZRGB>::Ptr box (new pcl::PointCloud<pcl::PointXYZRGB>); if(pcl::io::loadPCDFile<pcl::PointXYZRGB> (box_filename, *box) == -1) // load the file { PCL_ERROR ("Couldn't read file"); return -1; } std::cout << "points: " << box->points.size () <<std::endl; std::string scene_filename = argv[2]; std::cout << "Reading " << scene_filename << std::endl; pcl::PointCloud<pcl::PointXYZRGB>::Ptr scene (new pcl::PointCloud<pcl::PointXYZRGB>); if(pcl::io::loadPCDFile<pcl::PointXYZRGB> (scene_filename, *scene) == -1) // load the file { PCL_ERROR ("Couldn't read file"); return -1; } std::cout << "points: " << scene->points.size () <<std::endl; //**********************VOXEL GRID********************************************** float leaf = 0.005f; pcl::VoxelGrid<pcl::PointXYZRGB> grid; grid.setLeafSize (leaf, leaf, leaf); grid.setInputCloud (box); grid.filter (*box); grid.setInputCloud (scene); grid.filter (*scene); //**********************COMPUTE NORMALS********************************************** pcl::PointCloud<pcl::PointNormal>::Ptr box_normals (new pcl::PointCloud<pcl::PointNormal>); pcl::PointCloud<pcl::PointNormal>::Ptr scene_normals (new pcl::PointCloud<pcl::PointNormal>); pcl::copyPointCloud(*box, *box_normals); pcl::copyPointCloud(*scene, *scene_normals); // Estimate normals for scene and object pcl::console::print_highlight ("Estimating scene and object normals...\n"); pcl::NormalEstimationOMP<pcl::PointXYZRGB, pcl::PointNormal> nest; nest.setViewPoint(3, -3, 0); nest.setRadiusSearch (0.025f); nest.setInputCloud (box); nest.compute (*box_normals); nest.setInputCloud (scene); nest.compute (*scene_normals); // Saving the resultant cloud pcl::io::savePCDFileASCII("normals_box.pcd", *box_normals); pcl::io::savePCDFileASCII("normals_scene.pcd", *scene_normals); //**********************COMPUTE ISS KEYPOINTS********************************************** pcl::PointCloud<pcl::PointNormal>::Ptr box_keypoints (new pcl::PointCloud<pcl::PointNormal>); pcl::PointCloud<pcl::PointNormal>::Ptr scene_keypoints (new pcl::PointCloud<pcl::PointNormal>); pcl::search::KdTree<pcl::PointNormal>::Ptr tree (new pcl::search::KdTree<pcl::PointNormal>); pcl::ISSKeypoint3D<pcl::PointNormal, pcl::PointNormal> iss_detector; double resolution = computeCloudResolution(box_normals); iss_detector.setSearchMethod (tree); iss_detector.setSalientRadius (6 * resolution); iss_detector.setNonMaxRadius (4 * resolution); iss_detector.setThreshold21 (0.975); iss_detector.setThreshold32 (0.975); iss_detector.setMinNeighbors (5); iss_detector.setNumberOfThreads (4); iss_detector.setInputCloud (box_normals); iss_detector.compute (*box_keypoints); resolution = computeCloudResolution(scene_normals); iss_detector.setSalientRadius (6 * resolution); iss_detector.setNonMaxRadius (4 * resolution); iss_detector.setInputCloud (scene_normals); iss_detector.compute (*scene_keypoints); // for(size_t i = 0; i < box_keypoints->width; i++) // { // for (size_t j = 0; j < box_normals->width; j++) // { // if(box_normals->points[j].x == box_keypoints->points[i].x && // box_normals->points[j].y == box_keypoints->points[i].y && // box_normals->points[j].z == box_keypoints->points[i].z) // { // box_keypoints->points[i].normal_x = box_normals->points[j].normal_x; // box_keypoints->points[i].normal_y = box_normals->points[j].normal_y; // box_keypoints->points[i].normal_z = box_normals->points[j].normal_z; // box_keypoints->points[i].curvature = box_normals->points[j].curvature; // } // } // } // for(size_t i = 0; i < scene_keypoints->width; i++) // { // for (size_t j = 0; j < scene_normals->width; j++) // { // if(scene_normals->points[j].x == scene_keypoints->points[i].x && // scene_normals->points[j].y == scene_keypoints->points[i].y && // scene_normals->points[j].z == scene_keypoints->points[i].z) // { // scene_keypoints->points[i].normal_x = scene_normals->points[j].normal_x; // scene_keypoints->points[i].normal_y = scene_normals->points[j].normal_y; // scene_keypoints->points[i].normal_z = scene_normals->points[j].normal_z; // scene_keypoints->points[i].curvature = scene_normals->points[j].curvature; // } // } // } // Saving the resultant cloud std::cout << "Resulting iss points of box: " << box_keypoints->points.size() <<std::endl; pcl::io::savePCDFileASCII("iss_keypoints_box.pcd", *box_keypoints); std::cout << "Resulting iss points of scene: " << scene_keypoints->points.size() <<std::endl; pcl::io::savePCDFileASCII("iss_keypoints_scene.pcd", *scene_keypoints); std::vector<int> v; pcl::removeNaNFromPointCloud(*scene_keypoints, *scene_keypoints, v); pcl::removeNaNFromPointCloud(*box_keypoints, *box_keypoints, v); //**********************COMPUTE FPFH IN KEYPOINTS********************************************** // Estimate features pcl::PointCloud<pcl::FPFHSignature33>::Ptr box_features (new pcl::PointCloud<pcl::FPFHSignature33>); pcl::PointCloud<pcl::FPFHSignature33>::Ptr scene_features (new pcl::PointCloud<pcl::FPFHSignature33>); pcl::console::print_highlight ("Estimating features...\n"); pcl::FPFHEstimation<pcl::PointNormal, pcl::PointNormal, pcl::FPFHSignature33> fest; fest.setRadiusSearch (0.055f); // 0.025 fest.setInputCloud (box_normals); fest.setInputNormals (box_normals); // for (int i = 0; i < box_normals->points.size(); i++) //!!! Check how to acess normals !!! // { // if (!pcl::isFinite<pcl::PointNormal>(box_normals->points[i])) // { // std::cout << "normals[%d] are not finite\n"; // } // } fest.compute (*box_features); fest.setInputCloud (scene_normals); fest.setInputNormals (scene_normals); // for (int i = 0; i < scene_normals->points.size(); i++) //!!! Check how to acess normals !!! // { // if (!pcl::isFinite<pcl::PointNormal>(scene_normals->points[i])) // { // std::cout << "normals[%d] are not finite\n"; // } // } fest.compute (*scene_features); pcl::io::savePCDFileASCII("features_box.pcd", *box_features); pcl::io::savePCDFileASCII("features_scene.pcd", *scene_features); // USC estimation object. // pcl::PointCloud<pcl::UniqueShapeContext1960>::Ptr box_features (new pcl::PointCloud<pcl::UniqueShapeContext1960>); // pcl::PointCloud<pcl::UniqueShapeContext1960>::Ptr scene_features (new pcl::PointCloud<pcl::UniqueShapeContext1960>); // pcl::UniqueShapeContext<pcl::PointNormal, pcl::UniqueShapeContext1960, pcl::ReferenceFrame> usc; // usc.setInputCloud(scene_keypoints); // // Search radius, to look for neighbors. It will also be the radius of the support sphere. // usc.setRadiusSearch(0.05); // // The minimal radius value for the search sphere, to avoid being too sensitive // // in bins close to the center of the sphere. // usc.setMinimalRadius(0.05 / 10.0); // // Radius used to compute the local point density for the neighbors // // (the density is the number of points within that radius). // usc.setPointDensityRadius(0.05 / 5.0); // // Set the radius to compute the Local Reference Frame. // usc.setLocalRadius(0.05); // usc.compute(*scene_features); // usc.setInputCloud(box_keypoints); // usc.compute(*box_features); //**********************FIND CORRESPONDENCES BETWEEN SCENE AND BOX********************************************** // A kd-tree object that uses the FLANN library for fast search of nearest neighbors. // pcl::KdTreeFLANN<pcl::FPFHSignature33> matching; pcl::KdTreeFLANN<pcl::FPFHSignature33> matching; matching.setInputCloud(box_features); // A Correspondence object stores the indices of the query and the match, // and the distance/weight. pcl::Correspondences correspondences; // Check every descriptor computed for the scene. for (size_t i = 0; i < scene_features->size(); ++i) { std::vector<int> neighbors(1); std::vector<float> squaredDistances(1); // Ignore NaNs. // if (pcl_isfinite(scene_features->at(i).descriptor[0])) // { // Find the nearest neighbor (in descriptor space)... int neighborCount = matching.nearestKSearch(scene_features->at(i), 1, neighbors, squaredDistances); // ...and add a new correspondence if the distance is less than a threshold // (SHOT distances are between 0 and 1, other descriptors use different metrics). // std::cout << sqrt(squaredDistances[0] / squaredDistances[1]) << std::endl; if (sqrt(squaredDistances[0] / squaredDistances[1]) > 0.6 && sqrt(squaredDistances[0] / squaredDistances[1]) != std::numeric_limits<float>::infinity()) { pcl::Correspondence correspondence(neighbors[0], static_cast<int>(i), squaredDistances[0]); correspondences.push_back(correspondence); } // } } std::cout << "Found " << correspondences.size() << " correspondences." << std::endl; //**********************PERFORM BOX TO SCENE ALIGNMENT********************************************** pcl::PointCloud<pcl::PointNormal>::Ptr box_aligned (new pcl::PointCloud<pcl::PointNormal>); // Perform alignment leaf = 0.005f; pcl::console::print_highlight ("Starting alignment...\n"); pcl::SampleConsensusPrerejective<pcl::PointNormal,pcl::PointNormal,pcl::FPFHSignature33> align; align.setInputSource (box_normals); align.setSourceFeatures (box_features); align.setInputTarget (scene_normals); align.setTargetFeatures (scene_features); align.setMaximumIterations (50000); // Number of RANSAC iterations align.setNumberOfSamples (5); // Number of points to sample for generating/prerejecting a pose align.setCorrespondenceRandomness (3); // Number of nearest features to use align.setSimilarityThreshold (0.6f); // Polygonal edge length similarity threshold align.setMaxCorrespondenceDistance (5.5f * leaf); // Inlier threshold align.setInlierFraction (0.1f); // Required inlier fraction for accepting a pose hypothesis { pcl::ScopeTime t("Alignment"); align.align (*box_aligned); } if (align.hasConverged ()) { // Print results printf ("\n"); Eigen::Matrix4f transformation = align.getFinalTransformation (); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", transformation (0,0), transformation (0,1), transformation (0,2)); pcl::console::print_info ("R = | %6.3f %6.3f %6.3f | \n", transformation (1,0), transformation (1,1), transformation (1,2)); pcl::console::print_info (" | %6.3f %6.3f %6.3f | \n", transformation (2,0), transformation (2,1), transformation (2,2)); pcl::console::print_info ("\n"); pcl::console::print_info ("t = < %0.3f, %0.3f, %0.3f >\n", transformation (0,3), transformation (1,3), transformation (2,3)); pcl::console::print_info ("\n"); pcl::console::print_info ("Inliers: %i/%i\n", align.getInliers ().size (), box_aligned->size ()); pcl::io::savePCDFileASCII("box_aligned.pcd", *box_aligned); } else { pcl::console::print_error ("Alignment failed!\n"); } //**********************VISUALIZATION********************************************** // Visualization of keypoints along with the original cloud pcl::visualization::PCLVisualizer viewer("PCL Viewer"); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointNormal> box_keypoints_color_handler (box_keypoints, 0, 255, 0); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointNormal> scene_keypoints_color_handler (scene_keypoints, 0, 255, 0); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> box_color_handler (box, 255, 0, 0); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZRGB> scene_color_handler (scene, 255, 0, 0); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointNormal> box_aligned_color_handler (box_aligned, 0, 0, 255); viewer.setBackgroundColor( 0.0, 0.0, 0.0 ); viewer.addPointCloud(box, box_color_handler, "box"); viewer.addPointCloud(box_keypoints, box_keypoints_color_handler, "box_keypoints"); viewer.addPointCloud(scene, scene_color_handler, "scene"); viewer.addPointCloud(box_aligned, box_aligned_color_handler, "aligned"); viewer.addPointCloud(scene_keypoints, scene_keypoints_color_handler, "scene_keypoints"); viewer.addCorrespondences<pcl::PointXYZRGB>(scene, box, correspondences); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 7, "box_keypoints"); viewer.setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 7, "scene_keypoints"); while(!viewer.wasStopped()) { viewer.spinOnce (); } return 0; }
44.701449
157
0.680132
[ "object", "vector" ]
ab2ad720acf051724ce74f8258cb4a21995b22ef
22,209
cc
C++
cartographer/mapping_3d/submaps.cc
binxxx/cartographer
0f09131437acd8da86c48455593af1dd1551f1eb
[ "Apache-2.0" ]
null
null
null
cartographer/mapping_3d/submaps.cc
binxxx/cartographer
0f09131437acd8da86c48455593af1dd1551f1eb
[ "Apache-2.0" ]
null
null
null
cartographer/mapping_3d/submaps.cc
binxxx/cartographer
0f09131437acd8da86c48455593af1dd1551f1eb
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 The Cartographer Authors * * 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 "cartographer/mapping_3d/submaps.h" #include <cmath> #include <limits> #include "cartographer/common/math.h" #include "cartographer/sensor/range_data.h" #include "glog/logging.h" namespace cartographer { namespace mapping_3d { namespace { struct PixelData { int min_z = INT_MAX; int max_z = INT_MIN; int count = 0; float probability_sum = 0.f; float max_probability = 0.5f; }; // Filters 'range_data', retaining only the returns that have no more than // 'max_range' distance from the origin. Removes misses and reflectivity // information. sensor::RangeData FilterRangeDataByMaxRange(const sensor::RangeData& range_data, const float max_range) { sensor::RangeData result{range_data.origin, {}, {}}; for (const Eigen::Vector3f& hit : range_data.returns) { if ((hit - range_data.origin).norm() <= max_range) { result.returns.push_back(hit); } } return result; } std::vector<PixelData> AccumulatePixelData( const int width, const int height, const Eigen::Array2i& min_index, const Eigen::Array2i& max_index, const std::vector<Eigen::Array4i>& voxel_indices_and_probabilities) { std::vector<PixelData> accumulated_pixel_data(width * height); for (const Eigen::Array4i& voxel_index_and_probability : voxel_indices_and_probabilities) { const Eigen::Array2i pixel_index = voxel_index_and_probability.head<2>(); if ((pixel_index < min_index).any() || (pixel_index > max_index).any()) { // Out of bounds. This could happen because of floating point inaccuracy. continue; } const int x = max_index.x() - pixel_index[0]; const int y = max_index.y() - pixel_index[1]; PixelData& pixel = accumulated_pixel_data[x * width + y]; ++pixel.count; pixel.min_z = std::min(pixel.min_z, voxel_index_and_probability[2]); pixel.max_z = std::max(pixel.max_z, voxel_index_and_probability[2]); const float probability = mapping::ValueToProbability(voxel_index_and_probability[3]); pixel.probability_sum += probability; pixel.max_probability = std::max(pixel.max_probability, probability); } return accumulated_pixel_data; } // The first three entries of each returned value are a cell_index and the // last is the corresponding probability value. We batch them together like // this to only have one vector and have better cache locality. std::vector<Eigen::Array4i> ExtractVoxelData( const HybridGrid& hybrid_grid, const transform::Rigid3f& transform, Eigen::Array2i* min_index, Eigen::Array2i* max_index) { std::vector<Eigen::Array4i> voxel_indices_and_probabilities; const float resolution_inverse = 1.f / hybrid_grid.resolution(); constexpr float kXrayObstructedCellProbabilityLimit = 0.501f; for (auto it = HybridGrid::Iterator(hybrid_grid); !it.Done(); it.Next()) { const uint16 probability_value = it.GetValue(); const float probability = mapping::ValueToProbability(probability_value); if (probability < kXrayObstructedCellProbabilityLimit) { // We ignore non-obstructed cells. continue; } const Eigen::Vector3f cell_center_submap = hybrid_grid.GetCenterOfCell(it.GetCellIndex()); const Eigen::Vector3f cell_center_global = transform * cell_center_submap; const Eigen::Array4i voxel_index_and_probability( common::RoundToInt(cell_center_global.x() * resolution_inverse), common::RoundToInt(cell_center_global.y() * resolution_inverse), common::RoundToInt(cell_center_global.z() * resolution_inverse), probability_value); voxel_indices_and_probabilities.push_back(voxel_index_and_probability); const Eigen::Array2i pixel_index = voxel_index_and_probability.head<2>(); *min_index = min_index->cwiseMin(pixel_index); *max_index = max_index->cwiseMax(pixel_index); } return voxel_indices_and_probabilities; } // Builds texture data containing interleaved value and alpha for the // visualization from 'accumulated_pixel_data'. string ComputePixelValues( const std::vector<PixelData>& accumulated_pixel_data) { string cell_data; cell_data.reserve(2 * accumulated_pixel_data.size()); constexpr float kMinZDifference = 3.f; constexpr float kFreeSpaceWeight = 0.15f; for (const PixelData& pixel : accumulated_pixel_data) { // TODO(whess): Take into account submap rotation. // TODO(whess): Document the approach and make it more independent from the // chosen resolution. const float z_difference = pixel.count > 0 ? pixel.max_z - pixel.min_z : 0; if (z_difference < kMinZDifference) { cell_data.push_back(0); // value cell_data.push_back(0); // alpha continue; } const float free_space = std::max(z_difference - pixel.count, 0.f); const float free_space_weight = kFreeSpaceWeight * free_space; const float total_weight = pixel.count + free_space_weight; const float free_space_probability = 1.f - pixel.max_probability; const float average_probability = mapping::ClampProbability( (pixel.probability_sum + free_space_probability * free_space_weight) / total_weight); const int delta = 128 - mapping::ProbabilityToLogOddsInteger(average_probability); const uint8 alpha = delta > 0 ? 0 : -delta; const uint8 value = delta > 0 ? delta : 0; cell_data.push_back(value); // value cell_data.push_back((value || alpha) ? alpha : 1); // alpha } return cell_data; } } // namespace proto::SubmapsOptions CreateSubmapsOptions( common::LuaParameterDictionary* parameter_dictionary) { proto::SubmapsOptions options; options.set_high_resolution( parameter_dictionary->GetDouble("high_resolution")); options.set_high_resolution_max_range( parameter_dictionary->GetDouble("high_resolution_max_range")); options.set_low_resolution(parameter_dictionary->GetDouble("low_resolution")); options.set_num_range_data( parameter_dictionary->GetNonNegativeInt("num_range_data")); *options.mutable_range_data_inserter_options() = CreateRangeDataInserterOptions( parameter_dictionary->GetDictionary("range_data_inserter").get()); options.set_initial_map_file_name( parameter_dictionary->GetString("initial_map_file_name")); options.set_initial_map_resolution( parameter_dictionary->GetDouble("initial_map_resolution")); options.set_distance_map_range( parameter_dictionary->GetDouble("distance_map_range")); options.set_using_eskf( parameter_dictionary->GetBool("using_eskf")); CHECK_GT(options.num_range_data(), 0); return options; } Submap::Submap(const int max_num_range_data, const float high_resolution, const float low_resolution, const transform::Rigid3d& local_pose, common::ThreadPool* thread_pool, const double initial_map_resolution, const double distance_map_range, const bool using_octomap) : mapping::Submap(local_pose), high_resolution_hybrid_grid_(high_resolution), low_resolution_hybrid_grid_(low_resolution), thread_pool_(thread_pool), max_num_range_data_(max_num_range_data), distance_map_range_(distance_map_range), using_octomap_(using_octomap) { // std::cout << "using octomap: " << using_octomap_ << std::endl; if(using_octomap_) { // octomap grid shares the high resolution octomap_grid_ = std::shared_ptr<octomap::OcTree>( new octomap::OcTree(initial_map_resolution)); } } Submap::Submap(const mapping::proto::Submap3D& proto) : mapping::Submap(transform::ToRigid3(proto.local_pose())), high_resolution_hybrid_grid_(proto.high_resolution_hybrid_grid()), low_resolution_hybrid_grid_(proto.low_resolution_hybrid_grid()) { SetNumRangeData(proto.num_range_data()); finished_ = proto.finished(); } void Submap::ToProto(mapping::proto::Submap* const proto) const { auto* const submap_3d = proto->mutable_submap_3d(); *submap_3d->mutable_local_pose() = transform::ToProto(local_pose()); submap_3d->set_num_range_data(num_range_data()); submap_3d->set_finished(finished_); *submap_3d->mutable_high_resolution_hybrid_grid() = high_resolution_hybrid_grid().ToProto(); *submap_3d->mutable_low_resolution_hybrid_grid() = low_resolution_hybrid_grid().ToProto(); } void Submap::ToResponseProto( const transform::Rigid3d& global_submap_pose, mapping::proto::SubmapQuery::Response* const response) const { response->set_submap_version(num_range_data()); // Generate an X-ray view through the 'hybrid_grid', aligned to the xy-plane // in the global map frame. const float resolution = high_resolution_hybrid_grid_.resolution(); response->set_resolution(resolution); // Compute a bounding box for the texture. Eigen::Array2i min_index(INT_MAX, INT_MAX); Eigen::Array2i max_index(INT_MIN, INT_MIN); const std::vector<Eigen::Array4i> voxel_indices_and_probabilities = ExtractVoxelData(high_resolution_hybrid_grid_, global_submap_pose.cast<float>(), &min_index, &max_index); const int width = max_index.y() - min_index.y() + 1; const int height = max_index.x() - min_index.x() + 1; response->set_width(width); response->set_height(height); const std::vector<PixelData> accumulated_pixel_data = AccumulatePixelData( width, height, min_index, max_index, voxel_indices_and_probabilities); const string cell_data = ComputePixelValues(accumulated_pixel_data); common::FastGzipString(cell_data, response->mutable_cells()); *response->mutable_slice_pose() = transform::ToProto( global_submap_pose.inverse() * transform::Rigid3d::Translation(Eigen::Vector3d( max_index.x() * resolution, max_index.y() * resolution, global_submap_pose.translation().z()))); } std::shared_ptr<DynamicEDTOctomap> Submap::GetDistanceMap() { CHECK(distmap_grid_ != nullptr); return distmap_grid_; } std::shared_ptr<octomap::OcTree> Submap::GetOctomap() { return octomap_grid_; } void Submap::InsertRangeData(const sensor::RangeData& range_data, const RangeDataInserter& range_data_inserter, const int high_resolution_max_range) { if (finished_) return; if (distance_transformed_) return; // std::cout << "Submap: InsertRangeData" << std::endl; // transform point cloud from global (map) frame to local (submap) frame const sensor::RangeData transformed_range_data = sensor::TransformRangeData( range_data, local_pose().inverse().cast<float>()); if (using_octomap_) { // Schedule a thread to handle octomap and distance map udpate // std::cout << "Scheduling distance map update... \n"; thread_pool_->Schedule([=]() { common::MutexLocker locker(&mutex_); octomap::Pointcloud octomap_cloud; ToOctomapPointCloud(transformed_range_data, octomap_cloud); octomap::point3d sensor_origin(transformed_range_data.origin[0], transformed_range_data.origin[1], transformed_range_data.origin[2]); // octomap_clouds_.push_back(octomap_cloud); // sensor_origins_.push_back(sensor_origin); octomap_grid_->insertPointCloud(octomap_cloud, sensor_origin, octomap::pose6d(0.0,0.0,0.0, 0.0,0.0,0.0)); octomap_grid_->updateInnerOccupancy(); ComputeDistanceMap(); std::cout << "distance map update done... \n"; }); } range_data_inserter.Insert( FilterRangeDataByMaxRange(transformed_range_data, high_resolution_max_range), &high_resolution_hybrid_grid_); range_data_inserter.Insert(transformed_range_data, &low_resolution_hybrid_grid_); SetNumRangeData(num_range_data() + 1); // high_resolution_max_range_ = (high_resolution_max_range_ > // high_resolution_max_range) ? // high_resolution_max_range_: // high_resolution_max_range; } void Submap::ComputeOctomap() { for(size_t cloud_index = 0; cloud_index < octomap_clouds_.size(); ++cloud_index) { // Insert range data into octomap_grid_ octomap_grid_->insertPointCloud(octomap_clouds_[cloud_index], sensor_origins_[cloud_index], octomap::pose6d(0.0,0.0,0.0, 0.0,0.0,0.0)); } // std::cout << "number of clouds: " << octomap_clouds_.size() << std::endl; octomap_grid_->updateInnerOccupancy(); // std::cout << "update inner occupancy" << std::endl; // octomap_grid_->writeBinaryConst(std::string("/home/aeroscout/carto.bt")); // std::cout << "local pose:\n"; // std::cout << local_pose().translation() << std::endl; // std::cout << local_pose().rotation().w() << "\n" // << local_pose().rotation().x() << "\n" // << local_pose().rotation().y() << "\n" // << local_pose().rotation().z() << std::endl; } void Submap::LoadOctomap(const std::string map_file_name) { // std::string map_file_name = // std::string("/home/aeroscout/Documents/tunnel_sim/tunnel_sim.bt"); std::fstream map_file(map_file_name.c_str(), std::ios_base::binary | std::ios_base::in); if (map_file.is_open()) { octomap_grid_->readBinary(map_file_name); if(octomap_grid_.get()) { if(!octomap_grid_ || octomap_grid_->size() <= 1) { exit(-1); } } map_file.close(); } else { LOG(ERROR) << "Octomap file " << map_file_name << " not open."; exit(-1); } } void Submap::ComputeDistanceMap() { if (distance_transformed_) return; if (distmap_grid_ == nullptr) { double max_distance = 2.0; double min_x, min_y, min_z; double max_x, max_y, max_z; octomap_grid_->getMetricMin(min_x, min_y, min_z); octomap_grid_->getMetricMax(max_x, max_y, max_z); min_x = min_y = -distance_map_range_; max_x = max_y = distance_map_range_; bounding_box_ = {min_x, min_y, min_z, max_x, max_y, max_z}; octomap::point3d bound_min(min_x - max_distance, min_y - max_distance, min_z - max_distance); octomap::point3d bound_max(max_x + max_distance, max_y + max_distance, max_z + max_distance); std::cout << "distmap min size: [" << bound_min(0) << ", " << bound_min(1) << ", " << bound_min(2) << "]" << std::endl; std::cout << "distmap max size: [" << bound_max(0) << ", " << bound_max(1) << ", " << bound_max(2) << "]" << std::endl; distmap_grid_ = std::shared_ptr<DynamicEDTOctomap>( new DynamicEDTOctomap(max_distance, octomap_grid_.get(), bound_min, bound_max, false)); } // std::cout<< "distmap defined" << std::endl; distmap_grid_->update(); if (finished_) { distance_transformed_ = true; // std::cout << "labeling submap transformed.\n"; } // std::cout << "update distance map" << std::endl; // CHECK(!distance_transformed_); // distance_transformed_ = true; // std::cout << "Distance map updated!"; // std::cout << "Distance map local pose:" << std::endl; // std::cout << local_pose().translation() << std::endl; // std::cout << local_pose().rotation().w() << " " // << local_pose().rotation().x() << " " // << local_pose().rotation().y() << " " // << local_pose().rotation().z() << std::endl; } std::vector<double> Submap::GetDistanceMapBoundingBox() { return bounding_box_; } void Submap::ToOctomapPointCloud(const sensor::RangeData& range_data, octomap::Pointcloud& octomap_cloud) { for(auto point : range_data.returns) { // TODO: Check range octomap_cloud.push_back(point[0], point[1], point[2]); } } void Submap::Finish() { CHECK(!finished_); finished_ = true; } ActiveSubmaps::ActiveSubmaps(const proto::SubmapsOptions& options, common::ThreadPool* thread_pool) : options_(options), thread_pool_(thread_pool), range_data_inserter_(options.range_data_inserter_options()) { // We always want to have at least one submap which we can return and will // create it at the origin in absence of a better choice. // // TODO(whess): Start with no submaps, so that all of them can be // approximately gravity aligned. // std::cout << "ActiveSubmaps::ActiveSubmaps()::Initializing" << std::endl; transform::Rigid3d initial_matching_transform( Eigen::Vector3d(0.0,0.0,0.0), Eigen::Quaterniond(1.0,0.0,0.0,0.0)); if (options_.using_eskf()) { matching_submap_ = std::shared_ptr<Submap>( new Submap(options_.num_range_data(), options_.high_resolution(), options_.low_resolution(), initial_matching_transform, thread_pool_, options_.initial_map_resolution(), options_.distance_map_range(), options_.using_eskf())); matching_submap_->LoadOctomap(options_.initial_map_file_name()); matching_submap_->ComputeDistanceMap(); } AddSubmap(initial_matching_transform); } std::vector<std::shared_ptr<Submap>> ActiveSubmaps::submaps() const { return submaps_; } int ActiveSubmaps::matching_index() const { return matching_submap_index_; } std::shared_ptr<Submap> ActiveSubmaps::GetMatchingSubmap() { // CHECK(matching_submap_ != nullptr); return matching_submap_; } transform::Rigid3d ActiveSubmaps::GetMatchingSubmapLocalPose() { if (matching_submap_ != nullptr) { return matching_submap_->local_pose(); } else { return transform::Rigid3d::Identity(); } } std::vector<double> ActiveSubmaps::GetMatchingSubmapBoundingBox() { if (matching_submap_ != nullptr) { return matching_submap_->GetDistanceMapBoundingBox(); } else { std::vector<double> empty_vector; return empty_vector; } } void ActiveSubmaps::InsertRangeData( const sensor::RangeData& range_data, const Eigen::Quaterniond& gravity_alignment) { int cnt = 0; for (auto& submap : submaps_) { if (!submap->distance_transformed()) { // std::cout << cnt << "/" << submaps_.size() << " is not transformed.\n"; submap->InsertRangeData(range_data, range_data_inserter_, options_.high_resolution_max_range()); } cnt++; } // std::cout << "active submap size: " << submaps_.size() << std::endl; // std::cout << "active submaps end: num_range_data " // << submaps_.back()->num_range_data() << std::endl; if (submaps_.back()->num_range_data() == options_.num_range_data()) { AddSubmap(transform::Rigid3d(range_data.origin.cast<double>(), // gravity_alignment)); Eigen::Quaterniond::Identity())); } } void ActiveSubmaps::AddSubmap(const transform::Rigid3d& local_pose) { common::MutexLocker locker(&mutex_); if (submaps_.size() > 1) { CHECK_EQ(submaps_.size(), 2); submaps_.front()->Finish(); if (options_.using_eskf()) { // Schedule a thread to handle octomap and distance map udpate std::cout << "Scheduling final distance map update..." << std::endl; thread_pool_->Schedule([=]() { // Wait for all distance updates done then close the submap while (true) { common::MutexLocker locker(&mutex_); if (submaps_.front()->distance_transformed()) { submaps_.erase(submaps_.begin()); std::cout << "old active submap is deleted" << std::endl; // Set matching submap to new front matching_submap_ = submaps_.front(); CHECK(matching_submap_ != nullptr); CHECK(matching_submap_->GetDistanceMap() != nullptr); break; } // std::cout << "while loop: waiting ...\n"; } }); } else { submaps_.erase(submaps_.begin()); } ++matching_submap_index_; } // std::cout << "using eskf" << options_.using_eskf() << std::endl; submaps_.emplace_back(new Submap(options_.num_range_data(), options_.high_resolution(), options_.low_resolution(), local_pose, thread_pool_, options_.initial_map_resolution(), options_.distance_map_range(), options_.using_eskf())); LOG(INFO) << "Added submap " << matching_submap_index_ + submaps_.size(); } } // namespace mapping_3d } // namespace cartographer
40.38
80
0.644513
[ "vector", "transform" ]
ab2bde292f26d6e46db6a483e6bf0455c2877ccc
12,347
cpp
C++
igl/copyleft/cgal/intersect_other.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/copyleft/cgal/intersect_other.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/copyleft/cgal/intersect_other.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "intersect_other.h" #include "CGAL_includes.hpp" #include "mesh_to_cgal_triangle_list.h" #include "remesh_intersections.h" #include "../../slice_mask.h" #include "../../remove_unreferenced.h" #ifndef IGL_FIRST_HIT_EXCEPTION #define IGL_FIRST_HIT_EXCEPTION 10 #endif // Un-exposed helper functions namespace igl { namespace copyleft { namespace cgal { template <typename DerivedF> static IGL_INLINE void push_result( const Eigen::PlainObjectBase<DerivedF> & F, const int f, const int f_other, const CGAL::Object & result, std::map< typename DerivedF::Index, std::vector<std::pair<typename DerivedF::Index, CGAL::Object> > > & offending) //std::map< // std::pair<typename DerivedF::Index,typename DerivedF::Index>, // std::vector<typename DerivedF::Index> > & edge2faces) { typedef typename DerivedF::Index Index; typedef std::pair<Index,Index> EMK; if(offending.count(f) == 0) { // first time marking, initialize with new id and empty list offending[f] = {}; for(Index e = 0; e<3;e++) { // append face to edge's list Index i = F(f,(e+1)%3) < F(f,(e+2)%3) ? F(f,(e+1)%3) : F(f,(e+2)%3); Index j = F(f,(e+1)%3) < F(f,(e+2)%3) ? F(f,(e+2)%3) : F(f,(e+1)%3); //edge2faces[EMK(i,j)].push_back(f); } } offending[f].push_back({f_other,result}); } template < typename Kernel, typename DerivedVA, typename DerivedFA, typename DerivedVB, typename DerivedFB, typename DerivedIF, typename DerivedVVAB, typename DerivedFFAB, typename DerivedJAB, typename DerivedIMAB> static IGL_INLINE bool intersect_other_helper( const Eigen::PlainObjectBase<DerivedVA> & VA, const Eigen::PlainObjectBase<DerivedFA> & FA, const Eigen::PlainObjectBase<DerivedVB> & VB, const Eigen::PlainObjectBase<DerivedFB> & FB, const RemeshSelfIntersectionsParam & params, Eigen::PlainObjectBase<DerivedIF> & IF, Eigen::PlainObjectBase<DerivedVVAB> & VVAB, Eigen::PlainObjectBase<DerivedFFAB> & FFAB, Eigen::PlainObjectBase<DerivedJAB> & JAB, Eigen::PlainObjectBase<DerivedIMAB> & IMAB) { using namespace std; using namespace Eigen; typedef typename DerivedFA::Index Index; // 3D Primitives typedef CGAL::Point_3<Kernel> Point_3; typedef CGAL::Segment_3<Kernel> Segment_3; typedef CGAL::Triangle_3<Kernel> Triangle_3; typedef CGAL::Plane_3<Kernel> Plane_3; typedef CGAL::Tetrahedron_3<Kernel> Tetrahedron_3; // 2D Primitives typedef CGAL::Point_2<Kernel> Point_2; typedef CGAL::Segment_2<Kernel> Segment_2; typedef CGAL::Triangle_2<Kernel> Triangle_2; // 2D Constrained Delaunay Triangulation types typedef CGAL::Triangulation_vertex_base_2<Kernel> TVB_2; typedef CGAL::Constrained_triangulation_face_base_2<Kernel> CTAB_2; typedef CGAL::Triangulation_data_structure_2<TVB_2,CTAB_2> TDS_2; typedef CGAL::Exact_intersections_tag Itag; // Axis-align boxes for all-pairs self-intersection detection typedef std::vector<Triangle_3> Triangles; typedef typename Triangles::iterator TrianglesIterator; typedef typename Triangles::const_iterator TrianglesConstIterator; typedef CGAL::Box_intersection_d::Box_with_handle_d<double,3,TrianglesIterator> Box; typedef std::map<Index,std::vector<std::pair<Index,CGAL::Object> > > OffendingMap; typedef std::map<std::pair<Index,Index>,std::vector<Index> > EdgeMap; typedef std::pair<Index,Index> EMK; Triangles TA,TB; // Compute and process self intersections mesh_to_cgal_triangle_list(VA,FA,TA); mesh_to_cgal_triangle_list(VB,FB,TB); // http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Box_intersection_d/Chapter_main.html#Section_63.5 // Create the corresponding vector of bounding boxes std::vector<Box> A_boxes,B_boxes; const auto box_up = [](Triangles & T, std::vector<Box> & boxes) -> void { boxes.reserve(T.size()); for ( TrianglesIterator tit = T.begin(); tit != T.end(); ++tit) { boxes.push_back(Box(tit->bbox(), tit)); } }; box_up(TA,A_boxes); box_up(TB,B_boxes); OffendingMap offendingA,offendingB; //EdgeMap edge2facesA,edge2facesB; std::list<int> lIF; const auto cb = [&](const Box &a, const Box &b) -> void { using namespace std; // index in F and T int fa = a.handle()-TA.begin(); int fb = b.handle()-TB.begin(); const Triangle_3 & A = *a.handle(); const Triangle_3 & B = *b.handle(); if(CGAL::do_intersect(A,B)) { // There was an intersection lIF.push_back(fa); lIF.push_back(fb); if(params.first_only) { throw IGL_FIRST_HIT_EXCEPTION; } if(!params.detect_only) { CGAL::Object result = CGAL::intersection(A,B); push_result(FA,fa,fb,result,offendingA); push_result(FB,fb,fa,result,offendingB); } } }; try{ CGAL::box_intersection_d( A_boxes.begin(), A_boxes.end(), B_boxes.begin(), B_boxes.end(), cb); }catch(int e) { // Rethrow if not FIRST_HIT_EXCEPTION if(e != IGL_FIRST_HIT_EXCEPTION) { throw e; } // Otherwise just fall through } // Convert lIF to Eigen matrix assert(lIF.size()%2 == 0); IF.resize(lIF.size()/2,2); { int i=0; for( list<int>::const_iterator ifit = lIF.begin(); ifit!=lIF.end(); ) { IF(i,0) = (*ifit); ifit++; IF(i,1) = (*ifit); ifit++; i++; } } if(!params.detect_only) { // Obsolete, now remesh_intersections expects a single mesh // remesh_intersections(VA,FA,TA,offendingA,VVA,FFA,JA,IMA); // remesh_intersections(VB,FB,TB,offendingB,VVB,FFB,JB,IMB); // Combine mesh and offending maps DerivedVA VAB(VA.rows()+VB.rows(),3); VAB<<VA,VB; DerivedFA FAB(FA.rows()+FB.rows(),3); FAB<<FA,(FB.array()+VA.rows()); Triangles TAB; TAB.reserve(TA.size()+TB.size()); TAB.insert(TAB.end(),TA.begin(),TA.end()); TAB.insert(TAB.end(),TB.begin(),TB.end()); OffendingMap offending; //offending.reserve(offendingA.size() + offendingB.size()); for (const auto itr : offendingA) { // Remap offenders in FB to FAB auto offenders = itr.second; for(auto & offender : offenders) { offender.first += FA.rows(); } offending[itr.first] = offenders; } for (const auto itr : offendingB) { // Store offenders for FB according to place in FAB offending[FA.rows() + itr.first] = itr.second; } remesh_intersections( VAB,FAB,TAB,offending,params.stitch_all,VVAB,FFAB,JAB,IMAB); } return IF.rows() > 0; } } } } template < typename DerivedVA, typename DerivedFA, typename DerivedVB, typename DerivedFB, typename DerivedIF, typename DerivedVVAB, typename DerivedFFAB, typename DerivedJAB, typename DerivedIMAB> IGL_INLINE bool igl::copyleft::cgal::intersect_other( const Eigen::PlainObjectBase<DerivedVA> & VA, const Eigen::PlainObjectBase<DerivedFA> & FA, const Eigen::PlainObjectBase<DerivedVB> & VB, const Eigen::PlainObjectBase<DerivedFB> & FB, const RemeshSelfIntersectionsParam & params, Eigen::PlainObjectBase<DerivedIF> & IF, Eigen::PlainObjectBase<DerivedVVAB> & VVAB, Eigen::PlainObjectBase<DerivedFFAB> & FFAB, Eigen::PlainObjectBase<DerivedJAB> & JAB, Eigen::PlainObjectBase<DerivedIMAB> & IMAB) { if(params.detect_only) { return intersect_other_helper<CGAL::Epick> (VA,FA,VB,FB,params,IF,VVAB,FFAB,JAB,IMAB); }else { return intersect_other_helper<CGAL::Epeck> (VA,FA,VB,FB,params,IF,VVAB,FFAB,JAB,IMAB); } } IGL_INLINE bool igl::copyleft::cgal::intersect_other( const Eigen::MatrixXd & VA, const Eigen::MatrixXi & FA, const Eigen::MatrixXd & VB, const Eigen::MatrixXi & FB, const bool first_only, Eigen::MatrixXi & IF) { Eigen::MatrixXd VVAB; Eigen::MatrixXi FFAB; Eigen::VectorXi JAB,IMAB; return intersect_other( VA,FA,VB,FB,{true,first_only},IF,VVAB,FFAB,JAB,IMAB); } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template bool igl::copyleft::cgal::intersect_other<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, igl::copyleft::cgal::RemeshSelfIntersectionsParam const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); template bool igl::copyleft::cgal::intersect_other<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, igl::copyleft::cgal::RemeshSelfIntersectionsParam const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); #endif
42.575862
1,231
0.580303
[ "mesh", "geometry", "object", "vector", "3d" ]
ab2cf92e0e616cb53d193c32924a145002665a8b
5,305
cpp
C++
src/swr_app/framework.cpp
flubbe/swr
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
[ "MIT" ]
1
2022-02-15T21:00:31.000Z
2022-02-15T21:00:31.000Z
src/swr_app/framework.cpp
flubbe/swr
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
[ "MIT" ]
null
null
null
src/swr_app/framework.cpp
flubbe/swr
2f09acb9f27a8d5345aaeb6f229f74693a24fcdd
[ "MIT" ]
null
null
null
/** * swr - a software rasterizer * * application framework implementation. * * \author Felix Lubbe * \copyright Copyright (c) 2021 * \license Distributed under the MIT software license (see accompanying LICENSE.txt). */ /* C++ headers. */ #include <mutex> /* other library headers */ #ifndef __linux__ # ifdef __APPLE__ # include <SDL.h> # else # include "SDL.h" # endif #else # include <SDL2/SDL.h> #endif /* platform code. */ #include "../common/platform/platform.h" /* software rasterizer. */ #include "swr/swr.h" /* application framework */ #include "framework.h" namespace swr_app { /* * renderwindow. */ void renderwindow::free_resources() { if(sdl_renderer) { SDL_DestroyRenderer(sdl_renderer); sdl_renderer = nullptr; } if(sdl_window) { SDL_DestroyWindow(sdl_window); sdl_window = nullptr; } } bool renderwindow::create() { if(sdl_window || sdl_renderer) { // either the window is already created or something went very wrong. return false; } sdl_window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, SDL_WINDOW_SHOWN); if(!sdl_window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Window creation failed: %s\n", SDL_GetError()); return false; } auto surface = SDL_GetWindowSurface(sdl_window); sdl_renderer = SDL_CreateSoftwareRenderer(surface); if(!sdl_renderer) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Render creation for surface failed: %s\n", SDL_GetError()); SDL_DestroyWindow(sdl_window); sdl_window = nullptr; return false; } /* Clear the rendering surface with the specified color */ SDL_SetRenderDrawColor(sdl_renderer, 0xff, 0xff, 0xff, 0xff); SDL_RenderClear(sdl_renderer); return true; } bool renderwindow::get_surface_buffer_rgba32(std::vector<uint32_t>& contents) const { if(!sdl_window) { return false; } auto surface = SDL_GetWindowSurface(sdl_window); contents.clear(); contents.reserve(surface->w * surface->h * 4); /* 4 bytes per pixel; RGBA */ if(surface->format->BytesPerPixel < 1 || surface->format->BytesPerPixel > 4) { throw std::runtime_error(fmt::format("cannot handle pixel format with {} bytes per pixel", surface->format->BytesPerPixel)); } /* read and convert pixels. */ for(int y = 0; y < surface->h; ++y) { for(int x = 0; x < surface->w; ++x) { Uint8* p = (Uint8*)surface->pixels + y * surface->pitch + x * surface->format->BytesPerPixel; Uint32 pixel{0}; // (if speed was a concern, the branching should happen outside the for-loops) if(surface->format->BytesPerPixel == 1) { pixel = *p; } else if(surface->format->BytesPerPixel == 2) { pixel = *reinterpret_cast<Uint16*>(p); } else if(surface->format->BytesPerPixel == 3) { //!!todo: this needs to be tested. #if SDL_BYTEORDER == SDL_BIG_ENDIAN pixel = p[0] << 16 | p[1] << 8 | p[2]; #else pixel = p[0] | p[1] << 8 | p[2] << 16; #endif } else if(surface->format->BytesPerPixel == 4) { pixel = *reinterpret_cast<Uint32*>(p); } Uint8 r, g, b, a; SDL_GetRGBA(pixel, surface->format, &r, &g, &b, &a); contents.push_back((r << 24) | (g << 16) | (b << 8) | a); } } return true; } /* * application. */ /* singleton interface. */ application* application::global_app = nullptr; std::mutex application::global_app_mtx; void application::initialize_instance(int argc, char* argv[]) { assert(global_app != nullptr); // process command-line arguments. global_app->process_cmdline(argc, argv); // platform initialization with log disabled. platform::global_initialize(); if(SDL_WasInit(SDL_INIT_VIDEO) == 0) { /* Enable standard application logging */ if(SDL_LogGetPriority(SDL_LOG_CATEGORY_APPLICATION) != SDL_LOG_PRIORITY_INFO) { SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); } /* Initialize SDL */ if(SDL_Init(SDL_INIT_VIDEO) != 0) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "SDL_Init fail : %s\n", SDL_GetError()); throw std::runtime_error("SDL initialization failed."); } } } void application::shutdown_instance() { // thread-safe shutdown. this prevents multiple threads accessing the singleton at the same time. const std::scoped_lock lock{global_app_mtx}; // shut down SDL if(SDL_WasInit(SDL_INIT_EVERYTHING) != 0) { SDL_Quit(); } // shut down other platform services. platform::global_shutdown(); } bool application::process_cmdline(int argc, char* argv[]) { if(argc < 0 || argv == nullptr) { return false; } // skip the first argument, since it only contains the program's name cmd_args = {argv + 1, argv + argc}; return true; } } /* namespace swr_app */
25.382775
132
0.60886
[ "render", "vector" ]
ab30dc0a6068bde4ee530da6a2cdb5e12ea344ee
6,564
cpp
C++
data-server/test/unittest/range_ddl_unittest.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
1
2021-08-11T02:31:52.000Z
2021-08-11T02:31:52.000Z
data-server/test/unittest/range_ddl_unittest.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
null
null
null
data-server/test/unittest/range_ddl_unittest.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <fastcommon/shared_func.h> #include <common/ds_config.h> #include "helper/cpp_permission.h" #include "base/status.h" #include "base/util.h" #include "common/ds_config.h" #include "frame/sf_util.h" #include "range/range.h" #include "server/range_server.h" #include "server/run_status.h" #include "storage/store.h" #include "proto/gen/schpb.pb.h" #include "helper/table.h" #include "helper/mock/raft_server_mock.h" #include "helper/mock/socket_session_mock.h" int main(int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } char level[8] = "debug"; using namespace sharkstore::test::helper; using namespace sharkstore::dataserver; using namespace sharkstore::dataserver::storage; class DdlTest : public ::testing::Test { protected: void SetUp() override { log_init2(); set_log_level(level); strcpy(ds_config.rocksdb_config.path, "/tmp/sharkstore_ds_store_test_"); strcat(ds_config.rocksdb_config.path, std::to_string(getticks()).c_str()); ds_config.range_config.recover_concurrency = 1; range_server_ = new server::RangeServer; context_ = new server::ContextServer; context_->node_id = 1; context_->range_server = range_server_; context_->socket_session = new SocketSessionMock; context_->raft_server = new RaftServerMock; context_->run_status = new server::RunStatus; range_server_->Init(context_); } void TearDown() override { delete context_->range_server; delete context_->socket_session; delete context_->raft_server; delete context_; } protected: server::ContextServer *context_; server::RangeServer *range_server_; }; metapb::Range *genRange() { auto meta = new metapb::Range; meta->set_id(1); meta->set_start_key("01003"); meta->set_end_key("01004"); meta->mutable_range_epoch()->set_conf_ver(1); meta->mutable_range_epoch()->set_version(1); meta->set_table_id(1); auto peer = meta->add_peers(); peer->set_id(1); peer->set_node_id(1); auto pks = CreateAccountTable()->GetPKs(); for (const auto& pk : pks) { auto p = meta->add_primary_keys(); p->CopyFrom(pk); } return meta; } TEST_F(DdlTest, Ddl) { { // begin test create range auto msg = new common::ProtoMessage; schpb::CreateRangeRequest req; req.set_allocated_range(genRange()); auto len = req.ByteSizeLong(); msg->body.resize(len); ASSERT_TRUE(req.SerializeToArray(msg->body.data(), len)); range_server_->CreateRange(msg); ASSERT_FALSE(range_server_->ranges_.empty()); ASSERT_TRUE(range_server_->Find(1) != nullptr); std::vector<metapb::Range> metas; auto ret = range_server_->meta_store_->GetAllRange(&metas); ASSERT_TRUE(metas.size() == 1) << metas.size(); // end test create range } { // begin test create range (repeat) auto msg = new common::ProtoMessage; schpb::CreateRangeRequest req; req.set_allocated_range(genRange()); auto len = req.ByteSizeLong(); msg->body.resize(len); ASSERT_TRUE(req.SerializeToArray(msg->body.data(), len)); range_server_->CreateRange(msg); ASSERT_FALSE(range_server_->ranges_.empty()); ASSERT_TRUE(range_server_->Find(1) != nullptr); schpb::CreateRangeResponse resp; auto session_mock = static_cast<SocketSessionMock *>(context_->socket_session); ASSERT_TRUE(session_mock->GetResult(&resp)); ASSERT_FALSE(resp.header().has_error()); // test meta_store std::vector<metapb::Range> metas; auto ret = range_server_->meta_store_->GetAllRange(&metas); ASSERT_TRUE(metas.size() == 1) << metas.size(); // end test create range } { // begin test create range (repeat but epoch stale) auto msg = new common::ProtoMessage; schpb::CreateRangeRequest req; auto meta = genRange(); meta->mutable_range_epoch()->set_version(2); req.set_allocated_range(meta); auto len = req.ByteSizeLong(); msg->body.resize(len); ASSERT_TRUE(req.SerializeToArray(msg->body.data(), len)); range_server_->CreateRange(msg); ASSERT_FALSE(range_server_->ranges_.empty()); ASSERT_TRUE(range_server_->Find(1) != nullptr); schpb::CreateRangeResponse resp; auto session_mock = static_cast<SocketSessionMock *>(context_->socket_session); ASSERT_TRUE(session_mock->GetResult(&resp)); ASSERT_TRUE(resp.header().has_error()); ASSERT_TRUE(resp.header().error().has_stale_range()); // test meta_store std::vector<metapb::Range> metas; auto ret = range_server_->meta_store_->GetAllRange(&metas); ASSERT_TRUE(metas.size() == 1) << metas.size(); // end test create range } { // begin test delete range auto msg = new common::ProtoMessage; schpb::DeleteRangeRequest req; req.set_range_id(1); auto len = req.ByteSizeLong(); msg->body.resize(len); ASSERT_TRUE(req.SerializeToArray(msg->body.data(), len)); range_server_->DeleteRange(msg); ASSERT_TRUE(range_server_->ranges_.empty()); ASSERT_TRUE(range_server_->Find(1) == nullptr); schpb::DeleteRangeResponse resp; auto session_mock = static_cast<SocketSessionMock *>(context_->socket_session); ASSERT_TRUE(session_mock->GetResult(&resp)); ASSERT_FALSE(resp.header().has_error()); // test meta_store std::vector<metapb::Range> metas; auto ret = range_server_->meta_store_->GetAllRange(&metas); ASSERT_TRUE(metas.size() == 0) << metas.size(); // end test delete range } { // begin test delete range (not exist) auto msg = new common::ProtoMessage; schpb::DeleteRangeRequest req; req.set_range_id(1); auto len = req.ByteSizeLong(); msg->body.resize(len); ASSERT_TRUE(req.SerializeToArray(msg->body.data(), len)); range_server_->DeleteRange(msg); schpb::DeleteRangeResponse resp; auto session_mock = static_cast<SocketSessionMock *>(context_->socket_session); ASSERT_TRUE(session_mock->GetResult(&resp)); ASSERT_FALSE(resp.header().has_error()); // end test delete range } }
29.173333
87
0.641987
[ "vector" ]
ab331bdcd31df6d695679102b765155a1df8047e
1,403
cpp
C++
codeforces/C - Primes and Multiplication/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Primes and Multiplication/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Primes and Multiplication/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Sep/29/2019 19:47 * solution_verdict: Accepted language: GNU C++14 * run_time: 31 ms memory_used: 0 KB * problem: https://codeforces.com/contest/1228/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const long N=1e3,mod=1e9+7; vector<long>v; long big(long b,long p) { long ret=1; while(p) { if(p%2)ret=(1LL*ret*b)%mod; b=(1LL*b*b)%mod;p/=2; } return ret; } void facto(long x) { long sq=sqrt(x+2); for(long i=2;i<=sq;i++) { if(x%i==0) { v.push_back(i); while(x%i==0)x/=i; } } if(x>1)v.push_back(x); sort(v.begin(),v.end()); v.erase(unique(v.begin(),v.end()),v.end()); } int main() { ios_base::sync_with_stdio(0);cin.tie(0); long x;long n;cin>>x>>n;facto(x); long ans=1; for(auto x:v) { long nm=x;//cout<<"*"<<x<<endl; while(true) { long cnt=n/nm;if(cnt==0)break; ans=(ans*(big(x,cnt)))%mod; if(n/nm<x)break; nm=nm*x; } } cout<<ans<<endl; return 0; }
25.509091
111
0.416251
[ "vector" ]
ab38e8c377d6d419a326f6b51694d74ccadd4209
6,146
cc
C++
src/asp/IsisIO/IsisInterfaceMapLineScan.cc
nasa/StereoPipeline
8b9c0bcab258c41d10cb2973d97722765072a7bf
[ "NASA-1.3" ]
29
2015-05-06T01:28:21.000Z
2021-12-19T22:55:29.000Z
src/asp/IsisIO/IsisInterfaceMapLineScan.cc
imagineagents/StereoPipeline
8b9c0bcab258c41d10cb2973d97722765072a7bf
[ "NASA-1.3" ]
null
null
null
src/asp/IsisIO/IsisInterfaceMapLineScan.cc
imagineagents/StereoPipeline
8b9c0bcab258c41d10cb2973d97722765072a7bf
[ "NASA-1.3" ]
27
2015-01-15T04:20:50.000Z
2020-01-10T01:31:17.000Z
// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ // ASP #include <vw/Cartography/SimplePointImageManipulation.h> #include <vw/Camera/CameraModel.h> #include <vw/Math/LevenbergMarquardt.h> #include <asp/IsisIO/IsisInterfaceMapLineScan.h> // ISIS #include <ProjectionFactory.h> #include <iTime.h> #include <Latitude.h> #include <Longitude.h> using namespace vw; using namespace asp; using namespace asp::isis; // Constructor IsisInterfaceMapLineScan::IsisInterfaceMapLineScan( std::string const& filename ) : IsisInterface( filename ), m_projection( Isis::ProjectionFactory::CreateFromCube(m_label) ) { // Gutting Isis::Camera m_distortmap = m_camera->DistortionMap(); m_groundmap = m_camera->GroundMap(); m_focalmap = m_camera->FocalPlaneMap(); m_cache_px[0] = m_cache_px[1] = std::numeric_limits<double>::quiet_NaN(); } // Custom Functions class EphemerisLMA : public vw::math::LeastSquaresModelBase<EphemerisLMA> { vw::Vector3 m_point; Isis::Camera* m_camera; Isis::CameraDistortionMap *m_distortmap; Isis::CameraFocalPlaneMap *m_focalmap; public: typedef vw::Vector<double> result_type; // Back project result typedef vw::Vector<double> domain_type; // Ephemeris time typedef vw::Matrix<double> jacobian_type; inline EphemerisLMA( vw::Vector3 const& point, Isis::Camera* camera, Isis::CameraDistortionMap* distortmap, Isis::CameraFocalPlaneMap* focalmap ) : m_point(point), m_camera(camera), m_distortmap(distortmap), m_focalmap(focalmap) {} inline result_type operator()( domain_type const& x ) const; }; // LMA for projecting point to linescan camera EphemerisLMA::result_type EphemerisLMA::operator()( EphemerisLMA::domain_type const& x ) const { // Setting Ephemeris Time m_camera->SetTime( Isis::iTime( x[0] )); // Calculating the look direction in camera frame Vector3 instru; m_camera->InstrumentPosition(&instru[0]); instru *= 1000; // Spice gives in km Vector3 lookB = normalize( m_point - instru ); std::vector<double> lookB_copy(3); std::copy(lookB.begin(),lookB.end(),lookB_copy.begin()); std::vector<double> lookJ = m_camera->BodyRotation()->J2000Vector(lookB_copy); std::vector<double> lookC = m_camera->InstrumentRotation()->ReferenceVector(lookJ); Vector3 look; std::copy(lookC.begin(),lookC.end(),look.begin()); // Projecting to mm focal plane look = m_camera->FocalLength() * (look / look[2]); m_distortmap->SetUndistortedFocalPlane(look[0], look[1]); m_focalmap->SetFocalPlane( m_distortmap->FocalPlaneX(), m_distortmap->FocalPlaneY() ); result_type result(1); // Not exactly sure about lineoffset .. but ISIS does it result[0] = m_focalmap->DetectorLineOffset() - m_focalmap->DetectorLine(); return result; } Vector2 IsisInterfaceMapLineScan::point_to_pixel( Vector3 const& point ) const { // First seed LMA with an ephemeris time in the middle of the image double middle_et = m_camera->CacheStartTime().Et() + (m_camera->CacheEndTime().Et()-m_camera->CacheStartTime().Et())/2.0; // Build LMA EphemerisLMA model( point, m_camera.get(), m_distortmap, m_focalmap ); int status; Vector<double> objective(1), start(1); start[0] = middle_et; Vector<double> solution_e = math::levenberg_marquardt( model, start, objective, status ); // Make sure we found ideal time VW_ASSERT( status > 0, camera::PointToPixelErr() << " Unable to project point into linescan camera " ); // Setting to camera time to solution m_camera->SetTime( Isis::iTime( solution_e[0] ) ); // Working out pointing Vector3 center; m_camera->InstrumentPosition(&center[0]); Vector3 look = normalize(point-1000*center); // Calculating Rotation to camera frame std::vector<double> rot_inst = m_camera->InstrumentRotation()->Matrix(); std::vector<double> rot_body = m_camera->BodyRotation()->Matrix(); MatrixProxy<double,3,3> R_inst(&(rot_inst[0])); MatrixProxy<double,3,3> R_body(&(rot_body[0])); look = transpose(R_body*transpose(R_inst))*look; look = m_camera->FocalLength() * (look / look[2]); // Projecting back on to ground to find out time m_groundmap->SetFocalPlane( look[0], look[1], look[2] ); m_projection->SetGround( m_camera->UniversalLatitude(), m_camera->UniversalLongitude() ); m_cache_px = Vector2( m_projection->WorldX()-1, m_projection->WorldY()-1 ); return m_cache_px; } Vector3 IsisInterfaceMapLineScan::camera_center( Vector2 const& px ) const { if ( px != m_cache_px ) { m_cache_px = px; if (!m_projection->SetWorld( px[0]+1, px[1]+1 )) vw_throw( camera::PixelToRayErr() << "Failed to SetWorld." ); if (!m_groundmap->SetGround( Isis::Latitude(m_projection->UniversalLatitude(),Isis::Angle::Degrees), Isis::Longitude(m_projection->UniversalLongitude(),Isis::Angle::Degrees) ) ) vw_throw( camera::PixelToRayErr() << "Failed to SetGround." ); } Vector3 position; m_camera->InstrumentPosition( &position[0] ); return position * 1e3; } Vector3 IsisInterfaceMapLineScan::pixel_to_vector( Vector2 const& px ) const { Vector3 sB = camera_center( px ); Vector3 p_pB; m_camera->Sensor::Coordinate( &p_pB[0] ); return normalize(p_pB*1000 - sB); } Quat IsisInterfaceMapLineScan::camera_pose( Vector2 const& px ) const { camera_center( px ); std::vector<double> rot_inst = m_camera->InstrumentRotation()->Matrix(); std::vector<double> rot_body = m_camera->BodyRotation()->Matrix(); MatrixProxy<double,3,3> R_inst(&(rot_inst[0])); MatrixProxy<double,3,3> R_body(&(rot_body[0])); return Quat(R_body*transpose(R_inst)); }
36.583333
146
0.673283
[ "vector", "model" ]
ab3b094bee02a318594e0355d744e9fc1c0e89b8
6,927
cpp
C++
DebugTool/source/DebugPlotViewer/SeriesText.cpp
Bhaskers-Blu-Org2/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
270
2015-07-17T15:43:43.000Z
2019-04-21T12:13:58.000Z
DebugTool/source/DebugPlotViewer/SeriesText.cpp
JamesLinus/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
null
null
null
DebugTool/source/DebugPlotViewer/SeriesText.cpp
JamesLinus/Sora
6aa5411db71199e56d5cb24265b01a89f49b40f4
[ "BSD-2-Clause" ]
106
2015-07-20T10:40:34.000Z
2019-04-25T10:02:26.000Z
#include "stdafx.h" #include "SeriesText.h" //#include "DebugPlotViewerDoc.h" #include "TextSeriesProperty.h" #include "SubPlotWnd.h" #include "HelperFunc.h" #include "AppMessage.h" /*********************************** Text Series ***********************************/ HRESULT TextSeriesProp::CreateElementSeries(IXMLDOMDocument *pDom, IXMLDOMElement *pe) { IXMLDOMElement *pssub=NULL; HRESULT hr=S_OK; CreateAndAddElementNode(pDom, L"SName", L"\n\t\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->name); //pssub->Release(); CreateAndAddElementNode(pDom, L"SType", L"\n\t\t\t", pe, &pssub); pssub->put_text(_bstr_t(typeid(*this).name())); //pssub->Release(); //CreateAndAddElementNode(pDom, L"colorIsSet", L"\n\t\t\t", pe, &pssub); //pssub->put_text((_bstr_t)this->colorIsSet); CreateAndAddElementNode(pDom, L"IsLog", L"\n\t\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->isLog); //pssub->Release(); CreateAndAddElementNode(pDom, L"color", L"\n\t\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->color); CreateAndAddElementNode(pDom, L"replaceMode", L"\n\t\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->replaceMode); CreateAndAddElementNode(pDom, L"subRectTLX", L"\n\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->rect.TopLeft().x); CreateAndAddElementNode(pDom, L"subRectTLY", L"\n\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->rect.TopLeft().y); CreateAndAddElementNode(pDom, L"subRectBRX", L"\n\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->rect.BottomRight().x); CreateAndAddElementNode(pDom, L"subRectBRY", L"\n\t\t", pe, &pssub); pssub->put_text((_bstr_t)this->rect.BottomRight().y); return hr; } TextSeriesProp::TextSeriesProp() { isLog = false; replaceMode = true; //colorIsSet = false; color = RGB(0, 255, 0); // green; _ringBuffer = new RingBufferWithTimeStamp<char>(1*1024*1024); _writeFilter = new SoraDbgPlot::FrameWithSizeInfoWriter<char>(_ringBuffer); _latestTimeIdx = 0; _dataRange = 1; ::InitializeCriticalSection(&csLogBuf); } TextSeriesProp::~TextSeriesProp() { ::DeleteCriticalSection(&csLogBuf); delete _writeFilter; delete _ringBuffer; } BaseProperty * TextSeriesProp::GetPropertyPage() { BaseProperty * property = new TextSeriesProperty; property->SetTarget(this); return property; } void TextSeriesProp::Close() { CWnd * targetWnd = this->GetTargetWnd(); if (targetWnd) { LRESULT destroyed = targetWnd->SendMessage(WM_APP, CMD_SERIES_CLOSED, 0); if (! destroyed) { targetWnd->PostMessage(WM_APP, CMD_DATA_CLEAR, (LPARAM)this); targetWnd->InvalidateRgn(NULL, 1); } SetTargetWnd(0); } SeriesProp::Close(); } //void TextSeriesProp::UpdateView() //{ // if (!isLog) // SeriesProp::UpdateView(); // else // { // SharedSeriesInfo * sharedSeriesInfo = (SharedSeriesInfo *)this->smSeriesInfo->GetAddress(); // if (sharedSeriesInfo->dataElementSize == 0) // return; // // char * dataAddr = (char *)this->smSeriesData->GetAddress(); // // int wIdx = sharedSeriesInfo->wIdx; // int rIdx = sharedSeriesInfo->rIdx; // // int bufLen = sharedSeriesInfo->bufLen; // bufLen = bufLen - bufLen % sharedSeriesInfo->dataElementSize; // // if (sharedSeriesInfo->replace) // sharedSeriesInfo->rIdx = 0; // else // sharedSeriesInfo->rIdx = wIdx; // // int dataLen = wIdx - rIdx; // if (dataLen < 0) // { // dataLen += bufLen; // } // // if (dataLen >= 0) // { // char * dataBuf = new char[dataLen+1]; // // for (int i = 0; i < dataLen; i++) // { // dataBuf[i] = dataAddr[(rIdx+i)%bufLen]; // } // // dataBuf[dataLen] = 0; // // CString newStr(dataBuf); // // ::EnterCriticalSection(&csLogBuf); // if (logBuf.GetLength() < 32*1024) // logBuf.Append(newStr); // ::LeaveCriticalSection(&csLogBuf); // // delete [] dataBuf; // } // } //} void TextSeriesProp::Write(const void * ptr, size_t length) { size_t dummy; _writeFilter->Write(ptr, length, dummy); } size_t TextSeriesProp::DataSize() { return _ringBuffer->RecordCount(); } void TextSeriesProp::SeekTimeStamp(const std::vector<unsigned long long> & vecTimeStamp) { bool taken = false; unsigned long long timestampOldest; size_t idxOldest; std::for_each( vecTimeStamp.begin(), vecTimeStamp.end(), [&taken, &timestampOldest, &idxOldest, this] (unsigned long long in) { unsigned long long out; size_t outIdx; bool found = this->_ringBuffer->GetNearestOldTimeStamp(in, out, outIdx); if (found) { if (!taken) { taken = true; timestampOldest = out; idxOldest = outIdx; } else { if (timestampOldest > out) { timestampOldest = out; idxOldest = outIdx; } } } }); if (taken) { _latestTimeIdx = idxOldest; _dataRange = 1; } else { _latestTimeIdx = -1; } } void TextSeriesProp::SeekDataRanage(size_t idx, size_t range) { _latestTimeIdx = idx; _dataRange = range; } void TextSeriesProp::UpdateSubWnd() { SubPlotWnd * wnd = dynamic_cast<SubPlotWnd *>(this->GetTargetWnd()); if (wnd) { if (_latestTimeIdx >= 0) { size_t sizeOfData; bool succ = _ringBuffer->GetDataSizeByTimeStampIdx(_latestTimeIdx, sizeOfData); if (succ) { char * data = new char[sizeOfData + 1]; size_t readSize; succ = _ringBuffer->ReadDataByTimeStampIdx(_latestTimeIdx, data, sizeOfData, readSize); if (succ) { data[readSize] = 0; wnd->PlotText(CString(data)); } delete [] data; } } else { wnd->PlotText(CString("")); } } } SubPlotWnd * TextSeriesProp::CreateSubPlotWnd() { auto subWnd = new SubPlotWnd; //subWnd->seriesProp = this; this->SetTargetWnd(subWnd); subWnd->EventMoveWindow.Subscribe([this](const void * sender, const CRect & rect){ this->rect = rect; }); subWnd->StrategyGetColor.Set([this](const void * sender, const int & dummy, COLORREF & color){ color = this->color; //if (this->colorIsSet) // color = this->color; //else // color = RGB(0, 255, 0); }); return subWnd; } char * TextSeriesProp::GetData(size_t index) { size_t dataSize = this->DataSize(); if (dataSize <= index || index < 0) return false; size_t sizeOfData; bool succ = _ringBuffer->GetDataSizeByTimeStampIdx(index, sizeOfData); if (succ) { char * data = new char[sizeOfData + 1]; size_t readSize; succ = _ringBuffer->ReadDataByTimeStampIdx(index, data, sizeOfData, readSize); if (succ) { data[readSize] = 0; return data; } else { delete [] data; return 0; } } else return 0; } void TextSeriesProp::ClearData() { this->_ringBuffer->Reset(); } bool TextSeriesProp::Export(const CString & filename, bool bAll) { FILE * fp; errno_t ret = _wfopen_s(&fp, filename, L"wb"); if (ret == 0) { this->LockData(); if (1) { this->_ringBuffer->Export([fp](const char * ptr, size_t length){ fwrite(ptr, 1, length, fp); }); } this->UnlockData(); fclose(fp); return true; } return false; }
21.183486
95
0.655695
[ "vector" ]
ab465b557c37f993873f3ed6cac0989ad5e8ac9d
1,308
cpp
C++
D3D11Framework/D3D11Framework/RenderTarget.cpp
luca1337/DirectX11Framework
0dfc7da0b5e9e34835996d6cb17649d50beb5e45
[ "MIT" ]
null
null
null
D3D11Framework/D3D11Framework/RenderTarget.cpp
luca1337/DirectX11Framework
0dfc7da0b5e9e34835996d6cb17649d50beb5e45
[ "MIT" ]
null
null
null
D3D11Framework/D3D11Framework/RenderTarget.cpp
luca1337/DirectX11Framework
0dfc7da0b5e9e34835996d6cb17649d50beb5e45
[ "MIT" ]
null
null
null
#include "RenderTarget.h" #include "Texture.h" #include "Engine.h" #include "Device.h" #include "DepthTarget.h" #include "Core.h" RenderTarget::RenderTarget(std::shared_ptr<Texture> texture) : texture(texture) { // a render target view is an object able to receive rasterization // output (like an opengl framebuffer) if (Engine::Singleton().GetDxDevice()->GetDXHandle()->CreateRenderTargetView1(texture->GetDXHandle(), nullptr, &rtv) != S_OK) { throw std::exception("unable to create render target view"); } } void RenderTarget::Bind(std::shared_ptr<DepthTarget> depth_target) { depth_view = nullptr; if (depth_target) { depth_view = depth_target->GetDXHandle(); } // set the rendering area (viewport) D3D11_VIEWPORT viewport = {}; viewport.Width = (float)texture->GetWidth(); viewport.Height = (float)texture->GetHeight(); viewport.MinDepth = 0; viewport.MaxDepth = 1; viewport.TopLeftX = 0; viewport.TopLeftY = 0; Engine::Singleton().GetDxDevice()->GetDXContext()->RSSetViewports(1, &viewport); } void RenderTarget::Clear(std::initializer_list<float> color) { Engine::Singleton().GetDxDevice()->GetDXContext()->ClearRenderTargetView(rtv, color.begin()); Engine::Singleton().GetDxDevice()->GetDXContext()->OMSetRenderTargets(1, (ID3D11RenderTargetView**)&rtv, depth_view); }
29.727273
126
0.735474
[ "render", "object" ]
ab4d79d73ec180ae7c7167a60f038f2bf8a3719f
2,488
cc
C++
CondCore/EcalPlugins/plugins/EcalPyUtils.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CondCore/EcalPlugins/plugins/EcalPyUtils.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CondCore/EcalPlugins/plugins/EcalPyUtils.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
/* * Make some convenient Ecal function available in python * * \author Stefano Argiro * \version $Id: EcalPyUtils.cc,v 1.6 2012/07/17 09:17:11 davidlt Exp $ */ #include "DataFormats/EcalDetId/interface/EBDetId.h" #include "DataFormats/EcalDetId/interface/EEDetId.h" #include "CondTools/Ecal/interface/EcalFloatCondObjectContainerXMLTranslator.h" #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> using namespace boost::python; namespace ecalpyutils{ std::vector<int> hashedIndexToEtaPhi(int hashedindex){ int ieta= EBDetId::unhashIndex(hashedindex).ieta(); int iphi= EBDetId::unhashIndex(hashedindex).iphi(); std::vector<int> ret; ret.push_back(ieta); ret.push_back(iphi); return ret; } std::vector<int> hashedIndexToXY(int hashedindex){ int ix= EEDetId::unhashIndex(hashedindex).ix(); int iy= EEDetId::unhashIndex(hashedindex).iy(); int zside = EEDetId::unhashIndex(hashedindex).zside(); std::vector<int> ret; ret.push_back(ix); ret.push_back(iy); ret.push_back(zside); return ret; } int hashedIndex(int ieta, int iphi){ EBDetId d(ieta,iphi); return d.hashedIndex(); } int hashedIndexEE(int ix, int iy, int iz){ if (EEDetId::validDetId(ix,iy,iz)) { EEDetId d(ix,iy,iz); return d.hashedIndex(); } return 0; } int ism(int ieta, int iphi){ EBDetId d(ieta,iphi); return d.ism(); } std::string arraystoXML(const std::vector<float>& eb, const std::vector<float>& ee){ EcalCondHeader h; return EcalFloatCondObjectContainerXMLTranslator::dumpXML(h,eb,ee); } } BOOST_PYTHON_MODULE(pluginEcalPyUtils) { // looks like these are already defined somewhere // python access to stl integer vectors // class_< std::vector<int> >("vectorInt") // .def(vector_indexing_suite<std::vector<int> >()) // ; // class_< std::vector<float> >("vectorFloat") // .def(vector_indexing_suite<std::vector<float> >()) // ; def("hashedIndexToEtaPhi",&ecalpyutils::hashedIndexToEtaPhi); def("hashedIndexToXY",&ecalpyutils::hashedIndexToXY); def("hashedIndex",&ecalpyutils::hashedIndex); def("hashedIndexEE",&ecalpyutils::hashedIndexEE); def("ism",&ecalpyutils::ism); def("barrelfromXML",&EcalFloatCondObjectContainerXMLTranslator::barrelfromXML); def("endcapfromXML",&EcalFloatCondObjectContainerXMLTranslator::endcapfromXML); def("arraystoXML",&ecalpyutils::arraystoXML); }
27.644444
86
0.701768
[ "vector" ]
ab4ee2c36a4c6716fe98d026bf661ee38b42631d
1,796
cpp
C++
Company-Google/418. Sentence Screen Fitting/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Company-Google/418. Sentence Screen Fitting/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Company-Google/418. Sentence Screen Fitting/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 418. Sentence Screen Fitting // // Created by 边俊林 on 2020/1/7. // Copyright © 2020 边俊林. All rights reserved. // #include <map> #include <set> #include <queue> #include <string> #include <stack> #include <vector> #include <cstdio> #include <numeric> #include <cstdlib> #include <utility> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // // Solution 1: Brute Force, 4ms, beats 90% /* class Solution { public: int wordsTyping(vector<string>& sentence, int rows, int cols) { string pattern = ""; for (auto& str: sentence) pattern += str, pattern += ' '; int p = 0, len = pattern.length(); for (int i = 0; i < rows; ++i) { p += cols; if (pattern[p % len] == ' ') { ++p; } else { while (p > 0 && pattern[p % len] != ' ') { --p; } ++p; } } return p / len; } }; */ // Solution 2: Memo solution, 28ms beats 30% /* class Solution { public: int wordsTyping(vector<string>& sentence, int rows, int cols) { unordered_map<int, int> cnt; int p = 0, n = sentence.size(); for (int i = 0; i < rows; ++i) { if (cnt.count(p % n) > 0) { p += cnt[p % n]; } else { int begp = p, cp = 0, tmp = 0; while (cp + sentence[p % n].length() <= cols) { cp += sentence[p % n].length() + 1; ++p; ++tmp; } p = begp + (cnt[begp % n] = tmp); } } return p / n; } }; */ int main() { return 0; }
21.380952
67
0.454343
[ "vector" ]
ab52e415bb44286bdf693869d661b265cdd989aa
5,719
cpp
C++
device_driver/src/device_driver.cpp
MingshanHe/Dual-Cooperator
e5de191717c1ba4b6df76c8027257f491c003ebe
[ "MIT" ]
1
2022-02-18T05:50:43.000Z
2022-02-18T05:50:43.000Z
device_driver/src/device_driver.cpp
MingshanHe/Dual-Cooperator
e5de191717c1ba4b6df76c8027257f491c003ebe
[ "MIT" ]
1
2021-12-29T13:46:13.000Z
2022-02-21T01:45:46.000Z
device_driver/src/device_driver.cpp
MingshanHe/Dual-Cooperator
e5de191717c1ba4b6df76c8027257f491c003ebe
[ "MIT" ]
null
null
null
/* * device_driver.cpp * * Created on: Jan 7, 2021 * Author: hanbing */ #include "device_hardware/device_hardware.h" #include "device_interface/DeviceDriver/device_timer.h" #include "device_interface/Base/RobotSystem.h" #include <ros/ros.h> #include <ros/node_handle.h> #include <urdf/model.h> #include <controller_manager/controller_manager.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> int main(int argc, char **argv) { ROS_INFO("start ros robot\n"); if (0!=HYYRobotBase::initPriority(38)) { ROS_ERROR_STREAM("program priority set failure!"); return 0; } std::string controllers_namespace; bool load_dual_robot; std::string state_controller; bool sim_flag=false; int communication_time=0; ros::init(argc, argv, "hbrobot_control_node"); ros::NodeHandle node_root; if(!node_root.getParam("controllers_namespace", controllers_namespace)) { ROS_ERROR_STREAM("ros con't find paramber \"controllers_namespace\""); return 0; } if(!node_root.getParam("load_dual_robot", load_dual_robot)) { ROS_ERROR_STREAM("ros con't find paramber \"load_dual_robot\""); return 0; } if(!node_root.getParam("state_controller", state_controller)) { ROS_ERROR_STREAM("ros con't find paramber \"state_controller\""); return 0; } if(!node_root.getParam("sim_flag", sim_flag)) { ROS_ERROR_STREAM("ros con't find paramber \"sim_flag\""); return 0; } if(!node_root.getParam("communication_time", communication_time)) { ROS_ERROR_STREAM("ros con't find paramber \"communication_time\""); return 0; } //robot initialize std::string system_arg; if(!node_root.getParam("system_arg", system_arg)) { ROS_ERROR_STREAM("ros con't find paramber \"system_arg\""); return false; } HYYRobotBase::command_arg arg; if (0==HYYRobotBase::commandLineParser1(system_arg.c_str(), &arg)) { if (0!=HYYRobotBase::system_initialize(&arg)) { ROS_ERROR_STREAM("device initialize failure! system_initialize faiure!"); return false; } } else { ROS_ERROR_STREAM("device initialize failure! commandLineParser1 faiure!"); return false; } ros::NodeHandle node_robothw(node_root, controllers_namespace); //ec_hardware::ECHardware robot_hw; device_hardware::DeviceHardware robot_hw(sim_flag); if (!robot_hw.init(node_root, node_robothw)) { ROS_ERROR_STREAM("hardware init failure!"); return 0; } controller_manager::ControllerManager cm(&robot_hw,node_root); //load controller if(load_dual_robot) { std::string left_arm_controller; std::string right_arm_controller; if(!node_root.getParam("left_arm_controller", left_arm_controller)) { ROS_ERROR_STREAM("ros con't find paramber \"left_arm_controller\""); return 0; } if(!node_root.getParam("right_arm_controller", right_arm_controller)) { ROS_ERROR_STREAM("ros con't find paramber \"right_arm_controller\""); return 0; } if (!cm.loadController(controllers_namespace+"/"+left_arm_controller)) { ROS_ERROR_STREAM(left_arm_controller<<" controller load failure!"); return 0; } if (!cm.loadController(controllers_namespace+"/"+right_arm_controller)) { ROS_ERROR_STREAM(right_arm_controller<<" controller load failure!"); return 0; } if (!cm.loadController(controllers_namespace+"/"+state_controller)) { ROS_ERROR_STREAM(state_controller<<" controller load failure!"); return 0; } } else { std::string trajectory_controller; std::string hyy_controller; if(!node_robothw.getParam("trajectory_controller", trajectory_controller)) { ROS_ERROR_STREAM("ros con't find paramber \"trajectory_controller\""); return 0; } if(!node_robothw.getParam("hyy_controller", hyy_controller)) { ROS_ERROR_STREAM("ros con't find paramber \"hyy_controller\""); return 0; } if (!cm.loadController(controllers_namespace+"/"+trajectory_controller)) { ROS_ERROR_STREAM(trajectory_controller<<" controller load failure!"); return 0; } if (!cm.loadController(controllers_namespace+"/"+hyy_controller)) { ROS_ERROR_STREAM(hyy_controller<<" controller load failure!"); return 0; } if (!cm.loadController(controllers_namespace+"/"+state_controller)) { ROS_ERROR_STREAM(state_controller<<" controller load failure!"); return 0; } } ros::Time _time(0,0); ros::Duration d_time(0,communication_time);//s,ns, =1ms ros::AsyncSpinner spinner(1); spinner.start(); HYYRobotBase::RTimer timer; if (0!=HYYRobotBase::initUserTimer(&timer, 0, 1)) { ROS_ERROR_STREAM("device_timer start failure!"); } ROS_INFO("------------start robothw loop----------------"); struct timeval start,end; int __dtime=0; _time=ros::Time::now(); while (ros::ok()) { if (sim_flag) { d_time.sleep(); } else { HYYRobotBase::userTimer(&timer); } gettimeofday(&start,NULL); robot_hw.read(_time, d_time); _time=_time+d_time; cm.update(_time, d_time); robot_hw.write(_time, d_time); gettimeofday(&end,NULL); __dtime=(end.tv_sec*1000000+end.tv_usec)-(start.tv_sec*1000000+start.tv_usec); if (__dtime>(communication_time/1000*0.8)) { ROS_ERROR("over time, %d us",__dtime); } } return 1; }
28.452736
84
0.647666
[ "model" ]
ab5df0289e18f7b391944378a561aa1587f808c7
8,315
cc
C++
components/offline_pages/background/request_queue_in_memory_store_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2020-09-15T08:43:34.000Z
2020-09-15T08:43:34.000Z
components/offline_pages/background/request_queue_in_memory_store_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
components/offline_pages/background/request_queue_in_memory_store_unittest.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/offline_pages/background/request_queue_in_memory_store.h" #include <memory> #include "base/bind.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "components/offline_pages/background/request_queue_store.h" #include "components/offline_pages/background/save_page_request.h" #include "testing/gtest/include/gtest/gtest.h" namespace offline_pages { using UpdateStatus = RequestQueueStore::UpdateStatus; namespace { const int64_t kRequestId = 42; const GURL kUrl("http://example.com"); const ClientId kClientId("bookmark", "1234"); bool operator==(const SavePageRequest& lhs, const SavePageRequest& rhs) { return lhs.request_id() == rhs.request_id() && lhs.url() == rhs.url() && lhs.client_id() == rhs.client_id() && lhs.creation_time() == rhs.creation_time() && lhs.activation_time() == rhs.activation_time() && lhs.attempt_count() == rhs.attempt_count() && lhs.last_attempt_time() == rhs.last_attempt_time(); } } // namespace class RequestQueueInMemoryStoreTest : public testing::Test { public: enum class LastResult { kNone, kFalse, kTrue, }; RequestQueueInMemoryStoreTest(); // Test overrides. void SetUp() override; RequestQueueStore* store() { return store_.get(); } void PumpLoop(); void ResetResults(); // Callback used for get requests. void GetRequestsDone(bool result, const std::vector<SavePageRequest>& requests); // Callback used for add/update request. void AddOrUpdateDone(UpdateStatus result); // Callback used for remove requests. void RemoveDone(bool result, int count); // Callback used for reset. void ResetDone(bool result); LastResult last_result() const { return last_result_; } UpdateStatus last_update_status() const { return last_update_status_; } int last_remove_count() const { return last_remove_count_; } const std::vector<SavePageRequest>& last_requests() const { return last_requests_; } private: std::unique_ptr<RequestQueueInMemoryStore> store_; LastResult last_result_; UpdateStatus last_update_status_; int last_remove_count_; std::vector<SavePageRequest> last_requests_; scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; }; RequestQueueInMemoryStoreTest::RequestQueueInMemoryStoreTest() : last_result_(LastResult::kNone), last_update_status_(UpdateStatus::kFailed), last_remove_count_(0), task_runner_(new base::TestSimpleTaskRunner), task_runner_handle_(task_runner_) {} void RequestQueueInMemoryStoreTest::SetUp() { store_.reset(new RequestQueueInMemoryStore()); } void RequestQueueInMemoryStoreTest::PumpLoop() { task_runner_->RunUntilIdle(); } void RequestQueueInMemoryStoreTest::ResetResults() { last_result_ = LastResult::kNone; last_update_status_ = UpdateStatus::kFailed; last_remove_count_ = 0; last_requests_.clear(); } void RequestQueueInMemoryStoreTest::GetRequestsDone( bool result, const std::vector<SavePageRequest>& requests) { last_result_ = result ? LastResult::kTrue : LastResult::kFalse; last_requests_ = requests; } void RequestQueueInMemoryStoreTest::AddOrUpdateDone(UpdateStatus status) { last_update_status_ = status; } void RequestQueueInMemoryStoreTest::RemoveDone(bool result, int count) { last_result_ = result ? LastResult::kTrue : LastResult::kFalse; last_remove_count_ = count; } void RequestQueueInMemoryStoreTest::ResetDone(bool result) { last_result_ = result ? LastResult::kTrue : LastResult::kFalse; } TEST_F(RequestQueueInMemoryStoreTest, GetRequestsEmpty) { store()->GetRequests(base::Bind( &RequestQueueInMemoryStoreTest::GetRequestsDone, base::Unretained(this))); ASSERT_EQ(LastResult::kNone, last_result()); PumpLoop(); ASSERT_EQ(LastResult::kTrue, last_result()); ASSERT_TRUE(last_requests().empty()); } TEST_F(RequestQueueInMemoryStoreTest, AddRequest) { base::Time creation_time = base::Time::Now(); SavePageRequest request(kRequestId, kUrl, kClientId, creation_time); store()->AddOrUpdateRequest( request, base::Bind(&RequestQueueInMemoryStoreTest::AddOrUpdateDone, base::Unretained(this))); ASSERT_EQ(UpdateStatus::kFailed, last_update_status()); PumpLoop(); ASSERT_EQ(UpdateStatus::kAdded, last_update_status()); // Verifying get reqeust results after a request was added. ResetResults(); store()->GetRequests(base::Bind( &RequestQueueInMemoryStoreTest::GetRequestsDone, base::Unretained(this))); ASSERT_EQ(LastResult::kNone, last_result()); PumpLoop(); ASSERT_EQ(LastResult::kTrue, last_result()); ASSERT_EQ(1ul, last_requests().size()); ASSERT_TRUE(request == last_requests()[0]); } TEST_F(RequestQueueInMemoryStoreTest, UpdateRequest) { base::Time creation_time = base::Time::Now(); SavePageRequest original_request(kRequestId, kUrl, kClientId, creation_time); store()->AddOrUpdateRequest( original_request, base::Bind(&RequestQueueInMemoryStoreTest::AddOrUpdateDone, base::Unretained(this))); PumpLoop(); ResetResults(); base::Time new_creation_time = creation_time + base::TimeDelta::FromMinutes(1); base::Time activation_time = creation_time + base::TimeDelta::FromHours(6); SavePageRequest updated_request(kRequestId, kUrl, kClientId, new_creation_time, activation_time); store()->AddOrUpdateRequest( updated_request, base::Bind(&RequestQueueInMemoryStoreTest::AddOrUpdateDone, base::Unretained(this))); ASSERT_EQ(UpdateStatus::kFailed, last_update_status()); PumpLoop(); ASSERT_EQ(UpdateStatus::kUpdated, last_update_status()); // Verifying get reqeust results after a request was updated. ResetResults(); store()->GetRequests(base::Bind( &RequestQueueInMemoryStoreTest::GetRequestsDone, base::Unretained(this))); ASSERT_EQ(LastResult::kNone, last_result()); PumpLoop(); ASSERT_EQ(LastResult::kTrue, last_result()); ASSERT_EQ(1ul, last_requests().size()); ASSERT_TRUE(updated_request == last_requests()[0]); } TEST_F(RequestQueueInMemoryStoreTest, RemoveRequest) { base::Time creation_time = base::Time::Now(); SavePageRequest original_request(kRequestId, kUrl, kClientId, creation_time); store()->AddOrUpdateRequest( original_request, base::Bind(&RequestQueueInMemoryStoreTest::AddOrUpdateDone, base::Unretained(this))); PumpLoop(); ResetResults(); std::vector<int64_t> request_ids{kRequestId}; store()->RemoveRequests(request_ids, base::Bind(&RequestQueueInMemoryStoreTest::RemoveDone, base::Unretained(this))); ASSERT_EQ(LastResult::kNone, last_result()); ASSERT_EQ(0, last_remove_count()); PumpLoop(); ASSERT_EQ(LastResult::kTrue, last_result()); ASSERT_EQ(1, last_remove_count()); ASSERT_EQ(0ul, last_requests().size()); ResetResults(); // Removing a request that is missing fails. store()->RemoveRequests(request_ids, base::Bind(&RequestQueueInMemoryStoreTest::RemoveDone, base::Unretained(this))); ASSERT_EQ(LastResult::kNone, last_result()); ASSERT_EQ(0, last_remove_count()); PumpLoop(); ASSERT_EQ(LastResult::kFalse, last_result()); ASSERT_EQ(0, last_remove_count()); } TEST_F(RequestQueueInMemoryStoreTest, ResetStore) { base::Time creation_time = base::Time::Now(); SavePageRequest original_request(kRequestId, kUrl, kClientId, creation_time); store()->AddOrUpdateRequest( original_request, base::Bind(&RequestQueueInMemoryStoreTest::AddOrUpdateDone, base::Unretained(this))); PumpLoop(); ResetResults(); store()->Reset(base::Bind(&RequestQueueInMemoryStoreTest::ResetDone, base::Unretained(this))); ASSERT_EQ(LastResult::kNone, last_result()); PumpLoop(); ASSERT_EQ(LastResult::kTrue, last_result()); ASSERT_EQ(0ul, last_requests().size()); } } // offline_pages
34.218107
80
0.72267
[ "vector" ]
ab6485f237f284ce6bb368ab869c4e8bb2b85802
716
cc
C++
Codeforces/274 Division 2/Problem C/C.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/274 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/274 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include<stdio.h> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<math.h> #define sd(x) scanf("%d",&x); #define sd2(x,y) scanf("%d%d",&x,&y); #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z); #define fi first #define se second using namespace std; int n, a, b, mn, prev; vector<pair<int, int> > dates; int main(){ sd(n); for(int i = 0; i < n; i++){ sd2(a,b); dates.push_back(make_pair(a,b)); } sort(dates.begin(), dates.end()); prev = dates[0].se; for(int i = 1; i < n; i++){ if(dates[i].se >= prev) prev = dates[i].se; else{ prev = dates[i].fi; } } cout<< prev << endl; return 0; }
15.234043
44
0.589385
[ "vector" ]
ab64fb093cdbd1df512e0162869d8d6c7a6fd02f
2,068
cpp
C++
multithreading.cpp
m-shibata/jfbview-dpkg
ddca68777bf60da01da8bbeb14f1d4ac5a6e4cf9
[ "Apache-1.1" ]
1
2016-08-05T21:13:57.000Z
2016-08-05T21:13:57.000Z
multithreading.cpp
m-shibata/jfbview-dpkg
ddca68777bf60da01da8bbeb14f1d4ac5a6e4cf9
[ "Apache-1.1" ]
null
null
null
multithreading.cpp
m-shibata/jfbview-dpkg
ddca68777bf60da01da8bbeb14f1d4ac5a6e4cf9
[ "Apache-1.1" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2012-2014 Chuan Ji <ji@chu4n.com> * * * * 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 "multithreading.hpp" #include <unistd.h> #include <algorithm> #include <cassert> #include <thread> #include <vector> int GetDefaultNumThreads() { return std::min(2.0, sysconf(_SC_NPROCESSORS_ONLN) * 1.5); } void ExecuteInParallel( const std::function<void(int, int)> &f, int num_threads) { // 1. Set default value for num_threads if needed. assert(num_threads >= 0); if (num_threads <= 0) { num_threads = GetDefaultNumThreads(); } // 2. Spawn threads. std::vector<std::thread> threads; for (int i = 0; i < num_threads; ++i) { threads.push_back(std::thread(f, num_threads, i)); } // 3. Wait for threads to exit. for (std::thread& thread : threads) { thread.join(); } }
40.54902
79
0.448259
[ "vector" ]
ab66df18b5a88ec13b80ad6989879c70a83f81ef
4,655
hpp
C++
Code/PROJECT XYZ/Code/include/Engine/Input/Gesture.hpp
SonarSystems/SGE
bb98feba6192ed34918c4c7bac74c050452d8386
[ "Unlicense" ]
null
null
null
Code/PROJECT XYZ/Code/include/Engine/Input/Gesture.hpp
SonarSystems/SGE
bb98feba6192ed34918c4c7bac74c050452d8386
[ "Unlicense" ]
null
null
null
Code/PROJECT XYZ/Code/include/Engine/Input/Gesture.hpp
SonarSystems/SGE
bb98feba6192ed34918c4c7bac74c050452d8386
[ "Unlicense" ]
null
null
null
#pragma once namespace Sonar { /** * \brief Analogue Sticks */ enum AnalogueStick { LeftStick, RightStick }; /** * \brief Analogue Stick Direction */ enum Direction { Left, Right, Up, Down, NONE }; /** * \brief Logical Comparison Direction */ enum ComparisonDirection { LessThan, GreaterThan }; /** * \brief Patterns for the Gesture */ enum Pattern { LeftClockwiseUp, LeftCounterClockwiseDown, RightCounterClockwiseUp, RightClockwiseDown, UpCounterClockwiseLeft, UpClockwiseRight, DownClockwiseLeft, DownCounterClockwiseRight, Clockwise, CounterClockwise }; /** * \brief Individual gesture step */ struct GestureStep { std::pair<float, float> xMinMax; std::pair<float, float> yMinMax; Direction xDirection; Direction yDirection; float timeToFinish = 0; }; /** * \brief Gesture sequence with all steps and reset */ struct GesturePattern { std::vector<GestureStep> steps; float resetPos; Pattern pattern; }; class Gesture { public: /** * \brief Class constructor */ Gesture( const int &joystickID, const AnalogueStick &analogueStick, const Pattern &pattern ); /** * \brief Class destructor */ ~Gesture( ); /** * \brief Update the gesture */ void Update( ); /** * \brief Checks if the gesture is complete * * \return Output returns the status of the gesture */ [[nodiscard]] bool IsComplete( ); /** * \brief Reset the Gesture */ void Reset( ); /** * \brief Set the analogue stick * * \param analogueStick Analogue stick for gesture */ void SetAnalogueStick( const AnalogueStick &analogueStick ); /** * \brief Get the current analogue stick * * \return Output returns the gesture's analogue stick */ [[nodiscard]] AnalogueStick GetAnalogueStick( ) const; /** * \brief Set the joysticks ID * * \param analogueStick Analogue stick for gesture */ void SetJoystickID( const int &joystickID ); /** * \brief Get the ID of the current joystick * * \return Output returns the joystick ID */ [[nodiscard]] int GetJoystickID( ) const; /** * \brief Set the gesture pattern * * \param pattern Gesture pattern to be used */ void SetPattern( const Pattern &pattern ); /** * \brief Get the gesture pattern * * \return Output returns the gesture pattern */ [[nodiscard]] Pattern GetPattern( ) const; /** * \brief Get the status of the joystick rotation (only for Clockwise and CounterClockwise patterns) * * \return Output returns joystick rotation status */ [[nodiscard]] bool GetIsRotating( ) const; /** * \brief Get the total number of degrees turned (only for Clockwise and CounterClockwise patterns) * * \param isDegrees True (by default) returns the result in degrees and false returns it in radians * * \return Output returns total degrees turned by the joystick */ [[nodiscard]] bool GetTotalDegreesTurned( const bool &isDegrees = true ) const; /** * \brief Get the total number of circles turned by the joystick (only for Clockwise and CounterClockwise patterns) * * \return Output returns total number of joystick rotations */ [[nodiscard]] float GetTotalCirclesTurned( ) const; /** * \brief Get the gesture clock (only for Clockwise and CounterClockwise patterns) * * \return Output returns clock */ [[nodiscard]] Clock GetClock( ); private: void SetResetAxis( ); /** * \brief Keeps track of the time between steps */ Clock _clock; /** * \brief Is the device moving or not */ bool _isMoving; /** * \brief Is the gesture complete */ bool _isComplete; /** * \brief What stage of the gesture is currently active */ unsigned int _loopCounter; /** * \brief ID of the joystick to be checked */ int _joystickID; /** * \brief X axis of the joystick */ Joystick::Axis _xAxis; /** * \brief Y axis of the joystick */ Joystick::Axis _yAxis; /** * \brief Analogue stick to check gesture with */ AnalogueStick _analogueStick; /** * \brief Gesture pattern to be checked */ GesturePattern _gesturePattern; /** * \brief Reset axis to check */ Joystick::Axis _resetAxis; /** * \brief Comparison direction for the reset axis */ ComparisonDirection _comparisonDirection; float _previousAngle; /** * \brief Track whether or not the joystick is turning (only for Clockwise and CounterClockwise patterns) */ bool _isRotating; /** * \brief Total number of degrees the joystick has turned (only for Clockwise and CounterClockwise patterns) */ float _totalDegreesTurned; }; }
18.326772
116
0.672825
[ "vector" ]
03655143e3c7a234eddf957ace328e893ae75a77
64,416
cpp
C++
src/mame/drivers/tigeroad.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/tigeroad.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/tigeroad.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Phil Stroffolino, Bryan McPhail /*************************************************************************** Tiger Road (C) 1987 Capcom (licensed to Romstar) F1 Dream (C) 1988 Capcom cloned hardware: Pushman (C) 1990 Comad Bouncing Balls (c) 1991 Comad Please contact Phil Stroffolino (phil@maya.com) if there are any questions regarding this driver. TODO: - F1 Dream throws an address error if player wins all the races (i.e. when the game is supposed to give an ending): 010C68: 102E 001C move.b ($1c,A6), D0 ; reads 0xf from work RAM (misaligned) 010C6C: 207B 000E movea.l ($e,PC,D0.w), A0 ; table from 0x10c7c onward 010C70: 4E90 jsr (A0) ; throws address error here None of the available 5 vectors seems to fit here, btanb? ************************************************************************** Memory Overview: 0xfe0800 sprites 0xfec000 text 0xfe4000 input ports,dip switches (read); sound out, video reg (write) 0xfe4002 protection (F1 Dream only) 0xfe8000 scroll registers 0xff8200 palette 0xffC000 working RAM ************************************************************************** Pushman Notes With 'Debug Mode' on button 2 advances a level, button 3 goes back. The microcontroller mainly controls the animation of the enemy robots, the communication between the 68000 and MCU is probably not emulated 100% correct but it works. Emulation by Bryan McPhail, mish@tendril.co.uk The hardware is actually very similar to F1-Dream and Tiger Road but with a 68705 for protection. Pushman is known to be released in a 2 PCB stack as well as a large single plane board. ***************************************************************************/ #include "emu.h" #include "includes/tigeroad.h" #include "machine/gen_latch.h" #include "screen.h" #include "speaker.h" void tigeroad_state::msm5205_w(u8 data) { m_msm->reset_w(BIT(data, 7)); m_msm->data_w(data); m_msm->vclk_w(1); m_msm->vclk_w(0); } void f1dream_state::out3_w(u8 data) { if ((m_old_p3 & 0x20) != (data & 0x20)) { // toggles at the start and end of interrupt } if ((m_old_p3 & 0x01) != (data & 0x01)) { // toggles at the end of interrupt if (!(data & 0x01)) { m_maincpu->resume(SUSPEND_REASON_HALT); } } m_old_p3 = data; } void f1dream_state::to_mcu_w(u16 data) { m_mcu->set_input_line(MCS51_INT0_LINE, HOLD_LINE); /* after triggering this address there are one or two NOPs in the 68k code, then it expects the response to be ready the MCU isn't that fast, so either the CPU is suspended on write, or when bit 0x20 of MCU Port 3 toggles in the MCU interrupt code, however no combination of increasing the clock / boosting interleave etc. allows the MCU code to get there in time before the 68k is already expecting a result */ m_maincpu->suspend(SUSPEND_REASON_HALT, true); } /***************************************************************************/ void tigeroad_state::main_map(address_map &map) { map(0x000000, 0x03ffff).rom(); map(0xfe0800, 0xfe0cff).ram().share("spriteram"); map(0xfe0d00, 0xfe1807).ram(); // still part of OBJ RAM map(0xfe4000, 0xfe4001).portr("P1_P2"); map(0xfe4000, 0xfe4000).w(FUNC(tigeroad_state::videoctrl_w)); // char bank, coin counters, + ? map(0xfe4002, 0xfe4003).portr("SYSTEM"); map(0xfe4002, 0xfe4002).w("soundlatch", FUNC(generic_latch_8_device::write)); map(0xfe4004, 0xfe4005).portr("DSW"); map(0xfe8000, 0xfe8003).w(FUNC(tigeroad_state::scroll_w)); map(0xfe800e, 0xfe800f).nopw(); // fe800e = watchdog or IRQ acknowledge map(0xfec000, 0xfec7ff).ram().w(FUNC(tigeroad_state::videoram_w)).share("videoram"); map(0xff8000, 0xff87ff).ram().w(m_palette, FUNC(palette_device::write16)).share("palette"); map(0xffc000, 0xffffff).ram().share("ram16"); } u8 f1dream_state::mcu_shared_r(offs_t offset) { u8 ret = m_ram16[(0x3fe0 / 2) + offset]; return ret; } void f1dream_state::mcu_shared_w(offs_t offset, u8 data) { m_ram16[(0x3fe0 / 2) + offset] = (m_ram16[(0x3fe0 / 2) + offset] & 0xff00) | data; } void f1dream_state::f1dream_map(address_map &map) { main_map(map); map(0xfe4002, 0xfe4003).portr("SYSTEM").w(FUNC(f1dream_state::to_mcu_w)); } void f1dream_state::f1dream_mcu_io(address_map &map) { map(0x7f0, 0x7ff).rw(FUNC(f1dream_state::mcu_shared_r), FUNC(f1dream_state::mcu_shared_w)); } void pushman_state::pushman_map(address_map &map) { main_map(map); map(0x060000, 0x060007).r(FUNC(pushman_state::mcu_comm_r)); map(0x060000, 0x060003).w(FUNC(pushman_state::pushman_mcu_comm_w)); } void pushman_state::bballs_map(address_map &map) { map.global_mask(0xfffff); map(0x00000, 0x3ffff).rom(); map(0x60000, 0x60007).r(FUNC(pushman_state::mcu_comm_r)); map(0x60000, 0x60001).w(FUNC(pushman_state::bballs_mcu_comm_w)); // are these mirror addresses or does this PCB have a different addressing? map(0xe0800, 0xe17ff).ram().share("spriteram"); map(0xe4000, 0xe4001).portr("P1_P2"); map(0xe4000, 0xe4000).w(FUNC(pushman_state::videoctrl_w)); map(0xe4002, 0xe4003).portr("SYSTEM"); map(0xe4002, 0xe4002).w("soundlatch", FUNC(generic_latch_8_device::write)); map(0xe4004, 0xe4005).portr("DSW"); map(0xe8000, 0xe8003).w(FUNC(pushman_state::scroll_w)); map(0xe800e, 0xe800f).nopw(); // ? map(0xec000, 0xec7ff).ram().w(FUNC(pushman_state::videoram_w)).share("videoram"); map(0xf8000, 0xf87ff).ram().w(m_palette, FUNC(palette_device::write16)).share("palette"); map(0xfc000, 0xfffff).ram().share("ram16"); } // Capcom games ONLY void tigeroad_state::sound_map(address_map &map) { map(0x0000, 0x7fff).rom(); map(0x8000, 0x8001).rw("ym1", FUNC(ym2203_device::read), FUNC(ym2203_device::write)); map(0xa000, 0xa001).rw("ym2", FUNC(ym2203_device::read), FUNC(ym2203_device::write)); map(0xc000, 0xc7ff).ram(); map(0xe000, 0xe000).r("soundlatch", FUNC(generic_latch_8_device::read)); } void tigeroad_state::sound_port_map(address_map &map) { map.global_mask(0xff); map(0x7f, 0x7f).w("soundlatch2", FUNC(generic_latch_8_device::write)); } // toramich ONLY void tigeroad_state::sample_map(address_map &map) { map(0x0000, 0xffff).rom(); } void tigeroad_state::sample_port_map(address_map &map) { map.global_mask(0xff); map(0x00, 0x00).r("soundlatch2", FUNC(generic_latch_8_device::read)); map(0x01, 0x01).w(FUNC(tigeroad_state::msm5205_w)); } // Pushman / Bouncing Balls void tigeroad_state::comad_sound_map(address_map &map) { map(0x0000, 0x7fff).rom(); map(0xc000, 0xc7ff).ram(); map(0xe000, 0xe000).r("soundlatch", FUNC(generic_latch_8_device::read)); } void tigeroad_state::comad_sound_io_map(address_map &map) { map.global_mask(0xff); map(0x00, 0x01).w("ym1", FUNC(ym2203_device::write)); map(0x80, 0x81).w("ym2", FUNC(ym2203_device::write)); } static INPUT_PORTS_START( tigeroad ) PORT_START("P1_P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("SYSTEM") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START("DSW") PORT_DIPNAME( 0x0007, 0x0007, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("DIPA:1,2,3") PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0001, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0002, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0007, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0006, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0005, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0004, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0003, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x0038, 0x0038, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("DIPA:4,5,6") PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0008, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0010, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0038, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0030, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0028, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0020, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0018, DEF_STR( 1C_6C ) ) PORT_SERVICE( 0x0040, IP_ACTIVE_LOW ) PORT_DIPLOCATION("DIPA:7") PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("DIPA:8") PORT_DIPSETTING( 0x0080, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0300, 0x0300, DEF_STR( Lives ) ) PORT_DIPLOCATION("DIPB:1,2") PORT_DIPSETTING( 0x0300, "3" ) PORT_DIPSETTING( 0x0200, "4" ) PORT_DIPSETTING( 0x0100, "5" ) PORT_DIPSETTING( 0x0000, "7" ) PORT_DIPNAME( 0x0400, 0x0000, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("DIPB:3") PORT_DIPSETTING( 0x0000, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x0400, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x1800, 0x1800, DEF_STR( Bonus_Life ) ) PORT_DIPLOCATION("DIPB:4,5") PORT_DIPSETTING( 0x1800, "20000 70000 70000" ) PORT_DIPSETTING( 0x1000, "20000 80000 80000" ) PORT_DIPSETTING( 0x0800, "30000 80000 80000" ) PORT_DIPSETTING( 0x0000, "30000 90000 90000" ) PORT_DIPNAME( 0x6000, 0x6000, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("DIPB:6,7") PORT_DIPSETTING( 0x2000, "Very Easy (Level 0)") PORT_DIPSETTING( 0x4000, "Easy (Level 10)") PORT_DIPSETTING( 0x6000, "Normal (Level 20)") PORT_DIPSETTING( 0x0000, "Difficult (Level 30)") PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Allow_Continue ) ) PORT_DIPLOCATION("DIPB:8") PORT_DIPSETTING( 0x0000, DEF_STR( No ) ) PORT_DIPSETTING( 0x8000, DEF_STR( Yes ) ) INPUT_PORTS_END static INPUT_PORTS_START( toramich ) PORT_START("P1_P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("SYSTEM") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START("DSW") PORT_DIPNAME( 0x0007, 0x0007, DEF_STR( Coin_B ) ) PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0001, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0002, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0007, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0006, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0005, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0004, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0003, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x0038, 0x0038, DEF_STR( Coin_A ) ) PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0008, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0010, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0038, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0030, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0028, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0020, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0018, DEF_STR( 1C_6C ) ) PORT_SERVICE( 0x0040, IP_ACTIVE_LOW ) PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Flip_Screen ) ) PORT_DIPSETTING( 0x0080, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0300, 0x0300, DEF_STR( Lives ) ) PORT_DIPSETTING( 0x0300, "3" ) PORT_DIPSETTING( 0x0200, "4" ) PORT_DIPSETTING( 0x0100, "5" ) PORT_DIPSETTING( 0x0000, "7" ) PORT_DIPNAME( 0x0400, 0x0000, DEF_STR( Cabinet ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Upright )) PORT_DIPSETTING( 0x0400, DEF_STR( Cocktail )) PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Bonus_Life ) ) PORT_DIPSETTING( 0x0800, "20000 70000 70000" ) PORT_DIPSETTING( 0x0000, "20000 80000 80000" ) PORT_DIPNAME( 0x1000, 0x1000, "Allow Level Select" ) PORT_DIPSETTING( 0x1000, DEF_STR( No ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Yes ) ) PORT_DIPNAME( 0x6000, 0x6000, DEF_STR( Difficulty ) ) PORT_DIPSETTING( 0x4000, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x6000, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x2000, DEF_STR( Difficult ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Very_Difficult ) ) PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Allow_Continue ) ) PORT_DIPSETTING( 0x0000, DEF_STR( No ) ) PORT_DIPSETTING( 0x8000, DEF_STR( Yes ) ) INPUT_PORTS_END static INPUT_PORTS_START( f1dream ) PORT_START("P1_P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_8WAY PORT_COCKTAIL PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_COCKTAIL PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_COCKTAIL PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_START("SYSTEM") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START("DSW") PORT_DIPNAME( 0x0007, 0x0007, DEF_STR( Coin_B ) ) PORT_DIPLOCATION("DIPA:1,2,3") PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0001, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0002, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0007, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0006, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0005, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0004, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0003, DEF_STR( 1C_6C ) ) PORT_DIPNAME( 0x0038, 0x0038, DEF_STR( Coin_A ) ) PORT_DIPLOCATION("DIPA:4,5,6") PORT_DIPSETTING( 0x0000, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0008, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0010, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0038, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0030, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0028, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0020, DEF_STR( 1C_4C ) ) PORT_DIPSETTING( 0x0018, DEF_STR( 1C_6C ) ) PORT_SERVICE( 0x0040, IP_ACTIVE_LOW ) PORT_DIPLOCATION("DIPA:7") PORT_DIPNAME( 0x0080, 0x0080, DEF_STR( Flip_Screen ) ) PORT_DIPLOCATION("DIPA:8") PORT_DIPSETTING( 0x0080, DEF_STR( Off )) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0300, 0x0300, DEF_STR( Lives ) ) PORT_DIPLOCATION("DIPB:1,2") // "Not Used" according to Romstar manual PORT_DIPSETTING( 0x0300, "3" ) PORT_DIPSETTING( 0x0200, "4" ) PORT_DIPSETTING( 0x0100, "5" ) PORT_DIPSETTING( 0x0000, "7" ) PORT_DIPNAME( 0x0400, 0x0000, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("DIPB:3") PORT_DIPSETTING( 0x0000, DEF_STR( Upright )) PORT_DIPSETTING( 0x0400, DEF_STR( Cocktail )) PORT_DIPNAME( 0x1800, 0x1800, "F1 Up Point" ) PORT_DIPLOCATION("DIPB:4,5") PORT_DIPSETTING( 0x1800, "12" ) PORT_DIPSETTING( 0x1000, "16" ) PORT_DIPSETTING( 0x0800, "18" ) PORT_DIPSETTING( 0x0000, "20" ) PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("DIPB:6") PORT_DIPSETTING( 0x2000, DEF_STR( Normal ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Difficult ) ) PORT_DIPNAME( 0x4000, 0x0000, DEF_STR( Version ) ) PORT_DIPLOCATION("DIPB:7") PORT_DIPSETTING( 0x0000, DEF_STR( World ) ) PORT_DIPSETTING( 0x4000, DEF_STR( Japan ) ) PORT_DIPNAME( 0x8000, 0x8000, DEF_STR( Allow_Continue ) ) PORT_DIPLOCATION("DIPB:8") PORT_DIPSETTING( 0x0000, DEF_STR( No ) ) PORT_DIPSETTING( 0x8000, DEF_STR( Yes ) ) INPUT_PORTS_END static INPUT_PORTS_START( pushman ) PORT_START("P1_P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(1) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_BUTTON3 ) PORT_PLAYER(2) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_UNUSED ) PORT_START("SYSTEM") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_CUSTOM ) PORT_VBLANK("screen") // not sure, probably wrong PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START("DSW") PORT_DIPNAME( 0x0001, 0x0001, "Debug Mode (Cheat)") PORT_DIPLOCATION("SW1:1") // Listed as "Screen Skip" PORT_DIPSETTING( 0x0001, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0002, 0x0002, "Pull Option" ) PORT_DIPLOCATION("SW1:2") PORT_DIPSETTING( 0x0002, "5" ) PORT_DIPSETTING( 0x0000, "9" ) PORT_DIPNAME( 0x0004, 0x0004, DEF_STR( Level_Select ) ) PORT_DIPLOCATION("SW1:3") PORT_DIPSETTING( 0x0004, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Cabinet ) ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x0008, DEF_STR( Upright ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Cocktail ) ) PORT_DIPNAME( 0x0010, 0x0010, DEF_STR( Demo_Sounds ) ) PORT_DIPLOCATION("SW1:5") PORT_DIPSETTING( 0x0000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0010, DEF_STR( On ) ) PORT_SERVICE_DIPLOC( 0x0020, IP_ACTIVE_LOW, "SW1:6" ) PORT_DIPUNUSED_DIPLOC( 0x0040, 0x0040, "SW1:7" ) PORT_DIPUNUSED_DIPLOC( 0x0080, 0x0080, "SW1:8" ) PORT_DIPNAME( 0x0700, 0x0700, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW2:1,2,3") PORT_DIPSETTING( 0x0000, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x0100, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0200, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0300, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0700, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0600, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0500, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0400, DEF_STR( 1C_4C ) ) PORT_DIPNAME( 0x0800, 0x0800, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW2:4") PORT_DIPSETTING( 0x0800, DEF_STR( Easy ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Hard ) ) PORT_DIPUNUSED_DIPLOC( 0x1000, 0x1000, "SW2:5" ) PORT_DIPUNUSED_DIPLOC( 0x2000, 0x2000, "SW2:6" ) PORT_DIPUNUSED_DIPLOC( 0x4000, 0x4000, "SW2:7" ) PORT_DIPUNUSED_DIPLOC( 0x8000, 0x8000, "SW2:8" ) INPUT_PORTS_END static INPUT_PORTS_START( bballs ) PORT_START("P1_P2") PORT_BIT( 0x0001, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0002, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0004, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0008, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_4WAY PORT_PLAYER(1) PORT_BIT( 0x0010, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(1) PORT_NAME("P1 Open/Close Gate") // Open/Close gate PORT_BIT( 0x0020, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(1) PORT_NAME("P1 Zap") // Use Zap PORT_BIT( 0x0040, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0080, IP_ACTIVE_LOW, IPT_UNKNOWN ) // BUTTON3 in "test mode" PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_JOYSTICK_RIGHT ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_JOYSTICK_LEFT ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_JOYSTICK_UP ) PORT_4WAY PORT_PLAYER(2) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_PLAYER(2) PORT_NAME("P2 Open/Close Gate") // Open/Close gate PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_BUTTON2 ) PORT_PLAYER(2) PORT_NAME("P2 Zap") // Use Zap PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_UNKNOWN ) // BUTTON3 in "test mode" PORT_START("SYSTEM") PORT_BIT( 0x00ff, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x0100, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT( 0x0200, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT( 0x0400, IP_ACTIVE_LOW, IPT_CUSTOM ) PORT_VBLANK("screen") // not sure, probably wrong PORT_BIT( 0x0800, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x1000, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT( 0x2000, IP_ACTIVE_LOW, IPT_SERVICE1 ) PORT_BIT( 0x4000, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT( 0x8000, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_START("DSW") PORT_DIPNAME( 0x0007, 0x0007, DEF_STR( Coinage ) ) PORT_DIPLOCATION("SW1:1,2,3") PORT_DIPSETTING( 0x0000, DEF_STR( 5C_1C ) ) PORT_DIPSETTING( 0x0001, DEF_STR( 4C_1C ) ) PORT_DIPSETTING( 0x0002, DEF_STR( 3C_1C ) ) PORT_DIPSETTING( 0x0003, DEF_STR( 2C_1C ) ) PORT_DIPSETTING( 0x0007, DEF_STR( 1C_1C ) ) PORT_DIPSETTING( 0x0006, DEF_STR( 1C_2C ) ) PORT_DIPSETTING( 0x0005, DEF_STR( 1C_3C ) ) PORT_DIPSETTING( 0x0004, DEF_STR( 1C_4C ) ) PORT_DIPNAME( 0x0008, 0x0008, DEF_STR( Difficulty ) ) PORT_DIPLOCATION("SW1:4") PORT_DIPSETTING( 0x0008, DEF_STR( Easy ) ) // less bubbles before cycling PORT_DIPSETTING( 0x0000, DEF_STR( Hard ) ) // more bubbles before cycling PORT_DIPNAME( 0x0010, 0x0000, "Music (In-game)" ) PORT_DIPLOCATION("SW1:5") PORT_DIPSETTING( 0x0010, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x0020, 0x0000, "Music (Attract Mode)" ) PORT_DIPLOCATION("SW1:6") PORT_DIPSETTING( 0x0020, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0x00c0, 0x00c0, DEF_STR( Lives ) ) PORT_DIPLOCATION("SW1:7,8") PORT_DIPSETTING( 0x00c0, "1" ) PORT_DIPSETTING( 0x0080, "2" ) PORT_DIPSETTING( 0x0040, "3" ) PORT_DIPSETTING( 0x0000, "4" ) PORT_DIPNAME( 0x0100, 0x0100, "Zaps" ) PORT_DIPLOCATION("SW2:1") PORT_DIPSETTING( 0x0100, "1" ) PORT_DIPSETTING( 0x0000, "2" ) PORT_DIPNAME( 0x0200, 0x0000, "Display Next Ball" ) PORT_DIPLOCATION("SW2:2") PORT_DIPSETTING( 0x0200, DEF_STR( No ) ) PORT_DIPSETTING( 0x0000, DEF_STR( Yes ) ) PORT_DIPUNUSED_DIPLOC( 0x0400, 0x0400, "SW2:3" ) PORT_DIPUNUSED_DIPLOC( 0x0800, 0x0800, "SW2:4" ) PORT_DIPUNUSED_DIPLOC( 0x1000, 0x1000, "SW2:5" ) PORT_DIPNAME( 0x2000, 0x2000, DEF_STR( Unknown ) ) PORT_DIPLOCATION("SW2:6") // code at 0x0054ac, 0x0054f2, 0x0056fc PORT_DIPSETTING( 0x2000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x0000, DEF_STR( On ) ) PORT_DIPNAME( 0xc000, 0xc000, DEF_STR( Service_Mode ) ) PORT_DIPLOCATION("SW2:7,8") PORT_DIPSETTING( 0xc000, DEF_STR( Off ) ) // PORT_DIPSETTING( 0x8000, DEF_STR( Off ) ) PORT_DIPSETTING( 0x4000, "Inputs/Outputs" ) PORT_DIPSETTING( 0x0000, "Graphics" ) INPUT_PORTS_END static const gfx_layout text_layout = { 8,8, RGN_FRAC(1,1), 2, { 4, 0 }, { STEP4(0,1), STEP4(4*2,1) }, { STEP8(0,4*2*2) }, 16*8 }; static const gfx_layout tile_layout = { 32,32, RGN_FRAC(1,2), 4, { RGN_FRAC(1,2)+4, RGN_FRAC(1,2)+0, 4, 0 }, { STEP4(0,1), STEP4(4*2,1), STEP4(4*2*2*32,1), STEP4(4*2*2*32+4*2,1), STEP4(4*2*2*64,1), STEP4(4*2*2*64+4*2,1), STEP4(4*2*2*96,1), STEP4(4*2*2*96+4*2,1) }, { STEP32(0,4*2*2) }, 256*8 }; static GFXDECODE_START( gfx_tigeroad ) GFXDECODE_ENTRY( "text", 0, text_layout, 0x300, 16 ) GFXDECODE_ENTRY( "tiles", 0, tile_layout, 0x100, 16 ) GFXDECODE_END void tigeroad_state::tigeroad(machine_config &config) { // basic machine hardware M68000(config, m_maincpu, XTAL(10'000'000)); // verified on pcb m_maincpu->set_addrmap(AS_PROGRAM, &tigeroad_state::main_map); m_maincpu->set_vblank_int("screen", FUNC(tigeroad_state::irq2_line_hold)); Z80(config, m_audiocpu, XTAL(3'579'545)); // verified on pcb m_audiocpu->set_addrmap(AS_PROGRAM, &tigeroad_state::sound_map); m_audiocpu->set_addrmap(AS_IO, &tigeroad_state::sound_port_map); // IRQs are triggered by the YM2203 // video hardware BUFFERED_SPRITERAM16(config, "spriteram"); // Timings may be different, driver originally had 60.08Hz vblank. screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER)); screen.set_raw(6000000, 384, 128, 0, 262, 22, 246); // hsync is 50..77, vsync is 257..259 screen.set_screen_update(FUNC(tigeroad_state::screen_update)); screen.screen_vblank().set("spriteram", FUNC(buffered_spriteram16_device::vblank_copy_rising)); screen.set_palette(m_palette); GFXDECODE(config, m_gfxdecode, m_palette, gfx_tigeroad); TIGEROAD_SPRITE(config, m_spritegen, 0); m_spritegen->set_palette(m_palette); m_spritegen->set_color_base(0x200); PALETTE(config, m_palette).set_format(palette_device::xRGB_444, 1024); // sound hardware SPEAKER(config, "mono").front_center(); GENERIC_LATCH_8(config, "soundlatch"); GENERIC_LATCH_8(config, "soundlatch2"); ym2203_device &ym1(YM2203(config, "ym1", XTAL(3'579'545))); // verified on pcb ym1.irq_handler().set_inputline(m_audiocpu, 0); ym1.add_route(ALL_OUTPUTS, "mono", 0.25); ym2203_device &ym2(YM2203(config, "ym2", XTAL(3'579'545))); // verified on pcb ym2.add_route(ALL_OUTPUTS, "mono", 0.25); } void f1dream_state::machine_start() { save_item(NAME(m_old_p3)); } void f1dream_state::f1dream(machine_config &config) { tigeroad(config); m_maincpu->set_addrmap(AS_PROGRAM, &f1dream_state::f1dream_map); I8751(config, m_mcu, XTAL(10'000'000)); // ??? m_mcu->set_addrmap(AS_IO, &f1dream_state::f1dream_mcu_io); m_mcu->port_out_cb<1>().set("soundlatch", FUNC(generic_latch_8_device::write)); m_mcu->port_out_cb<3>().set(FUNC(f1dream_state::out3_w)); } // same as above but with additional Z80 for samples playback void tigeroad_state::toramich(machine_config &config) { tigeroad(config); // basic machine hardware z80_device &sample(Z80(config, "sample", 3579545)); // ? sample.set_addrmap(AS_PROGRAM, &tigeroad_state::sample_map); sample.set_addrmap(AS_IO, &tigeroad_state::sample_port_map); sample.set_periodic_int(FUNC(tigeroad_state::irq0_line_hold), attotime::from_hz(4000)); // ? // sound hardware MSM5205(config, m_msm, 384000); m_msm->set_prescaler_selector(msm5205_device::SEX_4B); // 4KHz playback ? m_msm->add_route(ALL_OUTPUTS, "mono", 1.0); } void tigeroad_state::f1dream_comad(machine_config &config) { // basic machine hardware M68000(config, m_maincpu, 8000000); m_maincpu->set_addrmap(AS_PROGRAM, &tigeroad_state::main_map); m_maincpu->set_vblank_int("screen", FUNC(tigeroad_state::irq2_line_hold)); Z80(config, m_audiocpu, 4000000); m_audiocpu->set_addrmap(AS_PROGRAM, &tigeroad_state::comad_sound_map); m_audiocpu->set_addrmap(AS_IO, &tigeroad_state::comad_sound_io_map); config.set_maximum_quantum(attotime::from_hz(3600)); // video hardware BUFFERED_SPRITERAM16(config, "spriteram"); screen_device &screen(SCREEN(config, "screen", SCREEN_TYPE_RASTER)); screen.set_raw(6000000, 384, 128, 0, 262, 22, 246); // hsync is 50..77, vsync is 257..259 screen.set_screen_update(FUNC(tigeroad_state::screen_update)); screen.screen_vblank().set("spriteram", FUNC(buffered_spriteram16_device::vblank_copy_rising)); screen.set_palette(m_palette); GFXDECODE(config, m_gfxdecode, m_palette, gfx_tigeroad); TIGEROAD_SPRITE(config, m_spritegen, 0); m_spritegen->set_palette(m_palette); m_spritegen->set_color_base(0x200); PALETTE(config, m_palette).set_format(palette_device::xRGB_444, 1024); // sound hardware SPEAKER(config, "mono").front_center(); GENERIC_LATCH_8(config, "soundlatch"); ym2203_device &ym1(YM2203(config, "ym1", 2000000)); ym1.irq_handler().set_inputline("audiocpu", 0); ym1.add_route(ALL_OUTPUTS, "mono", 0.40); ym2203_device &ym2(YM2203(config, "ym2", 2000000)); ym2.add_route(ALL_OUTPUTS, "mono", 0.40); } void pushman_state::machine_start() { save_item(NAME(m_host_semaphore)); save_item(NAME(m_mcu_semaphore)); save_item(NAME(m_host_latch)); save_item(NAME(m_mcu_latch)); save_item(NAME(m_mcu_output)); save_item(NAME(m_mcu_latch_ctl)); } void pushman_state::pushman(machine_config &config) { f1dream_comad(config); m_maincpu->set_addrmap(AS_PROGRAM, &pushman_state::pushman_map); M68705R3(config, m_mcu, 4000000); // No idea m_mcu->porta_w().set(FUNC(pushman_state::mcu_pa_w)); m_mcu->portb_w().set(FUNC(pushman_state::mcu_pb_w)); m_mcu->portc_w().set(FUNC(pushman_state::mcu_pc_w)); } void pushman_state::bballs(machine_config &config) { pushman(config); m_maincpu->set_addrmap(AS_PROGRAM, &pushman_state::bballs_map); } /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( tigeroad ) // N86614A-5 + N86614B-6 board combo - ECT program roms ROM_REGION( 0x40000, "maincpu", 0 ) // 256K for 68000 code ROM_LOAD16_BYTE( "tre_02.6j", 0x00000, 0x20000, CRC(c394add0) SHA1(f71cceca92ed7d2211f508df9ddfa97e0dd28d11) ) // Blue ink underline ROM_LOAD16_BYTE( "tre_04.6k", 0x00001, 0x20000, CRC(73bfbf4a) SHA1(821af477953f7a64f4f1b09e8978fb2bce4138ff) ) // Blue ink underline ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "tru_05.12k", 0x0000, 0x8000, CRC(f9a7c9bf) SHA1(4d37c71aa6523ac21c6e8b23f9957e75ec4304bf) ) // Red ink underline // i8751 microcontroller not populated // no samples player in the English version ROM_REGION( 0x008000, "text", 0 ) ROM_LOAD( "tr_01.10d", 0x00000, 0x08000, CRC(74a9f08c) SHA1(458958c8d9a2af5df88bb24c9c5bcbd37d6856bc) ) // 8x8 text ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "tr-01a.3f", 0x00000, 0x20000, CRC(a8aa2e59) SHA1(792f50d688a4ffb574e41257816bc304d41f0458) ) ROM_LOAD( "tr-04a.3h", 0x20000, 0x20000, CRC(8863a63c) SHA1(11bfce5b09c5b8a781c658f035d5658c3710d189) ) ROM_LOAD( "tr-02a.3j", 0x40000, 0x20000, CRC(1a2c5f89) SHA1(2a2aa2f1e2a0cdd4bbdb25236e49c7cc573db9e9) ) ROM_LOAD( "tr-05.3l", 0x60000, 0x20000, CRC(5bf453b3) SHA1(5eef151974c6b818a17756549d24a702e1f3a859) ) ROM_LOAD( "tr-03a.2f", 0x80000, 0x20000, CRC(1e0537ea) SHA1(bc65f7104d5f7728b68b3dcb45151c41fc30aa0d) ) ROM_LOAD( "tr-06a.2h", 0xa0000, 0x20000, CRC(b636c23a) SHA1(417e289745996bd00114df6ade591e702265d3a5) ) ROM_LOAD( "tr-07a.2j", 0xc0000, 0x20000, CRC(5f907d4d) SHA1(1820c5c6e0b078db9c64655c7983ea115ad81036) ) ROM_LOAD( "tr_08.2l", 0xe0000, 0x20000, CRC(adee35e2) SHA1(6707cf43a697eb9465449a144ae4508afe2e6496) ) // EPROM ROM_REGION( 0x080000, "spritegen", 0 ) ROM_LOAD32_BYTE( "tr-09a.3b", 0x00003, 0x20000, CRC(3d98ad1e) SHA1(f12cdf50e1708ddae092b9784d4319a7d5f092bc) ) ROM_LOAD32_BYTE( "tr-10a.2b", 0x00002, 0x20000, CRC(8f6f03d7) SHA1(08a02cfb373040ea5ffbf5604f68df92a1338bb0) ) ROM_LOAD32_BYTE( "tr-11a.3d", 0x00001, 0x20000, CRC(cd9152e5) SHA1(6df3c43c0c41289890296c2b2aeca915dfdae3b0) ) ROM_LOAD32_BYTE( "tr-12a.2d", 0x00000, 0x20000, CRC(7d8a99d0) SHA1(af8221cfd2ce9aa3bf296981fb7fddd1e9ef4599) ) ROM_REGION( 0x08000, "bgmap", 0 ) ROM_LOAD( "tr_13.7l", 0x0000, 0x8000, CRC(a79be1eb) SHA1(4191ccd48f7650930f9a4c2be0790239d7420bb1) ) ROM_REGION( 0x0100, "proms", 0 ) ROM_LOAD( "tr.9e", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) - N82S129A or compatible ROM_END ROM_START( tigeroadu ) // N86614A-5 + N86614B-6 board combo - US ROMSTAR program roms ROM_REGION( 0x40000, "maincpu", 0 ) // 256K for 68000 code ROM_LOAD16_BYTE( "tru_02.6j", 0x00000, 0x20000, CRC(8d283a95) SHA1(eb6c9225f79f62c22ae1e8980a557d896f598947) ) // Red ink underline ROM_LOAD16_BYTE( "tru_04.6k", 0x00001, 0x20000, CRC(72e2ef20) SHA1(57ab7df2050042690ccfb1f2d170840f926dcf46) ) // Red ink underline ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "tru_05.12k", 0x0000, 0x8000, CRC(f9a7c9bf) SHA1(4d37c71aa6523ac21c6e8b23f9957e75ec4304bf) ) // Red ink underline // i8751 microcontroller not populated // no samples player in the English version ROM_REGION( 0x008000, "text", 0 ) ROM_LOAD( "tr_01.10d", 0x00000, 0x08000, CRC(74a9f08c) SHA1(458958c8d9a2af5df88bb24c9c5bcbd37d6856bc) ) // 8x8 text ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "tr-01a.3f", 0x00000, 0x20000, CRC(a8aa2e59) SHA1(792f50d688a4ffb574e41257816bc304d41f0458) ) ROM_LOAD( "tr-04a.3h", 0x20000, 0x20000, CRC(8863a63c) SHA1(11bfce5b09c5b8a781c658f035d5658c3710d189) ) ROM_LOAD( "tr-02a.3j", 0x40000, 0x20000, CRC(1a2c5f89) SHA1(2a2aa2f1e2a0cdd4bbdb25236e49c7cc573db9e9) ) ROM_LOAD( "tr-05.3l", 0x60000, 0x20000, CRC(5bf453b3) SHA1(5eef151974c6b818a17756549d24a702e1f3a859) ) ROM_LOAD( "tr-03a.2f", 0x80000, 0x20000, CRC(1e0537ea) SHA1(bc65f7104d5f7728b68b3dcb45151c41fc30aa0d) ) ROM_LOAD( "tr-06a.2h", 0xa0000, 0x20000, CRC(b636c23a) SHA1(417e289745996bd00114df6ade591e702265d3a5) ) ROM_LOAD( "tr-07a.2j", 0xc0000, 0x20000, CRC(5f907d4d) SHA1(1820c5c6e0b078db9c64655c7983ea115ad81036) ) ROM_LOAD( "tr_08.2l", 0xe0000, 0x20000, CRC(adee35e2) SHA1(6707cf43a697eb9465449a144ae4508afe2e6496) ) // EPROM ROM_REGION( 0x080000, "spritegen", 0 ) ROM_LOAD32_BYTE( "tr-09a.3b", 0x00003, 0x20000, CRC(3d98ad1e) SHA1(f12cdf50e1708ddae092b9784d4319a7d5f092bc) ) ROM_LOAD32_BYTE( "tr-10a.2b", 0x00002, 0x20000, CRC(8f6f03d7) SHA1(08a02cfb373040ea5ffbf5604f68df92a1338bb0) ) ROM_LOAD32_BYTE( "tr-11a.3d", 0x00001, 0x20000, CRC(cd9152e5) SHA1(6df3c43c0c41289890296c2b2aeca915dfdae3b0) ) ROM_LOAD32_BYTE( "tr-12a.2d", 0x00000, 0x20000, CRC(7d8a99d0) SHA1(af8221cfd2ce9aa3bf296981fb7fddd1e9ef4599) ) ROM_REGION( 0x08000, "bgmap", 0 ) ROM_LOAD( "tr_13.7l", 0x0000, 0x8000, CRC(a79be1eb) SHA1(4191ccd48f7650930f9a4c2be0790239d7420bb1) ) ROM_REGION( 0x0100, "proms", 0 ) ROM_LOAD( "tr.9e", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) - N82S129A or compatible ROM_END ROM_START( toramich ) // N86614A-5 + N86614B-6 board combo ROM_REGION( 0x40000, "maincpu", 0 ) // 256K for 68000 code ROM_LOAD16_BYTE( "tr_02.6j", 0x00000, 0x20000, CRC(b54723b1) SHA1(dfad82e96dff072c967dd59e3db71fb3b43b6dcb) ) ROM_LOAD16_BYTE( "tr_04.6k", 0x00001, 0x20000, CRC(ab432479) SHA1(b8ec547f7bab67107a7c83931c7ed89142a7af69) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "tr_05.12k", 0x0000, 0x8000, CRC(3ebe6e62) SHA1(6f5708b6ff8c91bc706f73300e0785f15999d570) ) // i8751 microcontroller not populated ROM_REGION( 0x10000, "sample", 0 ) ROM_LOAD( "tr_03.11j", 0x0000, 0x10000, CRC(ea1807ef) SHA1(f856e7b592c6df81586821284ea2220468c5ea9d) ) ROM_REGION( 0x008000, "text", 0 ) ROM_LOAD( "tr_01.10d", 0x00000, 0x08000, CRC(74a9f08c) SHA1(458958c8d9a2af5df88bb24c9c5bcbd37d6856bc) ) // 8x8 text ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "tr-01a.3f", 0x00000, 0x20000, CRC(a8aa2e59) SHA1(792f50d688a4ffb574e41257816bc304d41f0458) ) ROM_LOAD( "tr-04a.3h", 0x20000, 0x20000, CRC(8863a63c) SHA1(11bfce5b09c5b8a781c658f035d5658c3710d189) ) ROM_LOAD( "tr-02a.3j", 0x40000, 0x20000, CRC(1a2c5f89) SHA1(2a2aa2f1e2a0cdd4bbdb25236e49c7cc573db9e9) ) ROM_LOAD( "tr-05.3l", 0x60000, 0x20000, CRC(5bf453b3) SHA1(5eef151974c6b818a17756549d24a702e1f3a859) ) ROM_LOAD( "tr-03a.2f", 0x80000, 0x20000, CRC(1e0537ea) SHA1(bc65f7104d5f7728b68b3dcb45151c41fc30aa0d) ) ROM_LOAD( "tr-06a.2h", 0xa0000, 0x20000, CRC(b636c23a) SHA1(417e289745996bd00114df6ade591e702265d3a5) ) ROM_LOAD( "tr-07a.2j", 0xc0000, 0x20000, CRC(5f907d4d) SHA1(1820c5c6e0b078db9c64655c7983ea115ad81036) ) ROM_LOAD( "tr_08.2l", 0xe0000, 0x20000, CRC(adee35e2) SHA1(6707cf43a697eb9465449a144ae4508afe2e6496) ) // EPROM ROM_REGION( 0x080000, "spritegen", 0 ) ROM_LOAD32_BYTE( "tr-09a.3b", 0x00003, 0x20000, CRC(3d98ad1e) SHA1(f12cdf50e1708ddae092b9784d4319a7d5f092bc) ) ROM_LOAD32_BYTE( "tr-10a.2b", 0x00002, 0x20000, CRC(8f6f03d7) SHA1(08a02cfb373040ea5ffbf5604f68df92a1338bb0) ) ROM_LOAD32_BYTE( "tr-11a.3d", 0x00001, 0x20000, CRC(cd9152e5) SHA1(6df3c43c0c41289890296c2b2aeca915dfdae3b0) ) ROM_LOAD32_BYTE( "tr-12a.2d", 0x00000, 0x20000, CRC(7d8a99d0) SHA1(af8221cfd2ce9aa3bf296981fb7fddd1e9ef4599) ) ROM_REGION( 0x08000, "bgmap", 0 ) ROM_LOAD( "tr_13.7l", 0x0000, 0x8000, CRC(a79be1eb) SHA1(4191ccd48f7650930f9a4c2be0790239d7420bb1) ) ROM_REGION( 0x0100, "proms", 0 ) ROM_LOAD( "tr.9e", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) - N82S129A or compatible ROM_END ROM_START( tigeroadb ) ROM_REGION( 0x40000, "maincpu", 0 ) // 256K for 68000 code ROM_LOAD16_BYTE( "tgrroad.3", 0x00000, 0x10000, CRC(14c87e07) SHA1(31363b56dd9d387f3ebd7ca1c209148c389ec1aa) ) ROM_LOAD16_BYTE( "tgrroad.5", 0x00001, 0x10000, CRC(0904254c) SHA1(9ce7b8a699bc21618032db9b0c5494242ad77a6b) ) ROM_LOAD16_BYTE( "tgrroad.2", 0x20000, 0x10000, CRC(cedb1f46) SHA1(bc2d5730ff809fb0f38327d72485d472ab9da54d) ) ROM_LOAD16_BYTE( "tgrroad.4", 0x20001, 0x10000, CRC(e117f0b1) SHA1(ed0050247789bedaeb213c3d7c2d2cdb239bb4b4) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "tru05.bin", 0x0000, 0x8000, CRC(f9a7c9bf) SHA1(4d37c71aa6523ac21c6e8b23f9957e75ec4304bf) ) // no samples player in the English version ROM_REGION( 0x008000, "text", 0 ) ROM_LOAD( "tr01.bin", 0x00000, 0x08000, CRC(74a9f08c) SHA1(458958c8d9a2af5df88bb24c9c5bcbd37d6856bc) ) // 8x8 text ROM_REGION( 0x100000, "tiles", 0 ) ROM_LOAD( "tr-01a.bin", 0x00000, 0x20000, CRC(a8aa2e59) SHA1(792f50d688a4ffb574e41257816bc304d41f0458) ) ROM_LOAD( "tr-04a.bin", 0x20000, 0x20000, CRC(8863a63c) SHA1(11bfce5b09c5b8a781c658f035d5658c3710d189) ) ROM_LOAD( "tr-02a.bin", 0x40000, 0x20000, CRC(1a2c5f89) SHA1(2a2aa2f1e2a0cdd4bbdb25236e49c7cc573db9e9) ) ROM_LOAD( "tr05.bin", 0x60000, 0x20000, CRC(5bf453b3) SHA1(5eef151974c6b818a17756549d24a702e1f3a859) ) ROM_LOAD( "tr-03a.bin", 0x80000, 0x20000, CRC(1e0537ea) SHA1(bc65f7104d5f7728b68b3dcb45151c41fc30aa0d) ) ROM_LOAD( "tr-06a.bin", 0xa0000, 0x20000, CRC(b636c23a) SHA1(417e289745996bd00114df6ade591e702265d3a5) ) ROM_LOAD( "tr-07a.bin", 0xc0000, 0x20000, CRC(5f907d4d) SHA1(1820c5c6e0b078db9c64655c7983ea115ad81036) ) ROM_LOAD( "tgrroad.17", 0xe0000, 0x10000, CRC(3f7539cc) SHA1(ca3ef1fabcb0c7abd7bc211ba128d2433e3dbf26) ) ROM_LOAD( "tgrroad.18", 0xf0000, 0x10000, CRC(e2e053cb) SHA1(eb9432140fc167dec5d3273112933201be2be1b3) ) ROM_REGION( 0x080000, "spritegen", 0 ) ROM_LOAD32_BYTE( "tr-09a.bin", 0x00003, 0x20000, CRC(3d98ad1e) SHA1(f12cdf50e1708ddae092b9784d4319a7d5f092bc) ) ROM_LOAD32_BYTE( "tr-10a.bin", 0x00002, 0x20000, CRC(8f6f03d7) SHA1(08a02cfb373040ea5ffbf5604f68df92a1338bb0) ) ROM_LOAD32_BYTE( "tr-11a.bin", 0x00001, 0x20000, CRC(cd9152e5) SHA1(6df3c43c0c41289890296c2b2aeca915dfdae3b0) ) ROM_LOAD32_BYTE( "tr-12a.bin", 0x00000, 0x20000, CRC(7d8a99d0) SHA1(af8221cfd2ce9aa3bf296981fb7fddd1e9ef4599) ) ROM_REGION( 0x08000, "bgmap", 0 ) ROM_LOAD( "tr13.bin", 0x0000, 0x8000, CRC(a79be1eb) SHA1(4191ccd48f7650930f9a4c2be0790239d7420bb1) ) ROM_REGION( 0x0100, "proms", 0 ) ROM_LOAD( "trprom.bin", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) ROM_END ROM_START( f1dream ) // N86614A-5 + N86614B-6 board combo ROM_REGION( 0x40000, "maincpu", 0 ) // 256K for 68000 code ROM_LOAD16_BYTE( "f1_02.6j", 0x00000, 0x20000, CRC(3c2ec697) SHA1(bccb431ad92455484420f91770e91db6d69b09ec) ) ROM_LOAD16_BYTE( "f1_03.6k", 0x00001, 0x20000, CRC(85ebad91) SHA1(000f5c617417ff20ee9b378166776fecfacdff95) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "f1_04.12k", 0x0000, 0x8000, CRC(4b9a7524) SHA1(19004958c19ac0af35f2c97790b0082ee2c15bc4) ) ROM_REGION( 0x1000, "mcu", 0 ) // i8751 microcontroller ROM_LOAD( "f1.9j", 0x0000, 0x1000, CRC(c8e6075c) SHA1(d98bd358d30d22a8009cd2728dde1871a8140c23) ) // labeled F1 ROM_REGION( 0x008000, "text", 0 ) ROM_LOAD( "f1_01.10d", 0x00000, 0x08000, CRC(361caf00) SHA1(8a109e4e116d0c5eea86f9c57c05359754daa5b9) ) // 8x8 text ROM_REGION( 0x060000, "tiles", 0 ) ROM_LOAD( "f1_12.3f", 0x00000, 0x10000, CRC(bc13e43c) SHA1(f9528839858d7a45395062a43b71d80400c73173) ) ROM_LOAD( "f1_10.1f", 0x10000, 0x10000, CRC(f7617ad9) SHA1(746a0ec433d5246ac4dbae17d6498e3d154e2df1) ) ROM_LOAD( "f1_14.3h", 0x20000, 0x10000, CRC(e33cd438) SHA1(89a6faea19e8a01b38ba45413609603e559877e9) ) ROM_LOAD( "f1_11.2f", 0x30000, 0x10000, CRC(4aa49cd7) SHA1(b7052d51a3cb570299f4db1492a1293c4d8b067f) ) ROM_LOAD( "f1_09.17f", 0x40000, 0x10000, CRC(ca622155) SHA1(00ae4a8e9cad2c42a10b410b594b0e414ada6cfe) ) ROM_LOAD( "f1_13.2h", 0x50000, 0x10000, CRC(2a63961e) SHA1(a35e9bf0408716f460487a8d2ae336572a98d2fb) ) ROM_REGION( 0x040000, "spritegen", 0 ) ROM_LOAD32_BYTE( "f1_06.3b", 0x00003, 0x10000, CRC(5e54e391) SHA1(475c968bfeb41b0448e621f59724c7b70d184d36) ) ROM_LOAD32_BYTE( "f1_05.2b", 0x00002, 0x10000, CRC(cdd119fd) SHA1(e279ada53f5a1e2ada0195b93399731af213f518) ) ROM_LOAD32_BYTE( "f1_08.3d", 0x00001, 0x10000, CRC(811f2e22) SHA1(cca7e8cc43408c2c3067a731a98a8a6418a000aa) ) ROM_LOAD32_BYTE( "f1_07.2d", 0x00000, 0x10000, CRC(aa9a1233) SHA1(c2079ad81d67b54483ea5f69ac2edf276ad58ca9) ) ROM_REGION( 0x08000, "bgmap", 0 ) ROM_LOAD( "f1_15.7l", 0x0000, 0x8000, CRC(978758b7) SHA1(ebd415d70e2f1af3b1bd51f40e7d60f22369638c) ) ROM_REGION( 0x0100, "proms", 0 ) ROM_LOAD( "tr.9e", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) - N82S129A or compatible ROM_END ROM_START( f1dreamb ) ROM_REGION( 0x40000, "maincpu", 0 ) // 256K for 68000 code ROM_LOAD16_BYTE( "f1d_04.bin", 0x00000, 0x10000, CRC(903febad) SHA1(73726b220ce45e1f13798e50fb6455671f1150f3) ) ROM_LOAD16_BYTE( "f1d_05.bin", 0x00001, 0x10000, CRC(666fa2a7) SHA1(f38e71293368ddc586f437c38ced1d8ce91527ea) ) ROM_LOAD16_BYTE( "f1d_02.bin", 0x20000, 0x10000, CRC(98973c4c) SHA1(a73d396a1c3e43e6250d9e0ab1902d6f754d1ed9) ) ROM_LOAD16_BYTE( "f1d_03.bin", 0x20001, 0x10000, CRC(3d21c78a) SHA1(edee180131a5b4d507ce0490fd3890bdd03ce62f) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "12k_04.bin", 0x0000, 0x8000, CRC(4b9a7524) SHA1(19004958c19ac0af35f2c97790b0082ee2c15bc4) ) ROM_REGION( 0x008000, "text", 0 ) ROM_LOAD( "10d_01.bin", 0x00000, 0x08000, CRC(361caf00) SHA1(8a109e4e116d0c5eea86f9c57c05359754daa5b9) ) // 8x8 text ROM_REGION( 0x060000, "tiles", 0 ) ROM_LOAD( "03f_12.bin", 0x00000, 0x10000, CRC(bc13e43c) SHA1(f9528839858d7a45395062a43b71d80400c73173) ) ROM_LOAD( "01f_10.bin", 0x10000, 0x10000, CRC(f7617ad9) SHA1(746a0ec433d5246ac4dbae17d6498e3d154e2df1) ) ROM_LOAD( "03h_14.bin", 0x20000, 0x10000, CRC(e33cd438) SHA1(89a6faea19e8a01b38ba45413609603e559877e9) ) ROM_LOAD( "02f_11.bin", 0x30000, 0x10000, CRC(4aa49cd7) SHA1(b7052d51a3cb570299f4db1492a1293c4d8b067f) ) ROM_LOAD( "17f_09.bin", 0x40000, 0x10000, CRC(ca622155) SHA1(00ae4a8e9cad2c42a10b410b594b0e414ada6cfe) ) ROM_LOAD( "02h_13.bin", 0x50000, 0x10000, CRC(2a63961e) SHA1(a35e9bf0408716f460487a8d2ae336572a98d2fb) ) ROM_REGION( 0x040000, "spritegen", 0 ) ROM_LOAD32_BYTE( "03b_06.bin", 0x00003, 0x10000, CRC(5e54e391) SHA1(475c968bfeb41b0448e621f59724c7b70d184d36) ) ROM_LOAD32_BYTE( "02b_05.bin", 0x00002, 0x10000, CRC(cdd119fd) SHA1(e279ada53f5a1e2ada0195b93399731af213f518) ) ROM_LOAD32_BYTE( "03d_08.bin", 0x00001, 0x10000, CRC(811f2e22) SHA1(cca7e8cc43408c2c3067a731a98a8a6418a000aa) ) ROM_LOAD32_BYTE( "02d_07.bin", 0x00000, 0x10000, CRC(aa9a1233) SHA1(c2079ad81d67b54483ea5f69ac2edf276ad58ca9) ) ROM_REGION( 0x08000, "bgmap", 0 ) ROM_LOAD( "07l_15.bin", 0x0000, 0x8000, CRC(978758b7) SHA1(ebd415d70e2f1af3b1bd51f40e7d60f22369638c) ) ROM_REGION( 0x0100, "proms", 0 ) ROM_LOAD( "09e_tr.bin", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) ROM_END ROM_START( f1dreamba ) ROM_REGION( 0x40000, "maincpu", 0 ) // 256K for 68000 code ROM_LOAD16_BYTE( "3.bin", 0x00000, 0x10000, CRC(bdfbbbec) SHA1(08e058f0e612463a2975c4283b7210a3247a90ad) ) ROM_LOAD16_BYTE( "5.bin", 0x00001, 0x10000, CRC(cc47cfb2) SHA1(2a6c66f4e7e81550af2d94e4a219a0c03173039e) ) ROM_LOAD16_BYTE( "2.bin", 0x20000, 0x10000, CRC(a34f63fb) SHA1(db1ce7ff3a2496649d8357c3999c1ea1a06ba043) ) ROM_LOAD16_BYTE( "4.bin", 0x20001, 0x10000, CRC(f98db083) SHA1(07e3e611eed1a77b7cd99c231e401c18465445ce) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "12k_04.bin", 0x0000, 0x8000, CRC(4b9a7524) SHA1(19004958c19ac0af35f2c97790b0082ee2c15bc4) ) ROM_REGION( 0x008000, "text", 0 ) ROM_LOAD( "10d_01.bin", 0x00000, 0x08000, CRC(361caf00) SHA1(8a109e4e116d0c5eea86f9c57c05359754daa5b9) ) // 8x8 text ROM_REGION( 0x060000, "tiles", 0 ) ROM_LOAD( "03f_12.bin", 0x00000, 0x10000, CRC(bc13e43c) SHA1(f9528839858d7a45395062a43b71d80400c73173) ) ROM_LOAD( "01f_10.bin", 0x10000, 0x10000, CRC(f7617ad9) SHA1(746a0ec433d5246ac4dbae17d6498e3d154e2df1) ) ROM_LOAD( "03h_14.bin", 0x20000, 0x10000, CRC(e33cd438) SHA1(89a6faea19e8a01b38ba45413609603e559877e9) ) ROM_LOAD( "02f_11.bin", 0x30000, 0x10000, CRC(4aa49cd7) SHA1(b7052d51a3cb570299f4db1492a1293c4d8b067f) ) ROM_LOAD( "17f_09.bin", 0x40000, 0x10000, CRC(ca622155) SHA1(00ae4a8e9cad2c42a10b410b594b0e414ada6cfe) ) ROM_LOAD( "02h_13.bin", 0x50000, 0x10000, CRC(2a63961e) SHA1(a35e9bf0408716f460487a8d2ae336572a98d2fb) ) ROM_REGION( 0x040000, "spritegen", 0 ) ROM_LOAD32_BYTE( "03b_06.bin", 0x00003, 0x10000, CRC(5e54e391) SHA1(475c968bfeb41b0448e621f59724c7b70d184d36) ) ROM_LOAD32_BYTE( "02b_05.bin", 0x00002, 0x10000, CRC(cdd119fd) SHA1(e279ada53f5a1e2ada0195b93399731af213f518) ) ROM_LOAD32_BYTE( "03d_08.bin", 0x00001, 0x10000, CRC(811f2e22) SHA1(cca7e8cc43408c2c3067a731a98a8a6418a000aa) ) ROM_LOAD32_BYTE( "02d_07.bin", 0x00000, 0x10000, CRC(aa9a1233) SHA1(c2079ad81d67b54483ea5f69ac2edf276ad58ca9) ) ROM_REGION( 0x08000, "bgmap", 0 ) ROM_LOAD( "07l_15.bin", 0x0000, 0x8000, CRC(978758b7) SHA1(ebd415d70e2f1af3b1bd51f40e7d60f22369638c) ) ROM_REGION( 0x0100, "proms", 0 ) ROM_LOAD( "09e_tr.bin", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) ROM_END ROM_START( pushman ) ROM_REGION( 0x40000, "maincpu", 0 ) ROM_LOAD16_BYTE( "pushman.012", 0x000000, 0x10000, CRC(330762bc) SHA1(c769b68da40183e6eb84212636bfd1265e5ed2d8) ) ROM_LOAD16_BYTE( "pushman.011", 0x000001, 0x10000, CRC(62636796) SHA1(1a205c1b0efff4158439bc9a21cfe3cd8834aef9) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "pushman.013", 0x00000, 0x08000, CRC(adfe66c1) SHA1(fa4ed13d655c664b06e9b91292d2c0a88cb5a569) ) ROM_REGION( 0x01000, "mcu", 0 ) // Verified same for all 4 currently dumped versions ROM_LOAD( "pushman68705r3p.ic23", 0x00000, 0x01000, CRC(d7916657) SHA1(89c14c6044f082fffe2a8f86d0a82336f4a110a2) ) ROM_REGION( 0x10000, "text", 0 ) ROM_LOAD( "pushman.001", 0x00000, 0x08000, CRC(626e5865) SHA1(4ab96c8512f439d18390094d71a898f5c576399c) ) ROM_REGION( 0x40000, "spritegen", 0 ) ROM_LOAD32_BYTE( "pushman.004", 0x00000, 0x10000, CRC(87aafa70) SHA1(560661b23ddac106a3d2762fc32da666b31e7424) ) ROM_LOAD32_BYTE( "pushman.005", 0x00001, 0x10000, CRC(7fd1200c) SHA1(15d6781a2d7e3ec2e8f85f8585b1e3fd9fe4fd1d) ) ROM_LOAD32_BYTE( "pushman.002", 0x00002, 0x10000, CRC(0a094ab0) SHA1(2ff5dcf0d9439eeadd61601170c9767f4d81f022) ) ROM_LOAD32_BYTE( "pushman.003", 0x00003, 0x10000, CRC(73d1f29d) SHA1(0a87fe02b1efd04c540f016b2626d32da70219db) ) ROM_REGION( 0x40000, "tiles", 0 ) ROM_LOAD( "pushman.006", 0x20000, 0x10000, CRC(48ef3da6) SHA1(407d50c2030584bb17a4d4a1bb45e0b04e1a95a4) ) ROM_LOAD( "pushman.008", 0x30000, 0x10000, CRC(4b6a3e88) SHA1(c57d0528e942dd77a13e5a4bf39053f52915d44c) ) ROM_LOAD( "pushman.007", 0x00000, 0x10000, CRC(b70020bd) SHA1(218ca4a08b87b7dc5c1eed99960f4098c4fc7e0c) ) ROM_LOAD( "pushman.009", 0x10000, 0x10000, CRC(cc555667) SHA1(6c79e14fc18d1d836392044779cb3219494a3447) ) ROM_REGION( 0x10000, "bgmap", 0 ) ROM_LOAD( "pushman.010", 0x00000, 0x08000, CRC(a500132d) SHA1(26b02c9fea69b51c5f7dc1b43b838cd336ebf862) ) ROM_REGION( 0x0100, "proms", 0 ) // this is the same as tiger road / f1-dream ROM_LOAD( "n82s129an.ic82", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) ROM_END ROM_START( pushmana ) ROM_REGION( 0x40000, "maincpu", 0 ) ROM_LOAD16_BYTE( "pushmana.212", 0x000000, 0x10000, CRC(871d0858) SHA1(690ca554c8c6f19c0f26ccd8d948e3aa6e1b23c0) ) ROM_LOAD16_BYTE( "pushmana.011", 0x000001, 0x10000, CRC(ae57761e) SHA1(63467d61c967f38e0fbb8130f08e09e03cdcce6c) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "pushman.013", 0x00000, 0x08000, CRC(adfe66c1) SHA1(fa4ed13d655c664b06e9b91292d2c0a88cb5a569) ) // missing from this set? ROM_REGION( 0x01000, "mcu", 0 ) // Verified same for all 4 currently dumped versions ROM_LOAD( "pushman68705r3p.ic23", 0x00000, 0x01000, CRC(d7916657) SHA1(89c14c6044f082fffe2a8f86d0a82336f4a110a2) ) ROM_REGION( 0x10000, "text", 0 ) ROM_LOAD( "pushmana.130", 0x00000, 0x10000, CRC(f83f92e7) SHA1(37f337d7b496f8d81eed247c80390a6aabcf4b95) ) ROM_REGION( 0x40000, "spritegen", 0 ) ROM_LOAD32_BYTE( "pushman.004", 0x00000, 0x10000, CRC(87aafa70) SHA1(560661b23ddac106a3d2762fc32da666b31e7424) ) // .58 ROM_LOAD32_BYTE( "pushman.005", 0x00001, 0x10000, CRC(7fd1200c) SHA1(15d6781a2d7e3ec2e8f85f8585b1e3fd9fe4fd1d) ) // .59 ROM_LOAD32_BYTE( "pushman.002", 0x00002, 0x10000, CRC(0a094ab0) SHA1(2ff5dcf0d9439eeadd61601170c9767f4d81f022) ) // .56 ROM_LOAD32_BYTE( "pushman.003", 0x00003, 0x10000, CRC(73d1f29d) SHA1(0a87fe02b1efd04c540f016b2626d32da70219db) ) // .57 ROM_REGION( 0x40000, "tiles", 0 ) ROM_LOAD( "pushman.006", 0x20000, 0x10000, CRC(48ef3da6) SHA1(407d50c2030584bb17a4d4a1bb45e0b04e1a95a4) ) // .131 ROM_LOAD( "pushman.008", 0x30000, 0x10000, CRC(4b6a3e88) SHA1(c57d0528e942dd77a13e5a4bf39053f52915d44c) ) // .148 ROM_LOAD( "pushman.007", 0x00000, 0x10000, CRC(b70020bd) SHA1(218ca4a08b87b7dc5c1eed99960f4098c4fc7e0c) ) // .132 ROM_LOAD( "pushman.009", 0x10000, 0x10000, CRC(cc555667) SHA1(6c79e14fc18d1d836392044779cb3219494a3447) ) // .149 ROM_REGION( 0x10000, "bgmap", 0 ) ROM_LOAD( "pushmana.189", 0x00000, 0x10000, CRC(59f25598) SHA1(ace33afd6e6d07376ed01048db99b13bcec790d7) ) ROM_REGION( 0x0100, "proms", 0 ) // this is the same as tiger road / f1-dream ROM_LOAD( "n82s129an.ic82", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) ROM_END ROM_START( pushmans ) ROM_REGION( 0x40000, "maincpu", 0 ) ROM_LOAD16_BYTE( "pman-12.ic212", 0x000000, 0x10000, CRC(4251109d) SHA1(d4b020e4ecc2005b3a4c1b34d88de82b09bf5a6b) ) ROM_LOAD16_BYTE( "pman-11.ic197", 0x000001, 0x10000, CRC(1167ed9f) SHA1(ca0296950a75ef15ff6f9d3a776b02180b941d61) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "pman-13.ic216", 0x00000, 0x08000, CRC(bc03827a) SHA1(b4d6ae164bbb7ba19e4934392fe2ba29575f28b9) ) ROM_REGION( 0x01000, "mcu", 0 ) // Verified same for all 4 currently dumped versions ROM_LOAD( "pushman68705r3p.ic23", 0x00000, 0x01000, CRC(d7916657) SHA1(89c14c6044f082fffe2a8f86d0a82336f4a110a2) ) ROM_REGION( 0x10000, "text", 0 ) ROM_LOAD( "pman-1.ic130", 0x00000, 0x08000, CRC(14497754) SHA1(a47d03c56add18c5d9aed221990550b18589ff43) ) ROM_REGION( 0x40000, "spritegen", 0 ) ROM_LOAD32_BYTE( "pman-4.ic58", 0x00000, 0x10000, CRC(16e5ce6b) SHA1(cb9c6094a853abc550eae29c35083f26a0d1de94) ) ROM_LOAD32_BYTE( "pman-5.ic59", 0x00001, 0x10000, CRC(b82140b8) SHA1(0a16b904eb2739bfa22a87d03266d3ff2b750b67) ) ROM_LOAD32_BYTE( "pman-2.56", 0x00002, 0x10000, CRC(2cb2ac29) SHA1(165447ad7eb8593c0d4346096ec13ac386e905c9) ) ROM_LOAD32_BYTE( "pman-3.57", 0x00003, 0x10000, CRC(8ab957c8) SHA1(143501819920c521353930f83e49f1e19fbba34f) ) ROM_REGION( 0x40000, "tiles", 0 ) ROM_LOAD( "pman-6.ic131", 0x20000, 0x10000, CRC(bd0f9025) SHA1(7262410d4631f1b051c605d5cea5b91e9f68327e) ) ROM_LOAD( "pman-8.ic148", 0x30000, 0x10000, CRC(591bd5c0) SHA1(6e0e18e0912fa38e113420ac31c7f36853b830ec) ) ROM_LOAD( "pman-7.ic132", 0x00000, 0x10000, CRC(208cb197) SHA1(161633b6b0acf25447a5c0b3c6fbf18adc6e2243) ) ROM_LOAD( "pman-9.ic149", 0x10000, 0x10000, CRC(77ee8577) SHA1(63d13683dd097d8e7cb71ad3abe04e11f2a58bd3) ) ROM_REGION( 0x10000, "bgmap", 0 ) ROM_LOAD( "pman-10.ic189", 0x00000, 0x08000, CRC(5f9ae9a1) SHA1(87619918c28c942780f6dbd3818d4cc69932eefc) ) ROM_REGION( 0x0100, "proms", 0 ) // this is the same as tiger road / f1-dream ROM_LOAD( "n82s129an.ic82", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) ROM_END ROM_START( pushmant ) // Single plane PCB ROM_REGION( 0x40000, "maincpu", 0 ) ROM_LOAD16_BYTE( "12.ic212", 0x000000, 0x10000, CRC(f5c77d86) SHA1(66d2d5dc9f4662efc5a865c9cc1bba653e86a674) ) ROM_LOAD16_BYTE( "11.ic197", 0x000001, 0x10000, CRC(2e09ff08) SHA1(9bb05c51c985c3a12fb8d6fd915276e304651eb1) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "13.ic216", 0x00000, 0x08000, CRC(adfe66c1) SHA1(fa4ed13d655c664b06e9b91292d2c0a88cb5a569) ) // Same as the Comad set ROM_REGION( 0x01000, "mcu", 0 ) // Verified same for all 4 currently dumped versions ROM_LOAD( "pushman68705r3p.ic23", 0x00000, 0x01000, CRC(d7916657) SHA1(89c14c6044f082fffe2a8f86d0a82336f4a110a2) ) ROM_REGION( 0x10000, "text", 0 ) ROM_LOAD( "1.ic130", 0x00000, 0x08000, CRC(14497754) SHA1(a47d03c56add18c5d9aed221990550b18589ff43) ) // Same as the Sammy set ROM_REGION( 0x40000, "spritegen", 0 ) ROM_LOAD32_BYTE( "4.ic58", 0x00000, 0x10000, CRC(69209214) SHA1(c5b527234aefbdfb39864806e2b1784fdf2dd49c) ) ROM_LOAD32_BYTE( "5.ic59", 0x00001, 0x10000, CRC(75fc0ac4) SHA1(aa3a19573b96d89b94bfddda5b404d19cbb47335) ) ROM_LOAD32_BYTE( "2.ic56", 0x00002, 0x10000, CRC(2bb8093f) SHA1(e86048d676b06796a1d2ed325ea8ea9cada3c4b6) ) ROM_LOAD32_BYTE( "3.ic57", 0x00003, 0x10000, CRC(5f1c4e7a) SHA1(751caf2365eccbab6d7de5434c4656ac5bd7f13b) ) ROM_REGION( 0x40000, "tiles", 0 ) ROM_LOAD( "6.ic131", 0x20000, 0x10000, CRC(bd0f9025) SHA1(7262410d4631f1b051c605d5cea5b91e9f68327e) ) // These 4 are the same as the Sammy set ROM_LOAD( "8.ic148", 0x30000, 0x10000, CRC(591bd5c0) SHA1(6e0e18e0912fa38e113420ac31c7f36853b830ec) ) ROM_LOAD( "7.ic132", 0x00000, 0x10000, CRC(208cb197) SHA1(161633b6b0acf25447a5c0b3c6fbf18adc6e2243) ) ROM_LOAD( "9.ic149", 0x10000, 0x10000, CRC(77ee8577) SHA1(63d13683dd097d8e7cb71ad3abe04e11f2a58bd3) ) ROM_REGION( 0x10000, "bgmap", 0 ) ROM_LOAD( "10.ic189", 0x00000, 0x08000, CRC(5f9ae9a1) SHA1(87619918c28c942780f6dbd3818d4cc69932eefc) ) // Same as the Sammy set ROM_REGION( 0x0100, "proms", 0 ) // this is the same as tiger road / f1-dream ROM_LOAD( "n82s129an.ic82", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) ROM_END ROM_START( bballs ) ROM_REGION( 0x40000, "maincpu", 0 ) ROM_LOAD16_BYTE( "bb12.m17", 0x000000, 0x10000, CRC(4501c245) SHA1(b03ace135b077e8c226dd3be04fa8e86ad096770) ) ROM_LOAD16_BYTE( "bb11.l17", 0x000001, 0x10000, CRC(55e45b60) SHA1(103d848ae74b59ac2f5a5c5300323bbf8b109752) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "bb13.n4", 0x00000, 0x08000, CRC(1ef78175) SHA1(2e7dcbab3a572c2a6bb67a36ba283a5faeb14a88) ) ROM_REGION( 0x01000, "mcu", 0 ) // using dump from bballsa set ROM_LOAD( "mc68705r3.bin", 0x00000, 0x01000, CRC(4b37b853) SHA1(c95b7b1dcc6f4730fd08535001e2f02b34ea14c2) BAD_DUMP ) ROM_REGION( 0x10000, "text", 0 ) ROM_LOAD( "bb1.g20", 0x00000, 0x08000, CRC(b62dbcb8) SHA1(121613f6d2bcd226e71d4ae71830b9b0d15c2331) ) ROM_REGION( 0x40000, "spritegen", 0 ) ROM_LOAD32_BYTE( "bb4.d1", 0x00000, 0x10000, CRC(b77de5f8) SHA1(e966f982d712109c4402ca3a8cd2c19640d52bdb) ) ROM_LOAD32_BYTE( "bb5.d2", 0x00001, 0x10000, CRC(ffffccbf) SHA1(3ac85c06c3dca1de8839fca73f5de3982a3baca0) ) ROM_LOAD32_BYTE( "bb2.b1", 0x00002, 0x10000, CRC(a5b13236) SHA1(e2d21fa3c878b328238ba8b400f3ab00b0763f6b) ) ROM_LOAD32_BYTE( "bb3.b2", 0x00003, 0x10000, CRC(e35b383d) SHA1(5312e80d786dc2ffe0f7b1038a64f8ec6e590e0c) ) ROM_REGION( 0x40000, "tiles", 0 ) ROM_LOAD( "bb6.h1", 0x20000, 0x10000, CRC(0cada9ce) SHA1(5f2e85baf5f04e874e0857451946c8b1e1c8d209) ) ROM_LOAD( "bb8.j1", 0x30000, 0x10000, CRC(d55fe7c1) SHA1(de5ba87c0f905e6f1abadde3af63884a8a130806) ) ROM_LOAD( "bb7.h2", 0x00000, 0x10000, CRC(a352d53b) SHA1(c71e976b7c28630d7af11fffe0d1cfd7d611ee8b) ) ROM_LOAD( "bb9.j2", 0x10000, 0x10000, CRC(78d185ac) SHA1(6ed6e1f5eeb93129eeeab6bae22b640c9782f7fc) ) ROM_REGION( 0x10000, "bgmap", 0 ) ROM_LOAD( "bb10.l6", 0x00000, 0x08000, CRC(d06498f9) SHA1(9f33bbc40ebe11c03aec29289f76f1c3ca5bf009) ) ROM_REGION( 0x0100, "proms", 0 ) // this is the same as tiger road / f1-dream ROM_LOAD( "bb_prom.e9", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) N82S129 BPROM ROM_END ROM_START( bballsa ) ROM_REGION( 0x40000, "maincpu", 0 ) ROM_LOAD16_BYTE( "12.ic212", 0x000000, 0x10000, CRC(8917aedd) SHA1(ded983ba753699c97b02e991eb7195c0122b4065) ) ROM_LOAD16_BYTE( "11.ic197", 0x000001, 0x10000, CRC(430fca1b) SHA1(70ed70396f5346a3120f7a046a111fa114c997bc) ) ROM_REGION( 0x10000, "audiocpu", 0 ) ROM_LOAD( "13.ic216", 0x00000, 0x08000, CRC(1ef78175) SHA1(2e7dcbab3a572c2a6bb67a36ba283a5faeb14a88) ) ROM_REGION( 0x01000, "mcu", 0 ) ROM_LOAD( "mc68705r3.bin", 0x00000, 0x01000, CRC(4b37b853) SHA1(c95b7b1dcc6f4730fd08535001e2f02b34ea14c2) ) ROM_REGION( 0x10000, "text", 0 ) ROM_LOAD( "1.ic130", 0x00000, 0x08000, CRC(67672444) SHA1(f1d4681999d44e8d3cbf26b8a9c05f50573e0df6) ) ROM_REGION( 0x40000, "spritegen", 0 ) ROM_LOAD32_BYTE( "4.ic58", 0x00000, 0x10000, CRC(144ca816) SHA1(c166e3f42f12c14df977adad363575e786b2be51) ) ROM_LOAD32_BYTE( "5.ic59", 0x00001, 0x10000, CRC(486c8385) SHA1(4421160573a2435bb0f330a04fef486d14a1293b) ) ROM_LOAD32_BYTE( "2.ic56", 0x00002, 0x10000, CRC(1d464915) SHA1(3396e919da7e3d08a1a9c76db5d0d214ddf7adcd) ) ROM_LOAD32_BYTE( "3.ic57", 0x00003, 0x10000, CRC(595439ec) SHA1(6e1a79e5583960f700fd8a63cd48c7e222a315dc) ) ROM_REGION( 0x40000, "tiles", 0 ) ROM_LOAD( "6.ic131", 0x20000, 0x10000, CRC(15d4975b) SHA1(71dbb63e70a52ec12fdfc20047a48beb73fac8a0) ) ROM_LOAD( "8.ic148", 0x30000, 0x10000, CRC(c1a21c75) SHA1(34b877ac85274e50b2ce65945b9761e70e80b852) ) ROM_LOAD( "7.ic132", 0x00000, 0x10000, CRC(2289393a) SHA1(e1370925a92f7d9f96c9431cf1b8dd262c41017e) ) ROM_LOAD( "9.ic149", 0x10000, 0x10000, CRC(1fe3d172) SHA1(f7415e8633507a507ec1cd68de224722a726a473) ) ROM_REGION( 0x10000, "bgmap", 0 ) ROM_LOAD( "10.ic189", 0x00000, 0x08000, CRC(52e4ab27) SHA1(c9ae15f970b4bf120a4bbee9adcf0e5e4de001e7) ) ROM_REGION( 0x0100, "proms", 0 ) // this is the same as tiger road / f1-dream ROM_LOAD( "bb_prom.e9", 0x0000, 0x0100, CRC(ec80ae36) SHA1(397ec8fc1b106c8b8d4bf6798aa429e8768a101a) ) // priority (not used) N82S129 BPROM ROM_END /***************************************************************************/ GAME( 1987, tigeroad, 0, tigeroad, tigeroad, tigeroad_state, empty_init, ROT0, "Capcom", "Tiger Road (US)", MACHINE_SUPPORTS_SAVE ) GAME( 1987, tigeroadu, tigeroad, tigeroad, tigeroad, tigeroad_state, empty_init, ROT0, "Capcom (Romstar license)", "Tiger Road (US, Romstar license)", MACHINE_SUPPORTS_SAVE ) GAME( 1987, toramich, tigeroad, toramich, toramich, tigeroad_state, empty_init, ROT0, "Capcom", "Tora e no Michi (Japan)", MACHINE_SUPPORTS_SAVE ) GAME( 1987, tigeroadb, tigeroad, tigeroad, tigeroad, tigeroad_state, empty_init, ROT0, "bootleg", "Tiger Road (US bootleg)", MACHINE_SUPPORTS_SAVE ) // F1 Dream has an Intel 8751 microcontroller for protection GAME( 1988, f1dream, 0, f1dream, f1dream, f1dream_state, empty_init, ROT0, "Capcom (Romstar license)", "F-1 Dream", MACHINE_SUPPORTS_SAVE ) GAME( 1988, f1dreamb, f1dream, tigeroad, f1dream, tigeroad_state, empty_init, ROT0, "bootleg", "F-1 Dream (bootleg, set 1)", MACHINE_SUPPORTS_SAVE ) GAME( 1988, f1dreamba,f1dream, tigeroad, f1dream, tigeroad_state, empty_init, ROT0, "bootleg", "F-1 Dream (bootleg, set 2)", MACHINE_SUPPORTS_SAVE ) // This Comad hardware is based around the F1 Dream design GAME( 1990, pushman, 0, pushman, pushman, pushman_state, empty_init, ROT0, "Comad", "Pushman (Korea, set 1)", MACHINE_SUPPORTS_SAVE ) GAME( 1990, pushmana, pushman, pushman, pushman, pushman_state, empty_init, ROT0, "Comad", "Pushman (Korea, set 2)", MACHINE_SUPPORTS_SAVE ) GAME( 1990, pushmans, pushman, pushman, pushman, pushman_state, empty_init, ROT0, "Comad (American Sammy license)", "Pushman (American Sammy license)", MACHINE_SUPPORTS_SAVE ) GAME( 1990, pushmant, pushman, pushman, pushman, pushman_state, empty_init, ROT0, "Comad (Top Tronic license)", "Pushman (Top Tronic license)", MACHINE_SUPPORTS_SAVE ) GAME( 1991, bballs, 0, bballs, bballs, pushman_state, empty_init, ROT0, "Comad", "Bouncing Balls", MACHINE_SUPPORTS_SAVE ) GAME( 1991, bballsa, bballs, bballs, bballs, pushman_state, empty_init, ROT0, "Comad", "Bouncing Balls (Adult)", MACHINE_SUPPORTS_SAVE )
51.245823
175
0.743464
[ "3d" ]
0366a11d27dedb7eaefb51336991c8b67bfd4013
3,062
hh
C++
isaac_variant_caller/src/lib/blt_util/nploid_genotype_util.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
21
2015-01-09T01:11:28.000Z
2019-09-04T03:48:21.000Z
isaac_variant_caller/src/lib/blt_util/nploid_genotype_util.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
4
2015-07-23T09:38:39.000Z
2018-02-01T05:37:26.000Z
isaac_variant_caller/src/lib/blt_util/nploid_genotype_util.hh
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
13
2015-01-29T16:41:26.000Z
2021-06-25T02:42:32.000Z
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Copyright (c) 2009-2013 Illumina, Inc. // // This software is provided under the terms and conditions of the // Illumina Open Source Software License 1. // // You should have received a copy of the Illumina Open Source // Software License 1 along with this program. If not, see // <https://github.com/sequencing/licenses/> // /// \file /// \author Chris Saunders /// #ifndef __NPLOID_GENOTYPE_UTIL_HH #define __NPLOID_GENOTYPE_UTIL_HH #include "blt_util/seq_util.hh" #include <boost/utility.hpp> #include <string> #include <vector> unsigned nploid_gtype_size(const unsigned ploidy); /// pre-compute genotype count, labels and allele frequencies for any /// given ploidy: /// struct nploid_info : private boost::noncopyable { nploid_info(const unsigned init_ploidy); unsigned ploidy() const { return _ploidy; } unsigned gtype_size() const { return _ginfo.size(); } const char* label(const unsigned gt_index) const { return _ginfo[gt_index].label.c_str(); } unsigned get_ref_gtype(const char a) const { return _ref_gtype[base_to_id(a)]; } /// look up expectation frequencies directly: double expect_freq(const unsigned gt_index, const unsigned base_id) const { return expect_freq_level(gt_index,base_id)*expect_freq_chunk(); } /// expectation frequencies will always be multiples of 1/ploidy, /// so more efficient client code can be written by asking for freq /// level and chunk size, where expect=level*chunk, chunk=1/ploidy /// double expect_freq_chunk() const { return _echunk; } unsigned expect_freq_level(const unsigned gt_index, const unsigned base_id) const { return _ginfo[gt_index].efreq_levels[base_id]; } unsigned expect_freq_level_size() const { return _ploidy+1; } private: struct gtype_info { gtype_info() { for (unsigned i(0); i<N_BASE; ++i) efreq_levels[i]=0; } gtype_info(const gtype_info& g) : label(g.label) { for (unsigned i(0); i<N_BASE; ++i) efreq_levels[i]=g.efreq_levels[i]; } gtype_info& operator=(const gtype_info& rhs) { if ( this == &rhs ) return *this; label=rhs.label; for (unsigned i(0); i<N_BASE; ++i) efreq_levels[i]=rhs.efreq_levels[i]; return *this; } std::string label; unsigned efreq_levels[N_BASE]; }; void ginfo_init(const unsigned init_ploidy, const unsigned pli, const unsigned init_i, gtype_info& gi); void ref_gtype_init(const unsigned init_ploidy, const unsigned pli, const unsigned init_i, const bool is_hom, unsigned*& ref, unsigned& index); unsigned _ploidy; double _echunk; std::vector<gtype_info> _ginfo; unsigned _ref_gtype[N_BASE]; }; #endif
25.098361
83
0.627694
[ "vector" ]
036b458971ff934f3a664e2127bb3711291bcf80
2,212
cpp
C++
Street-Combat/src/character.cpp
SakshayMahna/AI-for-Game-Programming
de2df8b25b233e6db08971226eece2cab2a7f3ef
[ "MIT" ]
null
null
null
Street-Combat/src/character.cpp
SakshayMahna/AI-for-Game-Programming
de2df8b25b233e6db08971226eece2cab2a7f3ef
[ "MIT" ]
null
null
null
Street-Combat/src/character.cpp
SakshayMahna/AI-for-Game-Programming
de2df8b25b233e6db08971226eece2cab2a7f3ef
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <cmath> #include <iostream> #include <algorithm> #include <string> #include "character.h" #include "animation.h" const float HEALTH_HEIGHT = 20; const float HEALTH_WIDTH = 1000; const float HEALTH_OFFSET = 100; // Character constructor Character::Character(float i_position[2], sf::Color color, std::string texture_filename, bool enemy, float h_height) { // Initialize attributes health = 100; health_entity.setFillColor(color); health_entity.setPosition(HEALTH_OFFSET, h_height); health_entity.setSize(sf::Vector2f(HEALTH_WIDTH * (health / 100), HEALTH_HEIGHT)); block = false; // Initialize position position[0] = i_position[0]; position[1] = i_position[1]; // Initialize entity and texture texture = TextureManager(); texture.load_texture("animation", texture_filename); entity.setPosition(i_position[0], i_position[1]); if (enemy) entity.setScale(-1.5, 1.5); else entity.setScale(1.5, 1.5); entity.setTexture(texture.getRef("animation")); } // Character Position Update void Character::updatePosition(float d_x, float d_y) { // Update position position[0] += d_x; position[1] += d_y; entity.move(d_x, d_y); } // Initialize animation void Character::initializeAnimations(int left, int top, int width, int height, std::vector<int> durations) { handler = AnimationHandler(sf::IntRect(left, top, width, height)); for (int duration : durations) { Animation anim = Animation(1, duration - 1, duration); handler.add_animation(anim); } handler.change_animation(0); entity.setTextureRect(handler.bounds); } // Animation Function void Character::animate(int animation_id) { handler.change_animation(animation_id); handler.update(0.03); entity.setTextureRect(handler.bounds); } // Render function void Character::render(sf::RenderWindow &window) { window.draw(entity); window.draw(health_entity); } // Change the health of character void Character::changeHealth(float dh) { health += dh; health_entity.setSize(sf::Vector2f(HEALTH_WIDTH * (health / 100), HEALTH_HEIGHT)); }
27.65
108
0.690778
[ "render", "vector" ]
036f694ba0723f4f29390ae69cdc43acb99d09f5
21,901
cpp
C++
code/graphics/generic.cpp
MageKing17/fs2open.github.com
84b25b52d7d775af8a810d70e6beb6d20405b58c
[ "Unlicense" ]
1
2015-04-24T12:37:48.000Z
2015-04-24T12:37:48.000Z
code/graphics/generic.cpp
JohnAFernandez/fs2open.github.com
c0bb5bc8eb640c3932aefd3dfad1fd4758571cff
[ "Unlicense" ]
4
2015-03-30T20:33:03.000Z
2020-06-03T08:48:35.000Z
code/graphics/generic.cpp
JohnAFernandez/fs2open.github.com
c0bb5bc8eb640c3932aefd3dfad1fd4758571cff
[ "Unlicense" ]
1
2021-05-22T16:37:50.000Z
2021-05-22T16:37:50.000Z
#include "anim/packunpack.h" #include "globalincs/globals.h" #include "graphics/2d.h" #include "graphics/generic.h" #define BMPMAN_INTERNAL #include "bmpman/bm_internal.h" #ifdef _WIN32 #include <windows.h> // for MAX_PATH #else #define MAX_PATH 255 #endif //#define TIMER #ifdef TIMER #include "io/timer.h" #endif //we check background type to avoid messed up colours for ANI #define ANI_BPP_CHECK (ga->ani.bg_type == BM_TYPE_PCX) ? 16 : 32 // These two functions find if a bitmap or animation exists by filename, no extension needed. bool generic_bitmap_exists(const char *filename) { return cf_exists_full_ext(filename, CF_TYPE_ANY, BM_NUM_TYPES, bm_ext_list) != 0; } bool generic_anim_exists(const char *filename) { return cf_exists_full_ext(filename, CF_TYPE_ANY, BM_ANI_NUM_TYPES, bm_ani_ext_list) != 0; } // Goober5000 int generic_anim_init_and_stream(generic_anim *ga, const char *anim_filename, BM_TYPE bg_type, bool attempt_hi_res) { int stream_result = -1; char filename[NAME_LENGTH]; char *p; Assert(ga != NULL); Assert(anim_filename != NULL); // hi-res support if (attempt_hi_res && (gr_screen.res == GR_1024)) { // attempt to load a hi-res animation memset(filename, 0, NAME_LENGTH); strcpy_s(filename, "2_"); strncat(filename, anim_filename, NAME_LENGTH - 3); // remove extension p = strchr(filename, '.'); if(p) { *p = '\0'; } // attempt to stream the hi-res ani generic_anim_init(ga, filename); ga->ani.bg_type = bg_type; stream_result = generic_anim_stream(ga); } // we failed to stream hi-res, or we aren't running in hi-res, so try low-res if (stream_result < 0) { strcpy_s(filename, anim_filename); // remove extension p = strchr(filename, '.'); if(p) { *p = '\0'; } // attempt to stream the low-res ani generic_anim_init(ga, filename); ga->ani.bg_type = bg_type; stream_result = generic_anim_stream(ga); } return stream_result; } // Goober5000 void generic_anim_init(generic_anim *ga) { generic_anim_init(ga, NULL); } // Goober5000 void generic_anim_init(generic_anim *ga, const char *filename) { if (filename != NULL) strcpy_s(ga->filename, filename); else memset(ga->filename, 0, MAX_FILENAME_LEN); ga->first_frame = -1; ga->num_frames = 0; ga->keyframe = 0; ga->keyoffset = 0; ga->current_frame = 0; ga->previous_frame = -1; ga->direction = GENERIC_ANIM_DIRECTION_FORWARDS; ga->done_playing = 0; ga->total_time = 0.0f; ga->anim_time = 0.0f; //we only care about the stuff below if we're streaming ga->ani.animation = NULL; ga->ani.instance = NULL; ga->ani.bg_type = BM_TYPE_NONE; ga->type = BM_TYPE_NONE; ga->streaming = 0; ga->buffer = NULL; ga->height = 0; ga->width = 0; ga->bitmap_id = -1; ga->use_hud_color = false; } // CommanderDJ - same as generic_anim_init, just with an SCP_string void generic_anim_init(generic_anim *ga, const SCP_string& filename) { generic_anim_init(ga); filename.copy(ga->filename, MAX_FILENAME_LEN - 1); } // Goober5000 void generic_bitmap_init(generic_bitmap *gb, const char *filename) { if (filename == NULL) { gb->filename[0] = '\0'; } else { strncpy(gb->filename, filename, MAX_FILENAME_LEN - 1); } gb->bitmap_id = -1; } // Goober5000 // load a generic_anim // return 0 is successful, otherwise return -1 int generic_anim_load(generic_anim *ga) { int fps; if ( !VALID_FNAME(ga->filename) ) return -1; ga->first_frame = bm_load_animation(ga->filename, &ga->num_frames, &fps, &ga->keyframe, &ga->total_time); //mprintf(("generic_anim_load: %s - keyframe = %d\n", ga->filename, ga->keyframe)); if (ga->first_frame < 0) return -1; ga->done_playing = 0; ga->anim_time = 0.0f; return 0; } int generic_anim_stream(generic_anim *ga, const bool cache) { CFILE *img_cfp = NULL; int anim_fps = 0; int bpp; ga->type = BM_TYPE_NONE; auto res = cf_find_file_location_ext(ga->filename, BM_ANI_NUM_TYPES, bm_ani_ext_list, CF_TYPE_ANY, false); // could not be found, or is invalid for some reason if ( !res.found ) return -1; //make sure we can open it img_cfp = cfopen_special(res, "rb", CF_TYPE_ANY); if (img_cfp == NULL) { return -1; } strcat_s(ga->filename, bm_ani_ext_list[res.extension_index]); ga->type = bm_ani_type_list[res.extension_index]; //seek to the end cfseek(img_cfp, 0, CF_SEEK_END); cfclose(img_cfp); if(ga->type == BM_TYPE_ANI) { bpp = ANI_BPP_CHECK; if(ga->use_hud_color) bpp = 8; if (ga->ani.animation == nullptr) { ga->ani.animation = anim_load(ga->filename, CF_TYPE_ANY, 0); } if (ga->ani.instance == nullptr) { ga->ani.instance = init_anim_instance(ga->ani.animation, bpp); } #ifndef NDEBUG // for debug of ANI sizes strcpy_s(ga->ani.animation->name, ga->filename); #endif ga->num_frames = ga->ani.animation->total_frames; anim_fps = ga->ani.animation->fps; ga->height = ga->ani.animation->height; ga->width = ga->ani.animation->width; ga->buffer = ga->ani.instance->frame; ga->bitmap_id = bm_create(bpp, ga->width, ga->height, ga->buffer, (bpp==8)?BMP_AABITMAP:0); ga->ani.instance->last_bitmap = -1; ga->ani.instance->file_offset = ga->ani.animation->file_offset; ga->ani.instance->data = ga->ani.animation->data; ga->previous_frame = -1; } else if (ga->type == BM_TYPE_PNG) { if (ga->png.anim == nullptr) { try { ga->png.anim = new apng::apng_ani(ga->filename, cache); } catch (const apng::ApngException& e) { mprintf(("Failed to load apng: %s\n", e.what() )); delete ga->png.anim; ga->png.anim = nullptr; ga->type = BM_TYPE_NONE; return -1; } nprintf(("apng", "apng read OK (%ix%i@%i) duration (%f)\n", ga->png.anim->w, ga->png.anim->h, ga->png.anim->bpp, ga->png.anim->anim_time)); } ga->png.anim->goto_start(); ga->current_frame = 0; ga->png.previous_frame_time = 0.0f; ga->num_frames = ga->png.anim->nframes; ga->height = ga->png.anim->h; ga->width = ga->png.anim->w; ga->previous_frame = -1; ga->buffer = ga->png.anim->frame.data.data(); ga->bitmap_id = bm_create(ga->png.anim->bpp, ga->width, ga->height, ga->buffer, 0); } else { bpp = 32; if(ga->use_hud_color) bpp = 8; bm_load_and_parse_eff(ga->filename, CF_TYPE_ANY, &ga->num_frames, &anim_fps, &ga->keyframe, 0); char *p = strrchr( ga->filename, '.' ); if ( p ) *p = 0; char frame_name[MAX_FILENAME_LEN]; if (snprintf(frame_name, MAX_FILENAME_LEN, "%s_0000", ga->filename) >= MAX_FILENAME_LEN) { // Make sure the string is null terminated frame_name[MAX_FILENAME_LEN - 1] = '\0'; } ga->bitmap_id = bm_load(frame_name); if(ga->bitmap_id < 0) { mprintf(("Cannot find first frame for eff streaming. eff Filename: %s\n", ga->filename)); return -1; } if (snprintf(frame_name, MAX_FILENAME_LEN, "%s_0001", ga->filename) >= MAX_FILENAME_LEN) { // Make sure the string is null terminated frame_name[MAX_FILENAME_LEN - 1] = '\0'; } ga->eff.next_frame = bm_load(frame_name); bm_get_info(ga->bitmap_id, &ga->width, &ga->height); ga->previous_frame = 0; } // keyframe info if (ga->type == BM_TYPE_ANI) { //we only care if there are 2 keyframes - first frame, other frame to jump to for ship/weapons //mainhall door anis hav every frame as keyframe, so we don't care //other anis only have the first frame if(ga->ani.animation->num_keys == 2) { int key1 = ga->ani.animation->keys[0].frame_num; int key2 = ga->ani.animation->keys[1].frame_num; if (key1 < 0 || key1 >= ga->num_frames) key1 = -1; if (key2 < 0 || key2 >= ga->num_frames) key2 = -1; // some retail anis have their keyframes reversed // and some have their keyframes out of bounds if (key1 >= 0 && key1 >= key2) { ga->keyframe = ga->ani.animation->keys[0].frame_num; ga->keyoffset = ga->ani.animation->keys[0].offset; } else if (key2 >= 0 && key2 >= key1) { ga->keyframe = ga->ani.animation->keys[1].frame_num; ga->keyoffset = ga->ani.animation->keys[1].offset; } } } ga->streaming = 1; if (ga->type == BM_TYPE_PNG) { ga->total_time = ga->png.anim->anim_time; } else { if (anim_fps == 0) { Error(LOCATION, "animation (%s) has invalid fps of zero, fix this!", ga->filename); } ga->total_time = ga->num_frames / (float) anim_fps; } ga->done_playing = 0; ga->anim_time = 0.0f; return 0; } int generic_bitmap_load(generic_bitmap *gb) { if ( !VALID_FNAME(gb->filename) ) return -1; gb->bitmap_id = bm_load(gb->filename); if (gb->bitmap_id < 0) return -1; return 0; } void generic_anim_unload(generic_anim *ga) { if(ga->num_frames > 0) { if(ga->streaming) { if(ga->type == BM_TYPE_ANI) { free_anim_instance(ga->ani.instance); anim_free(ga->ani.animation); } if(ga->type == BM_TYPE_EFF) { if(ga->eff.next_frame >= 0) bm_release(ga->eff.next_frame); if(ga->bitmap_id >= 0) bm_release(ga->bitmap_id); } if(ga->type == BM_TYPE_PNG) { if(ga->bitmap_id >= 0) bm_release(ga->bitmap_id); if (ga->png.anim != nullptr) { delete ga->png.anim; ga->png.anim = nullptr; } } } else { //trying to release the first frame will release ALL frames bm_release(ga->first_frame); } if(ga->buffer) { bm_release(ga->bitmap_id); } } generic_anim_init(ga, NULL); } //for timer debug, #define TIMER void generic_render_eff_stream(generic_anim *ga) { if(ga->current_frame == ga->previous_frame) return; ubyte bpp = 32; if(ga->use_hud_color) bpp = 8; #ifdef TIMER int start_time = timer_get_fixed_seconds(); #endif #ifdef TIMER mprintf(("=========================\n")); mprintf(("frame: %d\n", ga->current_frame)); #endif char frame_name[MAX_FILENAME_LEN]; if (snprintf(frame_name, MAX_FILENAME_LEN, "%s_%.4d", ga->filename, ga->current_frame) >= MAX_FILENAME_LEN) { // Make sure the string is null terminated frame_name[MAX_FILENAME_LEN - 1] = '\0'; } if(bm_reload(ga->eff.next_frame, frame_name) == ga->eff.next_frame) { bitmap* next_frame_bmp = bm_lock(ga->eff.next_frame, bpp, (bpp==8)?BMP_AABITMAP:BMP_TEX_NONCOMP, true); if(next_frame_bmp->data) gr_update_texture(ga->bitmap_id, bpp, (ubyte*)next_frame_bmp->data, ga->width, ga->height); bm_unlock(ga->eff.next_frame); bm_unload(ga->eff.next_frame, 0, true); if (ga->current_frame == ga->num_frames-1) { if (snprintf(frame_name, MAX_FILENAME_LEN, "%s_0001", ga->filename) >= MAX_FILENAME_LEN) { // Make sure the string is null terminated frame_name[MAX_FILENAME_LEN - 1] = '\0'; } bm_reload(ga->eff.next_frame, frame_name); } } #ifdef TIMER mprintf(("end: %d\n", timer_get_fixed_seconds() - start_time)); mprintf(("=========================\n")); #endif } void generic_render_ani_stream(generic_anim *ga) { int i; int bpp = ANI_BPP_CHECK; if(ga->use_hud_color) bpp = 8; #ifdef TIMER int start_time = timer_get_fixed_seconds(); #endif if(ga->current_frame == ga->previous_frame) return; #ifdef TIMER mprintf(("=========================\n")); mprintf(("frame: %d\n", ga->current_frame)); #endif anim_check_for_palette_change(ga->ani.instance); // if we're using bitmap polys BM_SELECT_TEX_FORMAT(); if(ga->direction & GENERIC_ANIM_DIRECTION_BACKWARDS) { //grab the keyframe - every frame is a keyframe for ANI if(ga->ani.animation->flags & ANF_STREAMED) { ga->ani.instance->file_offset = ga->ani.animation->file_offset + ga->ani.animation->keys[ga->current_frame].offset; } else { ga->ani.instance->data = ga->ani.animation->data + ga->ani.animation->keys[ga->current_frame].offset; } if(ga->ani.animation->flags & ANF_STREAMED) { ga->ani.instance->file_offset = unpack_frame_from_file(ga->ani.instance, ga->buffer, ga->width * ga->height, (ga->ani.instance->xlate_pal) ? ga->ani.animation->palette_translation : NULL, (bpp==8)?1:0, bpp); } else { ga->ani.instance->data = unpack_frame(ga->ani.instance, ga->ani.instance->data, ga->buffer, ga->width * ga->height, (ga->ani.instance->xlate_pal) ? ga->ani.animation->palette_translation : NULL, (bpp==8)?1:0, bpp); } } else { //looping back if((ga->current_frame == 0) || (ga->current_frame < ga->previous_frame)) { //go back to keyframe if there is one if(ga->keyframe && (ga->current_frame > 0)) { if(ga->ani.animation->flags & ANF_STREAMED) { ga->ani.instance->file_offset = ga->ani.animation->file_offset + ga->keyoffset; } else { ga->ani.instance->data = ga->ani.animation->data + ga->keyoffset; } ga->previous_frame = ga->keyframe - 1; } //go back to the start else { ga->ani.instance->file_offset = ga->ani.animation->file_offset; ga->ani.instance->data = ga->ani.animation->data; ga->previous_frame = -1; } } #ifdef TIMER mprintf(("proc: %d\n", timer_get_fixed_seconds() - start_time)); mprintf(("previous frame: %d\n", ga->previous_frame)); #endif for(i = ga->previous_frame + 1; i <= ga->current_frame; i++) { if(ga->ani.animation->flags & ANF_STREAMED) { ga->ani.instance->file_offset = unpack_frame_from_file(ga->ani.instance, ga->buffer, ga->width * ga->height, (ga->ani.instance->xlate_pal) ? ga->ani.animation->palette_translation : NULL, (bpp==8)?1:0, bpp); } else { ga->ani.instance->data = unpack_frame(ga->ani.instance, ga->ani.instance->data, ga->buffer, ga->width * ga->height, (ga->ani.instance->xlate_pal) ? ga->ani.animation->palette_translation : NULL, (bpp==8)?1:0, bpp); } } } // always go back to screen format BM_SELECT_SCREEN_FORMAT(); //we need to use this because performance is worse if we flush the gfx card buffer gr_update_texture(ga->bitmap_id, bpp, ga->buffer, ga->width, ga->height); //in case we want to check that the frame is actually changing //mprintf(("frame crc = %08X\n", cf_add_chksum_long(0, ga->buffer, ga->width * ga->height * (bpp >> 3)))); ga->ani.instance->last_bitmap = ga->bitmap_id; #ifdef TIMER mprintf(("end: %d\n", timer_get_fixed_seconds() - start_time)); mprintf(("=========================\n")); #endif } /* * @brief apng specific animation rendering * * @param [in] ga pointer to generic_anim struct */ void generic_render_png_stream(generic_anim* ga) { if(ga->current_frame == ga->previous_frame) { return; } try { if ((ga->direction & GENERIC_ANIM_DIRECTION_BACKWARDS) && (ga->previous_frame != -1)) { // mainhall door anims start backwards to ensure they stay shut // in that case (i.e. previous_frame is -1) we actually want to call // next_frame, in order to retrieve the 1st frame of the animation ga->png.anim->prev_frame(); } else { ga->png.anim->next_frame(); } } catch (const apng::ApngException& e) { nprintf(("apng", "Unable to get next/prev apng frame: %s\n", e.what())); return; } bm_lock(ga->bitmap_id, ga->png.anim->bpp, BMP_TEX_NONCOMP, true); // lock in 32 bpp for png int bpp = ga->png.anim->bpp; if (ga->use_hud_color) { bpp = 8; } gr_update_texture(ga->bitmap_id, bpp, ga->buffer, ga->width, ga->height); // this will convert to 8 bpp if required bm_unlock(ga->bitmap_id); } /* * @brief calculate current frame for fixed frame delay animation formats (ani & eff) * * @param [in] *ga animation data * @param [in] frametime how long this frame took */ void generic_anim_render_fixed_frame_delay(generic_anim* ga, float frametime) { float keytime = 0.0; if(ga->keyframe) keytime = (ga->total_time * ((float)ga->keyframe / (float)ga->num_frames)); //don't mess with the frame time if we're paused if((ga->direction & GENERIC_ANIM_DIRECTION_PAUSED) == 0) { if(ga->direction & GENERIC_ANIM_DIRECTION_BACKWARDS) { //keep going forwards if we're in a keyframe loop if(ga->keyframe && (ga->anim_time >= keytime)) { ga->anim_time += frametime; if(ga->anim_time >= ga->total_time) { ga->anim_time = keytime - 0.001f; ga->done_playing = 0; } } else { //playing backwards ga->anim_time -= frametime; if((ga->direction & GENERIC_ANIM_DIRECTION_NOLOOP) && ga->anim_time <= 0.0) { ga->anim_time = 0; //stop on first frame when playing in reverse } else { while(ga->anim_time <= 0.0) ga->anim_time += ga->total_time; //make sure we're always positive, so we can go back to the end } } } else { ga->anim_time += frametime; if(ga->anim_time >= ga->total_time) { if(ga->direction & GENERIC_ANIM_DIRECTION_NOLOOP) { ga->anim_time = ga->total_time - 0.001f; //stop on last frame when playing - if it's equal we jump to the first frame } if(!ga->done_playing){ //we've played this at least once ga->done_playing = 1; } } } } if(ga->num_frames > 0) { ga->current_frame = 0; if(ga->done_playing && ga->keyframe) { ga->anim_time = fmod(ga->anim_time - keytime, ga->total_time - keytime) + keytime; } else { ga->anim_time = fmod(ga->anim_time, ga->total_time); } ga->current_frame += fl2i(ga->anim_time * ga->num_frames / ga->total_time); //sanity check CLAMP(ga->current_frame, 0, ga->num_frames - 1); if(ga->streaming) { //handle streaming - render one frame if(ga->type == BM_TYPE_ANI) { generic_render_ani_stream(ga); } else { generic_render_eff_stream(ga); } gr_set_bitmap(ga->bitmap_id); } else { gr_set_bitmap(ga->first_frame + ga->current_frame); } } } /* * @brief calculate current frame for variable frame delay animation formats (e.g. apng) * * @param [in] *ga animation data * @param [in] frametime how long this frame took * @param [in] alpha transparency to draw frame with (0.0 - 1.0) * * @note * uses both time & frame counts to determine end state; so that if the anims playing * can't be processed fast enough, all frames will still play, rather than the end * frames being skipped */ void generic_anim_render_variable_frame_delay(generic_anim* ga, float frametime, float alpha) { Assertion(ga->type == BM_TYPE_PNG, "only valid for apngs (currently); get a coder!"); if (ga->keyframe != 0) { Warning(LOCATION, "apngs don't support keyframes"); return; } // don't change the frame time if we're paused if((ga->direction & GENERIC_ANIM_DIRECTION_PAUSED) == 0) { if(ga->direction & GENERIC_ANIM_DIRECTION_BACKWARDS) { // playing backwards ga->anim_time -= frametime; if (ga->anim_time <= 0.0 && ga->png.anim->current_frame <= 0) { if(ga->direction & GENERIC_ANIM_DIRECTION_NOLOOP) { ga->anim_time = 0; //stop on first frame when playing in reverse } else { // loop back to end ga->anim_time = ga->total_time; ga->png.previous_frame_time = ga->total_time; ga->png.anim->current_frame = ga->num_frames-1; ga->current_frame = ga->num_frames-1; } } } else { // playing forwards ga->anim_time += frametime; if(ga->anim_time >= ga->total_time && ga->png.anim->current_frame >= ga->png.anim->nframes-1) { if(ga->direction & GENERIC_ANIM_DIRECTION_NOLOOP) { ga->anim_time = ga->total_time; // stop on last frame when playing } else { // loop back to start ga->anim_time = 0.0f; ga->png.previous_frame_time = 0.0f; ga->current_frame = 0; ga->png.anim->goto_start(); } ga->done_playing = 1; } } } if (ga->num_frames > 0) { // just increment or decrement the frame by one // jumping forwards multiple frames will just exacerbate slowdowns as multiple frames // would need to be composed if (ga->direction & GENERIC_ANIM_DIRECTION_BACKWARDS) { if (ga->anim_time <= ga->png.previous_frame_time - ga->png.anim->frame.delay && ga->png.anim->current_frame > 0) { ga->png.previous_frame_time -= ga->png.anim->frame.delay; ga->current_frame--; } } else { if (ga->anim_time >= ga->png.previous_frame_time + ga->png.anim->frame.delay && ga->png.anim->current_frame < ga->png.anim->nframes-1) { ga->png.previous_frame_time += ga->png.anim->frame.delay; ga->current_frame++; } } // verbose debug; but quite useful nprintf(("apng", "apng generic render timings/frames: %04f %04f %04f %04f | %03i %03i %03i\n", frametime, ga->anim_time, ga->png.anim->frame.delay, ga->png.previous_frame_time, ga->previous_frame, ga->current_frame, ga->png.anim->current_frame)); Assertion(ga->streaming != 0, "non-streaming apngs not implemented yet"); // note: generic anims are not currently ever non-streaming in FSO // I'm not even sure that the existing ani/eff code would allow non-streaming generic anims generic_render_png_stream(ga); gr_set_bitmap(ga->bitmap_id, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, alpha); } } /* * @brief render animations * * @param [in] *ga animation data * @param [in] frametime how long this frame took * @param [in] x 2D screen x co-ordinate to render at * @param [in] y 2D screen y co-ordinate to render at * @param [in] menu select if this is rendered in menu screen, or fullscreen */ void generic_anim_render(generic_anim *ga, float frametime, int x, int y, bool menu, const generic_extras *ge) { if ((ge != nullptr) && (ga->use_hud_color == true)) { Warning(LOCATION, "Monochrome generic anims can't use extra info (yet)"); return; } float a = 1.0f; if (ge != nullptr) { a = ge->alpha; } if (ga->type == BM_TYPE_PNG) { generic_anim_render_variable_frame_delay(ga, frametime, a); } else { generic_anim_render_fixed_frame_delay(ga, frametime); } if(ga->num_frames > 0) { ga->previous_frame = ga->current_frame; if(ga->use_hud_color) { gr_aabitmap(x, y, (menu ? GR_RESIZE_MENU : GR_RESIZE_FULL)); } else { if (ge == nullptr) { gr_bitmap(x, y, (menu ? GR_RESIZE_MENU : GR_RESIZE_FULL)); } else if (ge->draw == true) { // currently only for lua streaminganim objects // and don't draw them unless requested... gr_bitmap_uv(x, y, ge->width, ge->height, ge->u0, ge->v0, ge->u1, ge->v1, GR_RESIZE_NONE); } } } }
30.083791
218
0.66449
[ "render" ]
0371fdb991ac65fdf96de74709949bb2ede27c99
1,550
hpp
C++
components/core/src/clo/CommandLineArguments.hpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
28
2021-07-18T02:21:14.000Z
2021-09-30T22:46:24.000Z
components/core/src/clo/CommandLineArguments.hpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
15
2021-10-12T03:55:07.000Z
2022-03-24T09:04:35.000Z
components/core/src/clo/CommandLineArguments.hpp
kirkrodrigues/clp
bb81eec43da218a5fa3f3a367e0a24c144bdf0c8
[ "Apache-2.0" ]
11
2021-10-06T11:35:47.000Z
2022-03-20T11:40:49.000Z
#ifndef CLO_COMMANDLINEARGUMENTS_HPP #define CLO_COMMANDLINEARGUMENTS_HPP // C++ libraries #include <vector> #include <string> // Boost libraries #include <boost/asio.hpp> // Project headers #include "../CommandLineArgumentsBase.hpp" #include "../Defs.h" namespace clo { class CommandLineArguments : public CommandLineArgumentsBase { public: // Constructors explicit CommandLineArguments (const std::string& program_name) : CommandLineArgumentsBase(program_name), m_ignore_case(false), m_search_begin_ts(cEpochTimeMin), m_search_end_ts(cEpochTimeMax) {} // Methods ParsingResult parse_arguments (int argc, const char* argv[]) override; const std::string& get_archive_path () const { return m_archive_path; } bool ignore_case () const { return m_ignore_case; } const std::string& get_search_string () const { return m_search_string; } const std::string& get_file_path () const { return m_file_path; } epochtime_t get_search_begin_ts () const { return m_search_begin_ts; } epochtime_t get_search_end_ts () const { return m_search_end_ts; } private: // Methods void print_basic_usage () const override; // Variables std::string m_archive_path; bool m_ignore_case; std::string m_search_string; std::string m_file_path; epochtime_t m_search_begin_ts, m_search_end_ts; }; } #endif // CLO_COMMANDLINEARGUMENTS_HPP
33.695652
141
0.670968
[ "vector" ]
037300d26dbe60cf7d2cbc3714f3141c3f9ced2f
1,961
hpp
C++
src/include/duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
2
2020-01-07T17:19:02.000Z
2020-01-09T22:04:04.000Z
src/include/duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
src/include/duckdb/execution/operator/aggregate/physical_hash_aggregate.hpp
RelationalAI-oss/duckdb
a4908ae17de3ac62d42633ada03077b8c3ead7a5
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // execution/operator/aggregate/physical_hash_aggregate.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/execution/aggregate_hashtable.hpp" #include "duckdb/execution/physical_operator.hpp" #include "duckdb/storage/data_table.hpp" namespace duckdb { //! PhysicalHashAggregate is an group-by and aggregate implementation that uses //! a hash table to perform the grouping class PhysicalHashAggregate : public PhysicalOperator { public: PhysicalHashAggregate(vector<TypeId> types, vector<unique_ptr<Expression>> expressions, PhysicalOperatorType type = PhysicalOperatorType::HASH_GROUP_BY); PhysicalHashAggregate(vector<TypeId> types, vector<unique_ptr<Expression>> expressions, vector<unique_ptr<Expression>> groups, PhysicalOperatorType type = PhysicalOperatorType::HASH_GROUP_BY); //! The groups vector<unique_ptr<Expression>> groups; //! The aggregates that have to be computed vector<unique_ptr<Expression>> aggregates; bool is_implicit_aggr; public: void GetChunkInternal(ClientContext &context, DataChunk &chunk, PhysicalOperatorState *state) override; unique_ptr<PhysicalOperatorState> GetOperatorState() override; }; class PhysicalHashAggregateOperatorState : public PhysicalOperatorState { public: PhysicalHashAggregateOperatorState(PhysicalHashAggregate *parent, PhysicalOperator *child); //! Materialized GROUP BY expression DataChunk group_chunk; //! Materialized aggregates DataChunk aggregate_chunk; //! The current position to scan the HT for output tuples index_t ht_scan_position; index_t tuples_scanned; //! The HT unique_ptr<SuperLargeHashTable> ht; //! The payload chunk, only used while filling the HT DataChunk payload_chunk; }; } // namespace duckdb
35.017857
104
0.702193
[ "vector" ]
03742e7ce9a5178d143b1f43fb3f424c549becc1
5,904
cpp
C++
pcutil.cpp
surebeli/node-pc-util
f9d0a8c81106ed767edf6070931f73e562288282
[ "MIT" ]
null
null
null
pcutil.cpp
surebeli/node-pc-util
f9d0a8c81106ed767edf6070931f73e562288282
[ "MIT" ]
null
null
null
pcutil.cpp
surebeli/node-pc-util
f9d0a8c81106ed767edf6070931f73e562288282
[ "MIT" ]
null
null
null
#include <napi.h> #include <windows.h> #include <ShlObj.h> #include <Shlwapi.h> #include <string.h> #pragma comment(lib, "shlwapi.lib") static bool GetFileVersion(const wchar_t *file_path, WORD *major_version, WORD *minor_version, WORD *build_number, WORD *revision_number) { DWORD handle, len; UINT buf_len; LPTSTR buf_data; VS_FIXEDFILEINFO *file_info; len = GetFileVersionInfoSizeW(file_path, &handle); if (0 == len) return false; buf_data = (LPTSTR)malloc(len); if (!buf_data) return false; if (!GetFileVersionInfoW(file_path, handle, len, buf_data)) { free(buf_data); return false; } if (VerQueryValueW(buf_data, L"\\", (LPVOID *)&file_info, (PUINT)&buf_len)) { *major_version = HIWORD(file_info->dwFileVersionMS); *minor_version = LOWORD(file_info->dwFileVersionMS); *build_number = HIWORD(file_info->dwFileVersionLS); *revision_number = LOWORD(file_info->dwFileVersionLS); free(buf_data); return true; } free(buf_data); return false; } static int GetNTDLLVersion() { static int ret = 0; if (ret == 0) { wchar_t buf_dll_name[MAX_PATH] = {0}; HRESULT hr = ::SHGetFolderPathW(NULL, CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buf_dll_name); if (SUCCEEDED(hr) && ::PathAppendW(buf_dll_name, L"ntdll.dll")) { WORD major_version, minor_version, build_number, revision_number; GetFileVersion(buf_dll_name, &major_version, &minor_version, &build_number, &revision_number); ret = major_version * 100 + minor_version; } } return ret; } //遍历windows窗口 struct CaptureTargetInfo { HWND id = 0; std::wstring title; RECT rc{0, 0, 0, 0}; }; typedef std::vector<CaptureTargetInfo> CaptureTargetInfoList; static BOOL CALLBACK WindowsEnumerationHandler(HWND hwnd, LPARAM param) { CaptureTargetInfoList *list = reinterpret_cast<CaptureTargetInfoList *>(param); // Skip windows that are invisible, minimized, have no title, or are owned, // unless they have the app window style set. HWND owner = GetWindow(hwnd, GW_OWNER); LONG exstyle = GetWindowLong(hwnd, GWL_EXSTYLE); if (IsIconic(hwnd) || !IsWindowVisible(hwnd) || (owner && !(exstyle & WS_EX_APPWINDOW)) || (exstyle & WS_EX_LAYERED)) { return TRUE; } int len = GetWindowTextLength(hwnd); if (len == 0) { return TRUE; } // Skip the Program Manager window and the Start button. const size_t kClassLength = 256; WCHAR class_name[kClassLength]; int class_name_length = GetClassNameW(hwnd, class_name, kClassLength); // Skip Program Manager window and the Start button. This is the same logic // that's used in Win32WindowPicker in libjingle. Consider filtering other // windows as well (e.g. toolbars). if (wcscmp(class_name, L"Progman") == 0 || wcscmp(class_name, L"Button") == 0) return TRUE; if (GetNTDLLVersion() >= 602 && (wcscmp(class_name, L"ApplicationFrameWindow") == 0 || wcscmp(class_name, L"Windows.UI.Core.CoreWindow") == 0)) { return TRUE; } CaptureTargetInfo window; window.id = hwnd; const size_t kTitleLength = 500; WCHAR window_title[kTitleLength]; // Truncate the title if it's longer than kTitleLength. GetWindowTextW(hwnd, window_title, kTitleLength); window.title = window_title; // Skip windows when we failed to convert the title or it is empty. if (window.title.empty()) return TRUE; list->push_back(window); return TRUE; } static bool GetCaptureWindowList(CaptureTargetInfoList *windows) { CaptureTargetInfoList result; LPARAM param = reinterpret_cast<LPARAM>(&result); if (!EnumWindows(&WindowsEnumerationHandler, param)) return false; for (auto e : result) windows->push_back(e); return true; } static std::string wstring2string(std::wstring wstr) { std::string result; //获取缓冲区大小,并申请空间,缓冲区大小事按字节计算的 int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL); char *buffer = new char[len + 1]; //宽字节编码转换成多字节编码 WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL); buffer[len] = '\0'; //删除缓冲区并返回值 result.append(buffer); delete[] buffer; return result; } Napi::Array enumerateWindows(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); Napi::Array ar = Napi::Array::New(env); CaptureTargetInfoList windows; /// for desktop windows.push_back({0, L"Desktop", RECT{0, 0, 0, 0}}); /// for monitors EnumDisplayMonitors( nullptr, nullptr, [](HMONITOR hmon, HDC, LPRECT pRC, LPARAM lparam) { auto &monitors = *reinterpret_cast<CaptureTargetInfoList *>(lparam); wchar_t buf[100] = {0}; swprintf_s(buf, L"Monitor:(%d,%d,%d,%d)", pRC->left, pRC->top, pRC->right, pRC->bottom); monitors.push_back({(HWND)hmon, buf, *pRC}); return TRUE; }, reinterpret_cast<LPARAM>(&windows)); /// for windows GetCaptureWindowList(&windows); uint32_t i = 0; for (auto w : windows) { Napi::Object obj = Napi::Object::New(env); obj.Set("id", reinterpret_cast<int32_t>(w.id)); obj.Set("title", wstring2string(w.title).c_str()); obj.Set("left", w.rc.left); obj.Set("top", w.rc.top); obj.Set("right", w.rc.right); obj.Set("bottom", w.rc.bottom); ar[i++] = obj; } return ar; } // Initializes all functions exposed to JS Napi::Object Init(Napi::Env env, Napi::Object exports) { exports.Set(Napi::String::New(env, "enumerateWindows"), Napi::Function::New(env, enumerateWindows)); return exports; } NODE_API_MODULE(pcutil, Init)
30.910995
137
0.643123
[ "object", "vector" ]
037e45225a7bd270ad2f9a18420ca48831d52abf
644
cpp
C++
sdk/keyvault/azure-security-keyvault-secrets/src/keyvault_secret_properties.cpp
RickWinter/azure-sdk-for-cpp
b4fe751310f53669a941e00aa93072f2d10a4eba
[ "MIT" ]
96
2020-03-19T07:49:39.000Z
2022-03-20T14:22:41.000Z
sdk/keyvault/azure-security-keyvault-secrets/src/keyvault_secret_properties.cpp
RickWinter/azure-sdk-for-cpp
b4fe751310f53669a941e00aa93072f2d10a4eba
[ "MIT" ]
2,572
2020-03-18T22:54:53.000Z
2022-03-31T22:09:59.000Z
sdk/keyvault/azure-security-keyvault-secrets/src/keyvault_secret_properties.cpp
RickWinter/azure-sdk-for-cpp
b4fe751310f53669a941e00aa93072f2d10a4eba
[ "MIT" ]
81
2020-03-19T09:42:00.000Z
2022-03-24T05:11:05.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @file * @brief Declares SecretProperties. * */ #include "azure/keyvault/secrets/keyvault_secret.hpp" #include "private/secret_serializers.hpp" using namespace Azure::Security::KeyVault::Secrets; SecretProperties SecretProperties::CreateFromURL(std::string const& url) { // create a url object to validate the string is valid as url Azure::Core::Url urlInstance(url); SecretProperties result; // parse the url into the result object _detail::SecretSerializer::ParseIDUrl(result, urlInstance.GetAbsoluteUrl()); return result; }
28
78
0.759317
[ "object" ]
037ee400f7cf96a2d8209e27bbf5cf128e4f67ce
31,839
cc
C++
DEM/Src/nebula2/src/gfx2/nd3d9shader_main.cc
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
2
2017-04-30T20:24:29.000Z
2019-02-12T08:36:26.000Z
DEM/Src/nebula2/src/gfx2/nd3d9shader_main.cc
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
null
null
null
DEM/Src/nebula2/src/gfx2/nd3d9shader_main.cc
moltenguy1/deusexmachina
134f4ca4087fff791ec30562cb250ccd50b69ee1
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------ // nd3d9shader_main.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "gfx2/nd3d9shader.h" #include "gfx2/nd3d9server.h" #include "gfx2/nd3d9texture.h" #include "gfx2/nd3d9shaderinclude.h" #include "gfx2/nshaderparams.h" #include <Data/DataServer.h> #include <Data/Streams/FileStream.h> nNebulaClass(nD3D9Shader, "nshader2"); //------------------------------------------------------------------------------ /** */ nD3D9Shader::nD3D9Shader() : effect(0), inBeginPass(false), hasBeenValidated(false), didNotValidate(false), curTechniqueNeedsSoftwareVertexProcessing(false) { memset(this->parameterHandles, 0, sizeof(this->parameterHandles)); } //------------------------------------------------------------------------------ /** */ nD3D9Shader::~nD3D9Shader() { if (this->IsLoaded()) { this->Unload(); } } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::UnloadResource() { n_assert(this->IsLoaded()); n_assert(this->effect); n_assert(nD3D9Server::Instance()->pD3D9Device); // if this is the currently set shader, unlink from gfx server if (nD3D9Server::Instance()->GetShader() == this) { nD3D9Server::Instance()->SetShader(0); } // release d3dx resources this->effect->Release(); this->effect = 0; // reset current shader params this->curParams.Clear(); this->SetState(Unloaded); } //------------------------------------------------------------------------------ /** Load D3DX effects file. */ bool nD3D9Shader::LoadResource() { n_assert(!this->IsLoaded()); n_assert(0 == this->effect); HRESULT hr; IDirect3DDevice9* d3d9Dev = nD3D9Server::Instance()->pD3D9Device; n_assert(d3d9Dev); // mangle path name nString filename = this->GetFilename(); nString mangledPath = DataSrv->ManglePath(filename); //load fx file... Data::CFileStream File; // open the file if (!File.Open(mangledPath, Data::SAM_READ)) { n_error("nD3D9Shader: could not load shader file '%s'!", mangledPath.Get()); return false; } // get size of file int fileSize = File.GetSize(); // allocate data for file and read it void* buffer = n_malloc(fileSize); n_assert(buffer); File.Read(buffer, fileSize); File.Close(); ID3DXBuffer* errorBuffer = 0; #if N_D3D9_DEBUG DWORD compileFlags = D3DXSHADER_DEBUG | D3DXSHADER_SKIPOPTIMIZATION | D3DXSHADER_USE_LEGACY_D3DX9_31_DLL; #else DWORD compileFlags = D3DXSHADER_USE_LEGACY_D3DX9_31_DLL; #endif // create include file handler nString shaderPath(mangledPath); nD3D9ShaderInclude includeHandler(shaderPath.ExtractDirName()); // get global effect pool from gfx server ID3DXEffectPool* effectPool = nD3D9Server::Instance()->GetEffectPool(); n_assert(effectPool); // get the highest supported shader profiles LPCSTR vsProfile = D3DXGetVertexShaderProfile(d3d9Dev); LPCSTR psProfile = D3DXGetPixelShaderProfile(d3d9Dev); if (0 == vsProfile) { n_printf("Invalid Vertex Shader profile! Fallback to vs_2_0!\n"); vsProfile = "vs_2_0"; } if (0 == psProfile) { n_printf("Invalid Pixel Shader profile! Fallback to ps_2_0!\n"); psProfile = "ps_2_0"; } n_printf("Shader profiles: %s %s\n", vsProfile, psProfile); // create macro definitions for shader compiler D3DXMACRO defines[] = { { "VS_PROFILE", vsProfile }, { "PS_PROFILE", psProfile }, { 0, 0 }, }; // create effect if (compileFlags) { hr = D3DXCreateEffectFromFile( d3d9Dev, // pDevice shaderPath.Get(), // File name defines, // pDefines &includeHandler, // pInclude compileFlags, // Flags effectPool, // pPool &(this->effect), // ppEffect &errorBuffer); // ppCompilationErrors } else { hr = D3DXCreateEffect( d3d9Dev, // pDevice buffer, // pFileData fileSize, // DataSize defines, // pDefines &includeHandler, // pInclude compileFlags, // Flags effectPool, // pPool &(this->effect), // ppEffect &errorBuffer); // ppCompilationErrors } n_free(buffer); if (FAILED(hr)) { n_error("nD3D9Shader: failed to load fx file '%s' with:\n\n%s\n", mangledPath.Get(), errorBuffer ? errorBuffer->GetBufferPointer() : "No D3DX error message."); if (errorBuffer) { errorBuffer->Release(); } return false; } n_assert(this->effect); // success this->hasBeenValidated = false; this->didNotValidate = false; this->SetState(Valid); // validate the effect this->ValidateEffect(); return true; } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetBool(nShaderState::Param p, bool val) { n_assert(this->effect && (p < nShaderState::NumParameters)); this->curParams.SetArg(p, nShaderArg(val)); HRESULT hr = this->effect->SetBool(this->parameterHandles[p], val); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetBool() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetBoolArray(nShaderState::Param p, const bool* array, int count) { n_assert(this->effect && p < nShaderState::NumParameters); // FIXME Floh: is the C++ bool datatype really identical to the Win32 BOOL datatype? HRESULT hr = this->effect->SetBoolArray(this->parameterHandles[p], (const BOOL*)array, count); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetBoolArray() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetInt(nShaderState::Param p, int val) { n_assert(this->effect && p < nShaderState::NumParameters); this->curParams.SetArg(p, nShaderArg(val)); HRESULT hr = this->effect->SetInt(this->parameterHandles[p], val); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetInt() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetIntArray(nShaderState::Param p, const int* array, int count) { n_assert(this->effect && p < nShaderState::NumParameters); HRESULT hr = this->effect->SetIntArray(this->parameterHandles[p], array, count); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetIntArray() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetFloat(nShaderState::Param p, float val) { n_assert(this->effect && p < nShaderState::NumParameters); this->curParams.SetArg(p, nShaderArg(val)); HRESULT hr = this->effect->SetFloat(this->parameterHandles[p], val); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetFloat() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetFloatArray(nShaderState::Param p, const float* array, int count) { n_assert(this->effect && p < nShaderState::NumParameters); HRESULT hr = this->effect->SetFloatArray(this->parameterHandles[p], array, count); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetFloatArray() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetVector4(nShaderState::Param p, const vector4& val) { n_assert(this->effect && p < nShaderState::NumParameters); this->curParams.SetArg(p, nShaderArg(*(nFloat4*)&val)); HRESULT hr = this->effect->SetVector(this->parameterHandles[p], (CONST D3DXVECTOR4*)&val); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetVector() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetVector3(nShaderState::Param p, const vector3& val) { n_assert(this->effect && p < nShaderState::NumParameters); static vector4 v; v.set(val.x, val.y, val.z, 1.0f); this->curParams.SetArg(p, nShaderArg(*(nFloat4*)&v)); HRESULT hr = this->effect->SetVector(this->parameterHandles[p], (CONST D3DXVECTOR4*)&v); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetVector() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetFloat4(nShaderState::Param p, const nFloat4& val) { n_assert(this->effect && p < nShaderState::NumParameters); this->curParams.SetArg(p, nShaderArg(val)); HRESULT hr = this->effect->SetVector(this->parameterHandles[p], (CONST D3DXVECTOR4*)&val); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetVector() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetFloat4Array(nShaderState::Param p, const nFloat4* array, int count) { n_assert(this->effect && p < nShaderState::NumParameters); HRESULT hr = this->effect->SetVectorArray(this->parameterHandles[p], (CONST D3DXVECTOR4*)array, count); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetVectorArray() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetVector4Array(nShaderState::Param p, const vector4* array, int count) { n_assert(this->effect && p < nShaderState::NumParameters); HRESULT hr = this->effect->SetVectorArray(this->parameterHandles[p], (CONST D3DXVECTOR4*)array, count); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetVectorArray() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetMatrix(nShaderState::Param p, const matrix44& val) { n_assert(this->effect && p < nShaderState::NumParameters); this->curParams.SetArg(p, nShaderArg(&val)); HRESULT hr = this->effect->SetMatrix(this->parameterHandles[p], (CONST D3DXMATRIX*)&val); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetMatrix() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetMatrixArray(nShaderState::Param p, const matrix44* array, int count) { n_assert(this->effect && p < nShaderState::NumParameters); HRESULT hr = this->effect->SetMatrixArray(this->parameterHandles[p], (CONST D3DXMATRIX*)array, count); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetMatrixArray() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetMatrixPointerArray(nShaderState::Param p, const matrix44** array, int count) { n_assert(this->effect && p < nShaderState::NumParameters); HRESULT hr = this->effect->SetMatrixPointerArray(this->parameterHandles[p], (CONST D3DXMATRIX**)array, count); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif n_dxtrace(hr, "SetMatrixPointerArray() on shader failed!"); } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::SetTexture(nShaderState::Param p, nTexture2* tex) { n_assert(this->effect && p < nShaderState::NumParameters); if (0 == tex) { HRESULT hr = this->effect->SetTexture(this->parameterHandles[p], 0); this->curParams.SetArg(p, nShaderArg((nTexture2*)0)); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumTextureChanges++; #endif n_dxtrace(hr, "SetTexture(0) on shader failed!"); } else { uint curTexUniqueId = 0; if (this->curParams.IsParameterValid(p)) { nTexture2* curTex = this->curParams.GetArg(p).GetTexture(); if (curTex) { curTexUniqueId = curTex->GetUniqueId(); } } if ((!this->curParams.IsParameterValid(p)) || (curTexUniqueId != tex->GetUniqueId())) { this->curParams.SetArg(p, nShaderArg(tex)); HRESULT hr = this->effect->SetTexture(this->parameterHandles[p], ((nD3D9Texture*)tex)->GetBaseTexture()); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumTextureChanges++; #endif n_dxtrace(hr, "SetTexture() on shader failed!"); } } } //------------------------------------------------------------------------------ /** Set a whole shader parameter block at once. This is slightly faster (and more convenient) then setting single parameters. */ void nD3D9Shader::SetParams(const nShaderParams& params) { int i; HRESULT hr; int numValidParams = params.GetNumValidParams(); for (i = 0; i < numValidParams; i++) { nShaderState::Param curParam = params.GetParamByIndex(i); // parameter used in shader? D3DXHANDLE handle = this->parameterHandles[curParam]; if (handle != 0) { const nShaderArg& curArg = params.GetArgByIndex(i); // early out if parameter is void if (curArg.GetType() == nShaderState::Void) { continue; } // avoid redundant state switches if ((!this->curParams.IsParameterValid(curParam)) || (!(curArg == this->curParams.GetArg(curParam)))) { this->curParams.SetArg(curParam, curArg); switch (curArg.GetType()) { case nShaderState::Bool: hr = this->effect->SetBool(handle, curArg.GetBool()); break; case nShaderState::Int: hr = this->effect->SetInt(handle, curArg.GetInt()); break; case nShaderState::Float: hr = this->effect->SetFloat(handle, curArg.GetFloat()); break; case nShaderState::Float4: hr = this->effect->SetVector(handle, (CONST D3DXVECTOR4*)&(curArg.GetFloat4())); break; case nShaderState::Matrix44: hr = this->effect->SetMatrix(handle, (CONST D3DXMATRIX*)curArg.GetMatrix44()); break; case nShaderState::Texture: hr = this->effect->SetTexture(handle, ((nD3D9Texture*)curArg.GetTexture())->GetBaseTexture()); break; } n_dxtrace(hr, "Failed to set shader parameter in nD3D9Shader::SetParams"); #ifdef __NEBULA_STATS__ nD3D9Server::Instance()->statsNumRenderStateChanges++; #endif } } } } //------------------------------------------------------------------------------ /** Update the parameter handles table which maps nShader2 parameters to D3DXEffect parameter handles. - 19-Feb-04 floh Now also recognized parameters which are not used by the shader's current technique. */ void nD3D9Shader::UpdateParameterHandles() { n_assert(this->effect); HRESULT hr; memset(this->parameterHandles, 0, sizeof(this->parameterHandles)); // for each parameter in the effect... D3DXEFFECT_DESC effectDesc = { 0 }; hr = this->effect->GetDesc(&effectDesc); n_dxtrace(hr, "GetDesc() failed in UpdateParameterHandles()"); uint curParamIndex; for (curParamIndex = 0; curParamIndex < effectDesc.Parameters; curParamIndex++) { D3DXHANDLE curParamHandle = this->effect->GetParameter(NULL, curParamIndex); n_assert(NULL != curParamHandle); // get the associated Nebula2 parameter index D3DXPARAMETER_DESC paramDesc = { 0 }; hr = this->effect->GetParameterDesc(curParamHandle, &paramDesc); n_dxtrace(hr, "GetParameterDesc() failed in UpdateParameterHandles()"); nShaderState::Param nebParam = nShaderState::StringToParam(paramDesc.Name); if (nebParam != nShaderState::InvalidParameter) { this->parameterHandles[nebParam] = curParamHandle; } } } //------------------------------------------------------------------------------ /** Return true if parameter is used by effect. */ bool nD3D9Shader::IsParameterUsed(nShaderState::Param p) { n_assert(p < nShaderState::NumParameters); return (0 != this->parameterHandles[p]); } //------------------------------------------------------------------------------ /** Find the first valid technique and set it as current. This sets the hasBeenValidated and didNotValidate members */ void nD3D9Shader::ValidateEffect() { n_assert(!this->hasBeenValidated); n_assert(this->effect); n_assert(nD3D9Server::Instance()->pD3D9Device); IDirect3DDevice9* pD3D9Device = nD3D9Server::Instance()->pD3D9Device; n_assert(pD3D9Device); HRESULT hr; // get current vertex processing state bool origSoftwareVertexProcessing = nD3D9Server::Instance()->GetSoftwareVertexProcessing(); // set to hardware vertex processing (this could fail if it's a pure software processing device) nD3D9Server::Instance()->SetSoftwareVertexProcessing(false); // set on first technique that validates correctly D3DXHANDLE technique = NULL; hr = this->effect->FindNextValidTechnique(0, &technique); // NOTE: DON'T change this to SUCCEEDED(), since FindNextValidTechnique() may // return S_FALSE, which the SUCCEEDED() macro interprets as a success code! if (D3D_OK == hr) { // technique could be validated D3DXTECHNIQUE_DESC desc; this->effect->GetTechniqueDesc(this->effect->GetTechnique(0), &desc); this->SetTechnique(desc.Name); this->hasBeenValidated = true; this->didNotValidate = false; this->UpdateParameterHandles(); } else { // shader did not validate with hardware vertex processing, try with software vertex processing nD3D9Server::Instance()->SetSoftwareVertexProcessing(true); hr = this->effect->FindNextValidTechnique(0, &technique); this->hasBeenValidated = true; // NOTE: DON'T change this to SUCCEEDED(), since FindNextValidTechnique() may // return S_FALSE, which the SUCCEEDED() macro interprets as a success code! if (D3D_OK == hr) { // success with software vertex processing n_printf("nD3D9Shader() info: shader '%s' needs software vertex processing\n", this->GetFilename()); D3DXTECHNIQUE_DESC desc; this->effect->GetTechniqueDesc(this->effect->GetTechnique(0), &desc); this->SetTechnique(desc.Name); this->didNotValidate = false; this->UpdateParameterHandles(); } else { // NOTE: looks like this has been fixed in the April 2005 SDK... // shader didn't validate at all, this may happen although the shader is valid // on older nVidia cards if the effect has a vertex shader, thus we simply force // the first technique in the file as current n_printf("nD3D9Shader() warning: shader '%s' did not validate!\n", this->GetFilename()); // NOTE: this works around the dangling "BeginPass()" in D3DX when a shader did // not validate (reproducible on older nVidia cards) this->effect->EndPass(); D3DXTECHNIQUE_DESC desc; this->effect->GetTechniqueDesc(this->effect->GetTechnique(0), &desc); this->SetTechnique(desc.Name); this->didNotValidate = false; this->UpdateParameterHandles(); } } // restore original software processing mode nD3D9Server::Instance()->SetSoftwareVertexProcessing(origSoftwareVertexProcessing); } //------------------------------------------------------------------------------ /** This switches between hardware and software processing mode, as needed by this shader. */ void nD3D9Shader::SetVertexProcessingMode() { nD3D9Server* d3d9Server = (nD3D9Server*)nGfxServer2::Instance(); d3d9Server->SetSoftwareVertexProcessing(this->curTechniqueNeedsSoftwareVertexProcessing); } //------------------------------------------------------------------------------ /** 05-Jun-04 floh saveState parameter 26-Sep-04 floh I misread the save state docs for DX9.0c, state saving flags now correct again */ int nD3D9Shader::Begin(bool saveState) { n_assert(this->effect); // check if we already have been validated, if not, find the first // valid technique and set it as current if (!this->hasBeenValidated) { this->ValidateEffect(); } if (this->didNotValidate) { return 0; } // start rendering the effect UINT numPasses; DWORD flags; if (saveState) { // save all state flags = 0; } else { // save no state flags = D3DXFX_DONOTSAVESTATE | D3DXFX_DONOTSAVESAMPLERSTATE | D3DXFX_DONOTSAVESHADERSTATE; } this->SetVertexProcessingMode(); HRESULT hr = this->effect->Begin(&numPasses, flags); n_dxtrace(hr, "nD3D9Shader: Begin() failed on effect"); return numPasses; } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::BeginPass(int pass) { n_assert(this->effect); n_assert(this->hasBeenValidated && !this->didNotValidate); this->SetVertexProcessingMode(); #if (D3D_SDK_VERSION >= 32) //summer 2004 update sdk HRESULT hr = this->effect->BeginPass(pass); n_dxtrace(hr, "nD3D9Shader:BeginPass() failed on effect"); #else HRESULT hr = this->effect->Pass(pass); n_dxtrace(hr, "nD3D9Shader: Pass() failed on effect"); #endif } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::CommitChanges() { #if (D3D_SDK_VERSION >= 32) //summer 2004 update sdk n_assert(this->effect); n_assert(this->hasBeenValidated && !this->didNotValidate); this->SetVertexProcessingMode(); HRESULT hr = this->effect->CommitChanges(); n_dxtrace(hr, "nD3D9Shader: CommitChanges() failed on effect"); #endif } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::EndPass() { #if (D3D_SDK_VERSION >= 32) //summer 2004 update sdk n_assert(this->effect); n_assert(this->hasBeenValidated && !this->didNotValidate); this->SetVertexProcessingMode(); HRESULT hr = this->effect->EndPass(); n_dxtrace(hr, "nD3D9Shader: EndPass() failed on effect"); #endif } //------------------------------------------------------------------------------ /** */ void nD3D9Shader::End() { HRESULT hr; n_assert(this->effect); n_assert(this->hasBeenValidated); if (!this->didNotValidate) { this->SetVertexProcessingMode(); hr = this->effect->End(); n_dxtrace(hr, "End() failed on effect"); } } //------------------------------------------------------------------------------ /** */ bool nD3D9Shader::HasTechnique(const char* t) const { n_assert(t); n_assert(this->effect); D3DXHANDLE h = this->effect->GetTechniqueByName(t); return (0 != h); } //------------------------------------------------------------------------------ /** */ bool nD3D9Shader::SetTechnique(const char* t) { n_assert(t); n_assert(this->effect); // get handle to technique D3DXHANDLE hTechnique = this->effect->GetTechniqueByName(t); if (0 == hTechnique) { n_error("nD3D9Shader::SetTechnique(%s): technique not found in shader file %s!\n", t, this->GetFilename()); return false; } // check if technique needs software vertex processing (this is the // case if the 3d device is a mixed vertex processing device, and // the current technique includes a vertex shader this->curTechniqueNeedsSoftwareVertexProcessing = false; if (nGfxServer2::Instance()->AreVertexShadersEmulated()) { D3DXHANDLE hPass = this->effect->GetPass(hTechnique, 0); n_assert(0 != hPass); D3DXPASS_DESC passDesc = { 0 }; HRESULT hr = this->effect->GetPassDesc(hPass, &passDesc); n_assert(SUCCEEDED(hr)); if (passDesc.pVertexShaderFunction) { this->curTechniqueNeedsSoftwareVertexProcessing = true; } } // finally, set the technique HRESULT hr = this->effect->SetTechnique(hTechnique); if (FAILED(hr)) { n_printf("nD3D9Shader::SetTechnique(%s) on shader %s failed!\n", t, this->GetFilename()); return false; } return true; } //------------------------------------------------------------------------------ /** */ const char* nD3D9Shader::GetTechnique() const { n_assert(this->effect); return this->effect->GetCurrentTechnique(); } //------------------------------------------------------------------------------ /** This converts a D3DX parameter handle to a nShaderState::Param. */ nShaderState::Param nD3D9Shader::D3DXParamToShaderStateParam(D3DXHANDLE h) { int i; for (i = 0; i < nShaderState::NumParameters; i++) { if (this->parameterHandles[i] == h) { return (nShaderState::Param)i; } } // fallthrough: invalid handle return nShaderState::InvalidParameter; } //------------------------------------------------------------------------------ /** Create or update the instance stream declaration for this shader. Stream components will be appended, unless they already exist in the declaration. Returns the number of components appended. */ int nD3D9Shader::UpdateInstanceStreamDecl(nInstanceStream::Declaration& decl) { n_assert(this->effect); int numAppended = 0; HRESULT hr; D3DXEFFECT_DESC fxDesc; hr = this->effect->GetDesc(&fxDesc); n_dxtrace(hr, "GetDesc() failed on effect"); // for each parameter... uint paramIndex; for (paramIndex = 0; paramIndex < fxDesc.Parameters; paramIndex++) { D3DXHANDLE paramHandle = this->effect->GetParameter(NULL, paramIndex); n_assert(0 != paramHandle); D3DXHANDLE annHandle = this->effect->GetAnnotationByName(paramHandle, "Instance"); if (annHandle) { BOOL b; hr = this->effect->GetBool(annHandle, &b); n_dxtrace(hr, 0); if (b) { // add parameter to stream declaration (if not already exists) nShaderState::Param param = this->D3DXParamToShaderStateParam(paramHandle); n_assert(nShaderState::InvalidParameter != param); // get parameter type D3DXPARAMETER_DESC paramDesc; hr = this->effect->GetParameterDesc(paramHandle, &paramDesc); n_dxtrace(hr, 0); nShaderState::Type type = nShaderState::Void; if (paramDesc.Type == D3DXPT_FLOAT) { switch (paramDesc.Class) { case D3DXPC_SCALAR: type = nShaderState::Float; break; case D3DXPC_VECTOR: type = nShaderState::Float4; break; case D3DXPC_MATRIX_ROWS: case D3DXPC_MATRIX_COLUMNS: type = nShaderState::Matrix44; break; } } if (nShaderState::Void == type) { n_error("nShader2: Invalid data type for instance parameter '%s' in shader '%s'!", paramDesc.Name, this->GetFilename()); return 0; } // append instance stream component (if not exists yet) int i; bool paramExists = false; for (i = 0; i < decl.Size(); i++) { if (decl[i].GetParam() == param) { paramExists = true; break; } } if (!paramExists) { nInstanceStream::Component streamComponent(type, param); decl.Append(streamComponent); numAppended++; } } } } return numAppended; } //------------------------------------------------------------------------------ /** This method is called when the d3d device is lost. */ void nD3D9Shader::OnLost() { n_assert(Lost != this->GetState()); n_assert(this->effect); this->effect->OnLostDevice(); this->SetState(Lost); // flush my current parameters (important! otherwise, seemingly redundant // state will not be set after OnRestore())! this->curParams.Clear(); } //------------------------------------------------------------------------------ /** This method is called when the d3d device has been restored. */ void nD3D9Shader::OnRestored() { n_assert(Lost == this->GetState()); n_assert(this->effect); this->effect->OnResetDevice(); this->SetState(Valid); }
32.959627
119
0.541788
[ "3d" ]
0382f6b17759f5b49fe4e30315c72d8e4e740230
32,056
cpp
C++
article-supplementary-material/lunde2020information/Chapter4/tree_class_gumbel2.cpp
sondreus/agtboost
b01396652d23619a23eba8ca714b93038238de35
[ "MIT" ]
41
2020-08-14T12:58:25.000Z
2022-03-09T23:08:13.000Z
article-supplementary-material/lunde2020information/Chapter4/tree_class_gumbel2.cpp
sondreus/agtboost
b01396652d23619a23eba8ca714b93038238de35
[ "MIT" ]
24
2020-08-18T09:17:44.000Z
2022-02-14T10:53:00.000Z
article-supplementary-material/lunde2020information/Chapter4/tree_class_gumbel2.cpp
sondreus/agtboost
b01396652d23619a23eba8ca714b93038238de35
[ "MIT" ]
6
2021-01-14T15:39:15.000Z
2022-03-21T13:51:47.000Z
#include <RcppEigen.h> // Enable C++11 via this plugin (Rcpp 0.10.3 or later) // [[Rcpp::plugins("cpp11")]] // Enables Eigen // [[Rcpp::depends(RcppEigen)]] using namespace Eigen; using namespace Rcpp; template <class T> using Tvec = Eigen::Matrix<T,Dynamic,1>; template <class T> using Tmat = Eigen::Matrix<T,Dynamic,Dynamic>; template<class T> using Tavec = Eigen::Array<T,Eigen::Dynamic,1>; // ------------ CLASSES --------------- class node { public: int split_feature; // j int obs_in_node; // |I_t| double split_value; // s_j double node_prediction; // w_t double node_tr_loss; // -G_t^2 / (2*H_t) double prob_node; // p(q(x)=t) double local_optimism; // C(t|q) = E[(g+hw_0)^2]/(n_tE[h]) double expected_max_S; // E[S_max] //double split_point_optimism; // C(\hat{s}) = C(t|q)*p(q(x)=t)*(E[S_max]-1) double CRt; // p(q(x)=t) * C(t|q) * E[S_max] double p_split_CRt; // p(split(left,right) | q(x)=t) * CRt, p(split(left,right) | q(x)=t) \approx nl/nt for left node node* left; node* right; node* createLeaf(double node_prediction, double node_tr_loss, double local_optimism, double CRt, int obs_in_node, int obs_in_parent, int obs_tot); //void setLeft(double node_prediction, double node_tr_loss, double local_optimism, double prob_node, int obs_in_node); //void setRight(double node_prediction, double node_tr_loss, double local_optimism, double prob_node, int obs_in_node); node* getLeft(); node* getRight(); void split_node(Tvec<double> &g, Tvec<double> &h, Tmat<double> &X, Tmat<double> &cir_sim, node* nptr, int n, int depth, int maxDepth); bool split_information(const Tvec<double> &g, const Tvec<double> &h, const Tmat<double> &X, const Tmat<double> &cir_sim, const int n); double expected_reduction(); void reset_node(); // if no-split, reset j, s_j, E[S] and child nodes void print_child_branches(const std::string& prefix, const node* nptr, bool isLeft); void print_child_branches_2(const std::string& prefix, const node* nptr, bool isLeft); }; class GBTREE { //private: public: node* root; int maxDepth; GBTREE(); GBTREE(int maxDepth_); node* getRoot(); void train(Tvec<double> &g, Tvec<double> &h, Tmat<double> &X, Tmat<double> &cir_sim, int maxDepth=1); double predict_obs(Tvec<double> &x); Tvec<double> predict_data(Tmat<double> &X); double getTreeScore(); double getConditionalOptimism(); double getFeatureMapOptimism(); double getTreeOptimism(); // sum of the conditional and feature map optimism /* double getTreeBias(); double getTreeBiasFull(); double getTreeBiasFull2(); double getTreeBiasFullEXM(); */ int getNumLeaves(); void print_tree(int type); }; // --------------- MAX CIR ----------------- Tmat<double> interpolate_cir(const Tvec<double>&u, const Tmat<double>& cir_sim) { // cir long-term mean is 2.0 -- but do not use this! double EPS = 1e-12; int cir_obs = cir_sim.cols(); int n_timesteps = u.size(); int n_sim = cir_sim.rows(); int j=0; int i=0; // Find original time of sim: assumption equidistant steps on u\in(0,1) double delta_time = 1.0 / ( cir_obs+1.0 ); Tvec<double> u_cirsim = Tvec<double>::LinSpaced(cir_obs, delta_time, 1.0-delta_time); // Transform to CIR time Tvec<double> tau_sim = 0.5 * log( (u_cirsim.array()*(1-EPS))/(EPS*(1.0-u_cirsim.array())) ); Tvec<double> tau = 0.5 * log( (u.array()*(1-EPS))/(EPS*(1.0-u.array())) ); // Find indices and weights of for simulations Tvec<int> lower_ind(n_timesteps), upper_ind(n_timesteps); Tvec<double> lower_weight(n_timesteps), upper_weight(n_timesteps); // Surpress to lower boundary for( ; i<n_timesteps; i++ ){ if(tau[i] <= tau_sim[0]){ lower_ind[i] = 0; lower_weight[i] = 1.0; upper_ind[i] = 0; upper_weight[i] = 0.0; }else{ break; } } // Search until in-between cir_obs timepoints are found for( ; i<n_timesteps; i++ ){ // If at limit and tau > tau_sim --> at limit --> break if( tau_sim[cir_obs-1] < tau[i] ){ break; } for( ; j<(cir_obs-1); j++){ if( tau_sim[j] < tau[i] && tau[i] <= tau_sim[j+1] ){ lower_ind[i] = j; upper_ind[i] = j+1; lower_weight[i] = 1.0 - (tau[i]-tau_sim[j]) / (tau_sim[j+1]-tau_sim[j]); upper_weight[i] = 1.0 - lower_weight[i]; break; // stop search } } } // Surpress to upper boundary for( ; i<n_timesteps; i++ ){ if(tau[i] > tau_sim[cir_obs-1]){ lower_ind[i] = cir_obs-1; upper_ind[i] = 0; lower_weight[i] = 1.0; upper_weight[i] = 0.0; } } // Populate the return matrix Tmat<double> cir_interpolated(n_sim, n_timesteps); cir_interpolated.setZero(); for(i=0; i<n_sim; i++){ for(j=0; j<n_timesteps; j++){ cir_interpolated(i,j) = cir_sim( i, lower_ind[j] ) * lower_weight[j] + cir_sim( i, upper_ind[j] ) * upper_weight[j]; } } return cir_interpolated; } Tavec<double> rmax_cir(const Tvec<double>& u, const Tmat<double>& cir_sim) { // Simulate maximum of observations on a cir process // u: split-points on 0-1 // cir_sim: matrix of pre-simulated cir-processes on transformed interval int nsplits = u.size(); int simsplits = cir_sim.cols(); int nsims = cir_sim.rows(); Tvec<double> max_cir_obs(nsims); if(nsplits < simsplits){ double EPS = 1e-12; //int nsplits = u.size(); // Transform interval: 0.5*log( (b*(1-a)) / (a*(1-b)) ) Tvec<double> tau = 0.5 * log( (u.array()*(1-EPS))/(EPS*(1.0-u.array())) ); // Interpolate cir-simulations Tmat<double> cir_obs = interpolate_cir(u, cir_sim); // Calculate row-wise maximum (max of each cir process) max_cir_obs = cir_obs.rowwise().maxCoeff(); }else{ max_cir_obs = cir_sim.rowwise().maxCoeff(); } return max_cir_obs.array(); } // Empirical cdf p_n(X\leq x) double pmax_cir(double x, Tvec<double>& obs){ // Returns proportion of values in obs less or equal to x int n = obs.size(); int sum = 0; for(int i=0; i<n; i++){ if( obs[i] <= x ){ sum++; } } return (double)sum/n; } // Composite simpson's rule -- requires n even (grid.size() odd) double simpson(Tvec<double>& fval, Tvec<double>& grid){ // fval is f(x) on evenly spaced grid int n = grid.size() - 1; double h = (grid[n] - grid[0]) / n; double s = 0; if(n==2){ s = fval[0] + 4.0*fval[1] + fval[2]; }else{ s = fval[0] + fval[n]; for(int i=1; i<=(n/2); i++) { s += 4.0*fval[2*i-1]; } for(int i=1; i<=((n/2)-1); i++) { s += 2.0*fval[2*i]; } } s = s*h/3.0; return s; } // ------------ GUMBEL --------------- // Distribution function templated template<class T> T pgumbel(double q, T location, T scale, bool lower_tail, bool log_p){ T z = (q-location)/scale; T log_px = -exp(-z); // log p(X <= x) T res; if(lower_tail && log_p){ res = log_px; }else if(lower_tail && !log_p){ res = exp(log_px); }else if(!lower_tail && log_p){ res = log(1.0 - exp(log_px)); }else{ res = 1.0 - exp(log_px); } if( std::isnan(res) ){ return 1.0; }else{ return res; } } // Gradient of estimating equation for scale double grad_scale_est_obj(double scale, Tavec<double> &x){ int n = x.size(); Tavec<double> exp_x_beta = (-1.0*x/scale).exp(); //exp_x_beta = exp_x_beta.array().exp(); double f = scale + (x*exp_x_beta).sum()/exp_x_beta.sum() - x.sum()/n; double grad = 2*f* ( 1.0 + ( (x*x*exp_x_beta).sum() * exp_x_beta.sum() - pow((x*exp_x_beta).sum(),2.0) ) / pow(scale*exp_x_beta.sum(), 2.0)); return grad; } // ML Estimate of scale double scale_estimate(Tavec<double> &x){ // Start in variance estimate -- already pretty good int n = x.size(); int mean = x.sum()/n; double var = 0.0; for(int i=0; i<n; i++){ var += (x[i]-mean)*(x[i]-mean)/n; } double scale_est = sqrt(var*6.0)/M_PI; // do some gradient iterations to obtain ML estimate int NITER = 50; // max iterations double EPS = 1e-2; // precision double step_length = 0.2; //conservative double step; for(int i=0; i<NITER; i++){ // gradient descent step = - step_length * grad_scale_est_obj(scale_est, x); scale_est += step; //Rcpp::Rcout << "iter " << i << ", step: " << std::abs(step) << ", estimate: " << scale_est << std::endl; // check precision if(std::abs(step) <= EPS){ break; } } return scale_est; } // ML Estimates Tvec<double> par_gumbel_estimates(Tavec<double> &x){ int n = x.size(); double scale_est = scale_estimate(x); double location_est = scale_est * ( log(n) - log( (-1.0*x/scale_est).exp().sum() ) ); Tvec<double> res(2); res << location_est, scale_est; return res; } // ------------------- SORTING AND SPLITTING -------------------- template <typename T> Tvec<size_t> sort_indexes(const Tvec<T> &v) { // Initialize Tvec<size_t> idx(v.size()); std::iota(idx.data(), idx.data()+idx.size(), 0); // Sort with lambda functionality std::sort(idx.data(), idx.data() + idx.size(), [&v](int i1, int i2){return v[i1] < v[i2];}); // Return return idx; } // Algorithm 2 in Appendix C bool node::split_information(const Tvec<double> &g, const Tvec<double> &h, const Tmat<double> &X, const Tmat<double> &cir_sim, const int n) { // 1. Creates left right node // 2. Calculations under null hypothesis // 3. Loop over features // 3.1 Profiles over all possible splits // 3.2 Simultaniously builds observations vectors // 3.3.1 Build gumbel (or gamma-one-hot) cdf of max cir for feature j // 3.3.2 Update joint cdf of max max cir over all features // 4. Estimate E[S] // 5. Estimate local optimism and probabilities // 6. Update split information in child nodes, importantly p_split_CRt // 7. Returns false if no split happened, else true int split_feature =0, n_indices = g.size(), n_left = 0, n_right = 0, n_features = X.cols(), n_sim = cir_sim.rows(); double split_val=0.0, observed_reduction=0.0, split_score=0.0, w_l=0.0, w_r=0.0, tr_loss_l=0.0, tr_loss_r=0.0; // Return value bool any_split = false; // Iterators int j, i; // Sorting Tvec<double> vm(n_indices); Tvec<size_t> idx(n_indices); // Local optimism double local_opt_l=0.0, local_opt_r=0.0; double Gl, Gl2, Hl, Hl2, gxhl, Gr, Gr2, Hr, Hr2, gxhr; double G=0, H=0, G2=0, H2=0, gxh=0; // Prepare for CIR Tvec<double> u_store(n_indices); //double prob_delta = 1.0/n; double prob_delta = 1.0/n_indices; int num_splits; Tavec<double> max_cir(n_sim); int grid_size = 101; // should be odd double grid_end = 1.5*cir_sim.maxCoeff(); Tvec<double> grid = Tvec<double>::LinSpaced( grid_size, 0.0, grid_end ); Tavec<double> gum_cdf_grid(grid_size); Tavec<double> gum_cdf_mmcir_grid = Tvec<double>::Ones(grid_size); Tvec<double> gum_cdf_mmcir_complement(grid_size); // 1. Create child nodes node* left = new node; node* right = new node; // 2. Calculations under null hypothesis for(i=0; i<n_indices; i++){ G += g[i]; H+=h[i]; G2 += g[i]*g[i]; H2 += h[i]*h[i]; gxh += g[i]*h[i]; } // 3. Loop over features for(j=0; j<n_features; j++){ // 3.1 Profiles over all possible splits Gl = 0.0; Hl=0.0; Gl2=0; Hl2=0, gxhl=0; vm = X.col(j); idx = sort_indexes(vm); // 3.2 Simultaniously build observations vectors u_store.setZero(); num_splits = 0; for(i=0; i<(n_indices-1); i++){ // Left split calculations Gl += g[idx[i]]; Hl+=h[idx[i]]; Gl2 += g[idx[i]]*g[idx[i]]; Hl2 += h[idx[i]]*h[idx[i]]; gxhl += g[idx[i]]*h[idx[i]]; // Right split calculations Gr = G - Gl; Hr = H - Hl; Gr2 = G2 - Gl2; Hr2 = H2 - Hl2; gxhr = gxh - gxhl; // Is x_i the same as next? if(vm[idx[i+1]] > vm[idx[i]]){ // Update observation vector u_store[num_splits] = (i+1)*prob_delta; num_splits++; // Check for new maximum reduction split_score = (Gl*Gl/Hl + Gr*Gr/Hr - G*G/H)/(2.0*n); if(observed_reduction < split_score){ any_split = true; observed_reduction = split_score; // update // Populate nodes with information split_feature = j; split_val = vm[idx[i]]; w_l = -Gl/Hl; w_r = -Gr/Hr; tr_loss_l = -Gl*Gl / (Hl*2.0*n); tr_loss_r = -Gr*Gr / (Hr*2.0*n); n_left = i+1; n_right = n_indices - (i+1); // Eq. 25 in paper local_opt_l = (Gl2 - 2.0*gxhl*(Gl/Hl) + Gl*Gl*Hl2/(Hl*Hl)) / (Hl*(i+1)); local_opt_r = (Gr2 - 2.0*gxhr*(Gr/Hr) + Gr*Gr*Hr2/(Hr*Hr)) / (Hr*(n_indices-(i+1))); } } } // 3.3 Estimate empirical cdf for feature j if(num_splits > 0){ // At least one split-point // Get probabilities Tvec<double> u = u_store.head(num_splits); //Rcpp::Rcout << "u: \n" << u << std::endl; // COMMENT REMOVE // Get observations of max cir on probability observations max_cir = rmax_cir(u, cir_sim); // Input cir_sim! if(num_splits==1){ // Exactly gamma distrbuted: shape 1, scale 2 // Estimate cdf of max cir for feature j for(int k=0; k<grid_size; k++){ gum_cdf_grid[k] = R::pgamma(grid[k], 0.5, 2.0, 1, 0); // lower tail, not log } }else{ // Asymptotically Gumbel // Estimate Gumbel parameters Tvec<double> par_gumbel = par_gumbel_estimates(max_cir); // Estimate cdf of max cir for feature j for(int k=0; k<grid_size; k++){ gum_cdf_grid[k] = pgumbel<double>(grid[k], par_gumbel[0], par_gumbel[1], true, false); } } // Update empirical cdf for max max cir gum_cdf_mmcir_grid *= gum_cdf_grid; } } if(any_split){ // 4. Estimate E[S] gum_cdf_mmcir_complement = Tvec<double>::Ones(grid_size) - gum_cdf_mmcir_grid.matrix(); this->expected_max_S = simpson( gum_cdf_mmcir_complement, grid ); // 5. Update information in parent node -- reset later if no-split this->split_feature = split_feature; this->split_value = split_val; // C(s) = C(w|q)p(q)/2 * (E[S_max]-2) this->CRt = (this->prob_node)*(this->local_optimism)*(this->expected_max_S); //Rcpp::Rcout << "E[S]: " << this->expected_max_S << "\n" << "CRt: " << this->CRt << std::endl; //this->split_point_optimism = (local_opt_l*n_left + local_opt_r*n_right)/(2*n) * (this->expected_max_S - 2.0); // 6. Update split information in child nodes left = createLeaf(w_l, tr_loss_l, local_opt_l, this->CRt, n_left, n_left+n_right, n); // Update createLeaf() right = createLeaf(w_r, tr_loss_r, local_opt_r, this->CRt, n_right, n_left+n_right, n); //Rcpp::Rcout << "p_left_CRt: " << left->p_split_CRt << "\n" << "p_right_CRt:" << right->p_split_CRt << std::endl; // 7. update childs to left right this->left = left; this->right = right; } return any_split; } // --------------- NODE FUNCTIONS ----------- node* node::createLeaf(double node_prediction, double node_tr_loss, double local_optimism, double CRt, int obs_in_node, int obs_in_parent, int obs_tot) { node* n = new node; n->node_prediction = node_prediction; n->node_tr_loss = node_tr_loss; n->local_optimism = local_optimism; n->prob_node = (double)obs_in_node / obs_tot; // prob_node; double prob_split_complement = 1.0 - (double)obs_in_node / obs_in_parent; // if left: p(right, not left), oposite for right n->p_split_CRt = prob_split_complement * CRt; n->obs_in_node = obs_in_node; n->left = NULL; n->right = NULL; return n; } node* node::getLeft() { return this->left; } node* node::getRight() { return this->right; } double node::expected_reduction() { // Calculate expected reduction on node node* left = this->left; node* right = this->right; double loss_parent = this->node_tr_loss; double loss_l = left->node_tr_loss; double loss_r = right->node_tr_loss; double R = (loss_parent - loss_l - loss_r); double CR = left->p_split_CRt + right->p_split_CRt; return R-CR; /* double cond_optimism_parent = this->local_optimism * this->prob_node; double cond_optimism_left = left->local_optimism * left->prob_node; double cond_optimism_right = right->local_optimism * right->prob_node; double s_hat_optimism = this->split_point_optimism; double res = (loss_parent - loss_l - loss_r) + cond_optimism_parent - ( cond_optimism_left + cond_optimism_right + s_hat_optimism ); //(cond_optimism_parent - S/2.0*(cond_optimism_left+cond_optimism_right)); return res; */ } void node::reset_node() { // Reset node this->expected_max_S = 0.0; this->split_feature = 0; this->split_value = 0.0; this->p_split_CRt = 0.0; this->CRt = 0.0; //this->split_point_optimism = 0.0; this->left = NULL; this->right = NULL; } void node::split_node(Tvec<double> &g, Tvec<double> &h, Tmat<double> &X, Tmat<double> &cir_sim, node* nptr, int n, int depth, int maxDepth) { // if flags stop if(g.size()<10){ return; } // Check depth if(depth>=maxDepth){ return; } //else check split // Calculate split information bool any_split = nptr->split_information(g, h, X, cir_sim, n); /* //COMMENT Rcpp::Rcout << "node information \n " << "split_feature: " << nptr->split_feature << ", split_value: " << nptr->split_value << std::endl; */ // Check if a split happened if(!any_split){ return; } /* // Comment out of working on depth<maxDepth double expected_reduction = nptr->expected_reduction(); // if expected_reduction < 0 then reset node if(expected_reduction < 0){ nptr->reset_node(); return; } */ // Tests ok: partition data and split child-nodes // Create new g, h, and X partitions int n_left = nptr->left->obs_in_node; int n_right = nptr->right->obs_in_node; Tvec<double> vm = X.col(nptr->split_feature); Tvec<size_t> idx = sort_indexes(vm); Tvec<double> gl(n_left), hl(n_left), gr(n_right), hr(n_right); Tmat<double> xl(n_left, X.cols()), xr(n_right, X.cols()); for(int i=0; i<n_left; i++){ gl[i] = g[idx[i]]; hl[i] = h[idx[i]]; xl.row(i) = X.row(idx[i]); } for(int i=n_left; i<(n_left+n_right); i++){ gr[i-n_left] = g[idx[i]]; hr[i-n_left] = h[idx[i]]; xr.row(i-n_left) = X.row(idx[i]); } // Run recursively on left split_node(gl, hl, xl, cir_sim, nptr->left, n, depth+1, maxDepth); // Run recursively on right split_node(gr, hr, xr, cir_sim, nptr->right, n, depth+1, maxDepth); } // --------------- TREE FUNCTIONS ------- GBTREE::GBTREE(){ this->root = NULL; } GBTREE::GBTREE(int maxDepth_){ this->root = NULL; this->maxDepth = maxDepth_; } node* GBTREE::getRoot(){ return this->root; } void GBTREE::train(Tvec<double> &g, Tvec<double> &h, Tmat<double> &X, Tmat<double> &cir_sim, int maxDepth) { // Check if root exists // Else create root int n = g.size(); if(root == NULL){ // Calculate information double G=0, H=0, G2=0, H2=0, gxh=0; for(int i=0; i<n; i++){ G += g[i]; H+=h[i]; G2 += g[i]*g[i]; H2 += h[i]*h[i]; gxh += g[i]*h[i]; } double local_optimism = (G2 - 2.0*gxh*(G/H) + G*G*H2/(H*H)) / (H*n); root = root->createLeaf(-G/H, -G*G/(2*H*n), local_optimism, local_optimism, n, n, n); } root->split_node(g, h, X, cir_sim, root, n, 0, maxDepth); } double GBTREE::predict_obs(Tvec<double> &x){ node* current = this->root; if(current == NULL){ return 0; } while(current != NULL){ if(current->left == NULL && current ->right == NULL){ return current->node_prediction; } else{ /* // COMMENT Rcpp::Rcout << "x value: " << x[current->split_feature] << ", split_feature: " << current->split_feature << ", split_value: " << current->split_value << std::endl; */ if(x[current->split_feature] <= current->split_value){ current = current->left; }else{ current = current->right; } } } return 0; } Tvec<double> GBTREE::predict_data(Tmat<double> &X){ int n = X.rows(); Tvec<double> res(n), x(n); for(int i=0; i<n; i++){ x = X.row(i); res[i] = predict_obs(x); } return res; } double GBTREE::getTreeScore(){ // Recurse tree and sum leaf scores double treeScore = 0; node* current = this->root; node* pre; if(current == NULL){ return 0; } while (current != NULL) { if (current->left == NULL) { //std::cout << current->node_prediction << std::endl; treeScore += current->node_tr_loss; current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */ else { pre->right = NULL; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return treeScore; } double GBTREE::getConditionalOptimism(){ // Recurse tree and sum conditional optimism in leaves double conditional_opt_leaves = 0; node* current = this->root; node* pre; if(current == NULL){ return 0; } while (current != NULL) { if (current->left == NULL) { //std::cout << current->node_prediction << std::endl; conditional_opt_leaves += current->local_optimism * current->prob_node; current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */ else { pre->right = NULL; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return conditional_opt_leaves; } double GBTREE::getTreeOptimism(){ // Recurse tree and sum p_split_CRt in leaf-nodes double tree_optimism = 0.0; node* current = this->root; node* pre; if(current == NULL){ return 0; } while (current != NULL) { if (current->left == NULL) { //std::cout << current->node_prediction << std::endl; //conditional_opt_leaves += current->local_optimism * current->prob_node; current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */ else { pre->right = NULL; tree_optimism += current->CRt; // current->split_point_optimism; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return tree_optimism; } int GBTREE::getNumLeaves(){ int numLeaves = 0; node* current = this->root; node* pre; if(current == NULL){ return 0; } while (current != NULL) { if (current->left == NULL) { //std::cout << current->node_prediction << std::endl; numLeaves += 1; current = current->right; } else { /* Find the inorder predecessor of current */ pre = current->left; while (pre->right != NULL && pre->right != current) pre = pre->right; /* Make current as right child of its inorder predecessor */ if (pre->right == NULL) { pre->right = current; current = current->left; } /* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */ else { pre->right = NULL; current = current->right; } /* End of if condition pre->right == NULL */ } /* End of if condition current->left == NULL*/ } /* End of while */ return numLeaves; } void node::print_child_branches(const std::string& prefix, const node* nptr, bool isLeft){ if(nptr != NULL) { std::cout << prefix; std::cout << (isLeft ? "├──" : "└──" ); // print the value of the node // if leaf, print prediction, else print split info. if(nptr->left == NULL){ // is leaf: node prediction std::cout << nptr->node_prediction << std::endl; }else{ // not leaf: split information std::cout << "(" << nptr->split_feature << ", " << nptr->split_value << ")" << std::endl; } // enter the next tree level - left and right branch print_child_branches( prefix + (isLeft ? "| " : " "), nptr->left, true); print_child_branches( prefix + (isLeft ? "| " : " "), nptr->right, false); } } void node::print_child_branches_2(const std::string& prefix, const node* nptr, bool isLeft){ // tree optimism if(nptr != NULL) { std::cout << prefix; std::cout << (isLeft ? "├──" : "└──" ); // print the value of the node // if leaf, print prediction, else print split info. if(nptr->left == NULL){ // is leaf: node prediction std::cout << "[" << nptr->local_optimism << ", " << nptr->prob_node << "]" << std::endl; }else{ // not leaf: split information std::cout << "(" << nptr->expected_max_S << ", " << nptr->CRt << ")" << std::endl; } // enter the next tree level - left and right branch print_child_branches_2( prefix + (isLeft ? "| " : " "), nptr->left, true); print_child_branches_2( prefix + (isLeft ? "| " : " "), nptr->right, false); } } void GBTREE::print_tree(int type){ // Horizontal printing of the tree // Prints ( col_num , split_val ) for nodes not leaves // Prints node_prediction for all leaves if(type==1){ // Optimism root->print_child_branches_2("", root, false); }else{ // Decisions root->print_child_branches("", root, false); } } // ---------------- EXPOSING CLASSES TO R ---------- RCPP_EXPOSED_CLASS(GBTREE) RCPP_MODULE(gbtree_module){ using namespace Rcpp; class_<GBTREE>("GBTREE") .constructor() .constructor<int>() .field("maxDepth", &GBTREE::maxDepth) .method("getRoot", &GBTREE::getRoot) .method("train", &GBTREE::train) .method("predict_obs", &GBTREE::predict_obs) .method("predict_data", &GBTREE::predict_data) .method("getTreeScore", &GBTREE::getTreeScore) .method("getConditionalOptimism", &GBTREE::getConditionalOptimism) .method("getTreeOptimism", &GBTREE::getTreeOptimism) .method("getNumLeaves", &GBTREE::getNumLeaves) .method("print_tree", &GBTREE::print_tree) ; // class_<node>("node") // .constructor() // .field("split_feature", &node::split_feature) // .field("split_value", &node::split_value) // .field("node_prediction", &node::node_prediction) // .method("getLeft", &node::getLeft) // .method("getRight", &node::getRight) // ; }
30.442545
127
0.524145
[ "shape", "vector", "transform" ]
0383f6f1ba4a07199f1222626b63bcf624524ec1
19,044
cpp
C++
clintstmtoccurrence.cpp
ftynse/clint
d9be5631156d4b93dd8a6897503141a3bc652fac
[ "BSD-3-Clause" ]
18
2016-05-10T15:54:05.000Z
2022-03-29T22:27:30.000Z
clintstmtoccurrence.cpp
ftynse/clint
d9be5631156d4b93dd8a6897503141a3bc652fac
[ "BSD-3-Clause" ]
4
2017-04-12T12:52:14.000Z
2019-05-10T10:50:48.000Z
clintstmtoccurrence.cpp
ftynse/clint
d9be5631156d4b93dd8a6897503141a3bc652fac
[ "BSD-3-Clause" ]
3
2019-05-10T09:30:20.000Z
2020-12-20T08:08:20.000Z
#include "oslutils.h" #include "clintstmt.h" #include "clintstmtoccurrence.h" #include <functional> ClintStmtOccurrence::ClintStmtOccurrence(osl_statement_p stmt, const std::vector<int> &betaVector, ClintStmt *parent) : QObject(parent), m_oslStatement(stmt), m_statement(parent) { resetOccurrence(stmt, betaVector); } /// The split occurrence will hot have osl_statement set up by default. Use resetOccurrence to initialize it. ClintStmtOccurrence *ClintStmtOccurrence::split(const std::vector<int> &betaVector) { ClintStmtOccurrence *occurrence = new ClintStmtOccurrence(nullptr, betaVector, m_statement); occurrence->m_tilingDimensions = m_tilingDimensions; occurrence->m_tileSizes = m_tileSizes; return occurrence; } void ClintStmtOccurrence::resetOccurrence(osl_statement_p stmt, const std::vector<int> &betaVector) { bool differentBeta = (m_betaVector == betaVector); bool differentPoints = false; m_betaVector = betaVector; m_oslStatement = stmt; if (stmt == nullptr) { if (m_oslScattering != nullptr) emit pointsChanged(); if (differentBeta) emit betaChanged(); return; } osl_relation_p oslScattering = nullptr; oslListForeach(stmt->scattering, [&oslScattering,&betaVector](osl_relation_p scattering) { if (betaExtract(scattering) == betaVector) { CLINT_ASSERT(oslScattering == nullptr, "Duplicate beta-vector found"); oslScattering = scattering; } }); CLINT_ASSERT(oslScattering != nullptr, "Trying to create an occurrence for the inexistent beta-vector"); differentPoints = !osl_relation_equal(oslScattering, m_oslScattering); m_oslScattering = oslScattering; if (differentPoints) { emit pointsChanged(); } if (differentBeta) { emit betaChanged(); } } void ClintStmtOccurrence::resetBetaVector(const std::vector<int> &betaVector) { bool differentBeta = (m_betaVector == betaVector); m_betaVector = betaVector; if (differentBeta) emit betaChanged(); } bool operator < (const ClintStmtOccurrence &lhs, const ClintStmtOccurrence &rhs) { return lhs.m_betaVector < rhs.m_betaVector; } bool operator ==(const ClintStmtOccurrence &lhs, const ClintStmtOccurrence &rhs) { return lhs.m_betaVector == rhs.m_betaVector; } int ClintStmtOccurrence::ignoreTilingDim(int dim) const { // Ignore projections on tiled dimensions. for (int tilingDim : m_tilingDimensions) { if (tilingDim > dim) { return dim; } dim++; } return dim; } std::vector<std::vector<int>> ClintStmtOccurrence::projectOn(int horizontalDimIdx, int verticalDimIdx) const { if (m_oslScattering == nullptr) { std::cerr << "don't project" << std::endl; } CLINT_ASSERT(m_oslStatement != nullptr && m_oslScattering != nullptr, "Trying to project a non-initialized statement"); // Transform iterator (alpha only) indices to enumerator (beta-alpha-beta) indices // betaDims are found properly iff the dimensionalityChecker assertion holds. int horizontalScatDimIdx = 1 + 2 * horizontalDimIdx; int verticalScatDimIdx = 1 + 2 * verticalDimIdx; int horizontalOrigDimIdx = m_oslScattering->nb_output_dims + horizontalDimIdx; int verticalOrigDimIdx = m_oslScattering->nb_output_dims + verticalDimIdx; horizontalScatDimIdx = ignoreTilingDim(horizontalScatDimIdx); verticalScatDimIdx = ignoreTilingDim(verticalScatDimIdx); // horizontalOrigDimIdx = ignoreTilingDim(horizontalOrigDimIdx); // verticalOrigDimIdx = ignoreTilingDim(verticalOrigDimIdx); // Checking if all the relations for the same beta have the same structure. // AZ: Not sure if it is theoretically possible: statements with the same beta-vector // should normally be in the same part of the domain union and therefore have same // number of scattering variables. If the following assertion ever fails, check the // theoretical statement and if it does not hold, perform enumeration separately for // each union part. // AZ: this holds for SCoPs generated by Clan. // TODO: piggyback on oslUtils and Enumerator to pass around the mapping from original iterators // to the scattering (indices in applied matrix) since different parts of the domain and scattering // relation unions may have different number of input/output dimensions for the codes // originating from outside Clan/Clay toolset. // AZ: is this even possible without extra information? Two problematic cases, // 1. a1 = i + j, a2 = i - j; no clear mapping between a and i,j // 2. stripmine a1 >/< f(i), a2 = i; two a correspond to i in the same time. auto dimensionalityCheckerFunction = [](osl_relation_p rel, int output_dims, int input_dims, int parameters) { CLINT_ASSERT(rel->nb_output_dims == output_dims, "Dimensionality mismatch, proper polyhedron construction impossible"); CLINT_ASSERT(rel->nb_input_dims == input_dims, "Dimensionality mismatch, proper polyhedron construction impossible"); CLINT_ASSERT(rel->nb_parameters == parameters, "Dimensionality mismatch, proper polyhedron construction impossible"); }; oslListForeach(m_oslStatement->domain, dimensionalityCheckerFunction, m_oslStatement->domain->nb_output_dims, m_oslStatement->domain->nb_input_dims, m_oslStatement->domain->nb_parameters); CLINT_ASSERT(m_oslStatement->domain->nb_output_dims == m_oslScattering->nb_input_dims, "Scattering is not compatible with the domain"); bool horizontalOrigDimValid = horizontalOrigDimIdx < m_oslScattering->nb_output_dims + m_oslStatement->domain->nb_output_dims; bool verticalOrigDimValid = verticalOrigDimIdx < m_oslScattering->nb_output_dims + m_oslStatement->domain->nb_output_dims; // Get original and scattered iterator values depending on the axis displayed. bool projectHorizontal = (horizontalDimIdx != -2) && (dimensionality() > horizontalDimIdx); // FIXME: -2 is in VizProperties::NO_DIMENSION, but should be in a different class since it has nothing to do with viz bool projectVertical = (verticalDimIdx != -2) && (dimensionality() > verticalDimIdx); CLINT_ASSERT(!(projectHorizontal ^ (horizontalScatDimIdx >= 0 && horizontalScatDimIdx < m_oslScattering->nb_output_dims)), "Trying to project to the horizontal dimension that is not present in scattering"); CLINT_ASSERT(!(projectVertical ^ (verticalScatDimIdx >= 0 && verticalScatDimIdx < m_oslScattering->nb_output_dims)), "Trying to project to the vertical dimension that is not present in scattering"); std::vector<osl_relation_p> scatterings { m_oslScattering }; osl_relation_p applied = oslApplyScattering(oslListToVector(m_oslStatement->domain), scatterings); osl_relation_p ready = oslRelationsWithContext(applied, m_statement->scop()->fixedContext()); std::vector<int> allDimensions; allDimensions.reserve(m_oslScattering->nb_output_dims + 2); if (projectHorizontal && horizontalOrigDimValid) { allDimensions.push_back(horizontalScatDimIdx); } if (projectVertical && verticalOrigDimValid) { allDimensions.push_back(verticalScatDimIdx); } for (int i = 0, e = m_oslScattering->nb_input_dims; i < e; ++i) { allDimensions.push_back(m_oslScattering->nb_output_dims + i); } std::vector<std::vector<int>> points = program()->enumerator()->enumerate(ready, allDimensions); computeMinMax(points, horizontalDimIdx, verticalDimIdx); return std::move(points); } std::pair<std::vector<int>, std::pair<int, int>> ClintStmtOccurrence::parseProjectedPoint(std::vector<int> point, int horizontalDimIdx, int verticalDimIdx) const { std::pair<int, int> scatteredCoordinates {INT_MAX, INT_MAX}; // FIXME: INT_MAX is VizPoint::NO_COORD if (visibleDimensionality() >= horizontalDimIdx && horizontalDimIdx != -2) { CLINT_ASSERT(point.size() > 0, "Not enough dimensions"); scatteredCoordinates.first = point[0]; point.erase(std::begin(point)); } if (visibleDimensionality() >= verticalDimIdx && verticalDimIdx != -2) { CLINT_ASSERT(point.size() > 0, "Not enough dimensions"); scatteredCoordinates.second = point[0]; point.erase(std::begin(point)); } return std::make_pair(point, scatteredCoordinates); } void ClintStmtOccurrence::computeMinMax(const std::vector<std::vector<int>> &points, int horizontalDimIdx, int verticalDimIdx) const { // Initialize with extreme values for min and max unless already computed for previous polyhedron int horizontalMin, horizontalMax, verticalMin = 0, verticalMax = 0; if (horizontalDimIdx == -2) { // FIXME: -2 is in VizProperties::NO_DIMENSION return; } if (points.size() == 0) { m_cachedDimMins[horizontalDimIdx] = 0; m_cachedDimMaxs[horizontalDimIdx] = 0; m_cachedDimMins[verticalDimIdx] = 0; m_cachedDimMaxs[verticalDimIdx] = 0; return; } std::pair<int, int> scatteredCoordinates; std::tie(std::ignore, scatteredCoordinates) = parseProjectedPoint(points.front(), horizontalDimIdx, verticalDimIdx); bool computeHorizontal = scatteredCoordinates.first != INT_MAX && horizontalDimIdx != -2; // FIXME: INT_MAX is VizPoint::NO_COORD bool computeVertical = scatteredCoordinates.second != INT_MAX && verticalDimIdx != -2; if (computeHorizontal) { horizontalMin = INT_MAX; horizontalMax = INT_MIN; } if (computeVertical) { verticalMin = INT_MAX; verticalMax = INT_MIN; } // Compute min and max values for projected iterators of the current coordinate system. for (const std::vector<int> &point : points) { if (computeHorizontal) { horizontalMin = std::min(horizontalMin, point[0]); horizontalMax = std::max(horizontalMax, point[0]); } if (computeVertical) { verticalMin = std::min(verticalMin, point[1]); verticalMax = std::max(verticalMax, point[1]); } } CLINT_ASSERT(horizontalMin != INT_MIN, "Could not compute horizontal minimum"); CLINT_ASSERT(horizontalMax != INT_MAX, "Could not compute horizontal maximum"); CLINT_ASSERT(verticalMin != INT_MIN, "Could not compute vertical minimum"); CLINT_ASSERT(verticalMax != INT_MAX, "Could not compute vertical maximum"); if (computeHorizontal) { m_cachedDimMins[horizontalDimIdx] = horizontalMin; m_cachedDimMaxs[horizontalDimIdx] = horizontalMax; } if (computeVertical) { m_cachedDimMins[verticalDimIdx] = verticalMin; m_cachedDimMaxs[verticalDimIdx] = verticalMax; } } std::vector<int> ClintStmtOccurrence::makeBoundlikeForm(Bound bound, int dimIdx, int constValue, int constantBoundaryPart, const std::vector<int> &parameters, const std::vector<int> &parameterValues) { bool isConstantForm = std::all_of(std::begin(parameters), std::end(parameters), std::bind(std::equal_to<int>(), std::placeholders::_1, 0)); // Substitute parameters with current values. // Constant will differ depending on the target form: // for the constant form, all parameters are replaced with respective values; // for the parametric form, adjust with the current constant part of the boundary. int parameterSubstValue = 0; for (size_t i = 0; i < parameters.size(); i++) { parameterSubstValue += parameters[i] * parameterValues[i]; } parameterSubstValue += constantBoundaryPart; if (bound == Bound::LOWER && isConstantForm) { constValue = constValue - 1; } else if (bound == Bound::UPPER && isConstantForm) { constValue = -constValue - 1; } else if (bound == Bound::LOWER && !isConstantForm) { constValue = -constantBoundaryPart + (constValue + parameterSubstValue - 1); } else if (bound == Bound::UPPER && !isConstantForm) { constValue = -constantBoundaryPart + (parameterSubstValue - constValue - 1); } else { CLINT_UNREACHABLE; } std::vector<int> form; form.push_back(1); // Inequality for (int i = 0; i < m_oslStatement->domain->nb_output_dims; i++) { form.push_back(i == dimIdx ? (bound == Bound::LOWER ? -1 : 1) : 0); } for (int p : parameters) { form.push_back(-p); } form.push_back(constValue); return std::move(form); } static bool isVariableBoundary(int row, osl_relation_p scattering, int dimIdx) { bool variable = false; for (int i = 0; i < scattering->nb_input_dims + scattering->nb_output_dims + scattering->nb_local_dims; i++) { if (i + 1 == dimIdx) continue; if (!osl_int_zero(scattering->precision, scattering->m[row][1 + i])) variable = true; } return variable; } static bool isParametricBoundary(int row, osl_relation_p scattering) { int firstParameterDim = scattering->nb_input_dims + scattering->nb_output_dims + scattering->nb_local_dims + 1; for (int i = 0; i < scattering->nb_parameters; i++) { if (!osl_int_zero(scattering->precision, scattering->m[row][firstParameterDim + i])) return true; } return false; } std::vector<int> ClintStmtOccurrence::findBoundlikeForm(Bound bound, int dimIdx, int constValue) { std::vector<int> zeroParameters(m_oslStatement->domain->nb_parameters, 0); std::vector<int> parameterValues = scop()->parameterValues(); int oslDimIdx = 1 + dimIdx * 2 + 1; osl_relation_p scheduledDomain = ISLEnumerator::scheduledDomain(m_oslStatement->domain, m_oslScattering); int lowerRow = oslRelationDimUpperBound(scheduledDomain, oslDimIdx); int upperRow = oslRelationDimLowerBound(scheduledDomain, oslDimIdx); // Check if the request boundary exists and is unique. // If failed, try the opposite boundary. If the opposite does not // exist or is not unique, use constant form. if (lowerRow < 0 && upperRow < 0) { return makeBoundlikeForm(bound, dimIdx, constValue, 0, zeroParameters, parameterValues); } else if (lowerRow < 0 && bound == Bound::LOWER) { bound = Bound::UPPER; } else if (upperRow < 0 && bound == Bound::UPPER) { bound = Bound::LOWER; } // Check if the current boundary (either request or opposite) is // variable. If it is, try the opposite unless the opposite does // not exist. If both are variable or one is variable and another // does not exit, use constant form. bool upperVariable = upperRow >= 0 ? isVariableBoundary(upperRow, scheduledDomain, oslDimIdx) : true; bool lowerVariable = lowerRow >= 0 ? isVariableBoundary(lowerRow, scheduledDomain, oslDimIdx) : true; if (upperVariable && lowerVariable) { return makeBoundlikeForm(bound, dimIdx, constValue, 0, zeroParameters, parameterValues); } if (upperVariable && lowerRow >= 0) { bound = Bound::LOWER; } else if (lowerVariable && upperRow >= 0) { bound = Bound::UPPER; } int row = bound == Bound::UPPER ? upperRow : lowerRow; int firstParameterIdx = 1 + scheduledDomain->nb_input_dims + scheduledDomain->nb_output_dims + scheduledDomain->nb_local_dims; std::vector<int> parameters; parameters.reserve(scheduledDomain->nb_parameters); for (int i = 0; i < scheduledDomain->nb_parameters; i++) { int p = osl_int_get_si(scheduledDomain->precision, scheduledDomain->m[row][firstParameterIdx + i]); parameters.push_back(p); } // Make parametric form is the boundary itself is parametric. // Make constant form otherwise. if (isParametricBoundary(row, scheduledDomain)) { int boundaryConstantPart = osl_int_get_si(scheduledDomain->precision, scheduledDomain->m[row][scheduledDomain->nb_columns - 1]); return makeBoundlikeForm(bound, dimIdx, constValue, boundaryConstantPart, parameters, parameterValues); } else { return makeBoundlikeForm(bound, dimIdx, constValue, 0, zeroParameters, parameterValues); } } int ClintStmtOccurrence::minimumValue(int dimIdx) const { if (dimIdx >= dimensionality() || dimIdx < 0) return 0; if (m_cachedDimMins.count(dimIdx) == 0) { projectOn(dimIdx, -2); // FIXME: -2 is VizProperties::NoDimension } CLINT_ASSERT(m_cachedDimMins.count(dimIdx) == 1, "min cache failure"); return m_cachedDimMins[dimIdx]; } int ClintStmtOccurrence::maximumValue(int dimIdx) const { if (dimIdx >= dimensionality() || dimIdx < 0) return 0; if (m_cachedDimMaxs.count(dimIdx) == 0) { projectOn(dimIdx, -2); // FIXME: -2 is VizProperties::NoDimension } CLINT_ASSERT(m_cachedDimMaxs.count(dimIdx) == 1, "max cache failure"); return m_cachedDimMaxs[dimIdx]; } std::vector<int> ClintStmtOccurrence::untiledBetaVector() const { std::vector<int> beta(m_betaVector); // m_tilingDimensions is an ordered set, start from the end to remove higher // indices from beta-vector first. Thus lower indices will remain the same. for (auto it = m_tilingDimensions.rbegin(), eit = m_tilingDimensions.rend(); it != eit; it++) { if ((*it) % 2 == 0) { int index = (*it) / 2; beta.erase(beta.begin() + index); } } return std::move(beta); } void ClintStmtOccurrence::tile(int dimensionIdx, unsigned tileSize) { CLINT_ASSERT(tileSize != 0, "Cannot tile by 0 elements"); // Ignore previously tiled dimensions. dimensionIdx = depth(dimensionIdx) - 1; std::set<int> tilingDimensions; std::unordered_map<int, unsigned> tileSizes; for (int dim : m_tilingDimensions) { if (dim >= 2 * dimensionIdx + 1) { tilingDimensions.insert(dim + 2); if (m_tileSizes.count(dim)) tileSizes[dim + 2] = m_tileSizes[dim]; } else { tilingDimensions.insert(dim); if (m_tileSizes.count(dim)) tileSizes[dim] = m_tileSizes[dim]; } } tilingDimensions.insert(2 * dimensionIdx + 2); tilingDimensions.insert(2 * dimensionIdx + 1); tileSizes[2 * dimensionIdx + 1] = tileSize; m_tilingDimensions = tilingDimensions; m_tileSizes = tileSizes; } void ClintStmtOccurrence::untile(int dimensionIdx) { dimensionIdx = depth(dimensionIdx) - 2; std::set<int> tilingDimensions; std::unordered_map<int, unsigned> tileSizes; m_tilingDimensions.erase(2 * dimensionIdx + 2); m_tilingDimensions.erase(2 * dimensionIdx + 1); m_tileSizes.erase(2 * dimensionIdx + 1); for (int dim : m_tilingDimensions) { if (dim > 2 * dimensionIdx + 2) { tilingDimensions.insert(dim - 2); if (m_tileSizes.count(dim)) tileSizes[dim - 2] = m_tileSizes[dim]; } else { tilingDimensions.insert(dim); if (m_tileSizes.count(dim)) tileSizes[dim] = m_tileSizes[dim]; } } m_tilingDimensions = tilingDimensions; m_tileSizes = tileSizes; }
42.795506
212
0.692344
[ "vector", "transform" ]
038a73364288af44e228a3ac602f03d05bb47745
1,579
hpp
C++
deps/boost/include/boost/atomic/detail/wait_caps_freebsd_umtx.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
80
2021-09-07T12:44:32.000Z
2022-03-29T01:22:19.000Z
deps/boost/include/boost/atomic/detail/wait_caps_freebsd_umtx.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
2
2021-12-23T02:49:42.000Z
2022-02-15T05:28:24.000Z
deps/boost/include/boost/atomic/detail/wait_caps_freebsd_umtx.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
25
2021-09-14T06:24:25.000Z
2022-03-20T06:55:07.000Z
/* * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * Copyright (c) 2020 Andrey Semashev */ /*! * \file atomic/detail/wait_caps_freebsd_umtx.hpp * * This header defines waiting/notifying operations capabilities macros. */ #ifndef BOOST_ATOMIC_DETAIL_WAIT_CAPS_FREEBSD_UMTX_HPP_INCLUDED_ #define BOOST_ATOMIC_DETAIL_WAIT_CAPS_FREEBSD_UMTX_HPP_INCLUDED_ #include <sys/umtx.h> #include <boost/atomic/detail/config.hpp> #include <boost/atomic/detail/int_sizes.hpp> #include <boost/atomic/detail/capabilities.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif // FreeBSD _umtx_op uses physical address to the atomic object as a key, which means it should support address-free operations. // https://www.freebsd.org/cgi/man.cgi?query=_umtx_op&apropos=0&sektion=2&manpath=FreeBSD+11-current&format=html #if (defined(UMTX_OP_WAIT_UINT) && BOOST_ATOMIC_DETAIL_SIZEOF_INT == 4) ||\ (defined(UMTX_OP_WAIT) && BOOST_ATOMIC_DETAIL_SIZEOF_LONG == 4) #define BOOST_ATOMIC_HAS_NATIVE_INT32_WAIT_NOTIFY BOOST_ATOMIC_INT32_LOCK_FREE #define BOOST_ATOMIC_HAS_NATIVE_INT32_IPC_WAIT_NOTIFY BOOST_ATOMIC_INT32_LOCK_FREE #endif #if defined(UMTX_OP_WAIT) && BOOST_ATOMIC_DETAIL_SIZEOF_LONG == 8 #define BOOST_ATOMIC_HAS_NATIVE_INT64_WAIT_NOTIFY BOOST_ATOMIC_INT64_LOCK_FREE #define BOOST_ATOMIC_HAS_NATIVE_INT64_IPC_WAIT_NOTIFY BOOST_ATOMIC_INT64_LOCK_FREE #endif #endif // BOOST_ATOMIC_DETAIL_WAIT_CAPS_FREEBSD_UMTX_HPP_INCLUDED_
38.512195
128
0.80304
[ "object" ]
038e92f18f20f972fa41e6aa80b6ab8be1d5f8b2
2,391
cc
C++
Codeforces/331 Division 2/Problem C/C.cc
VastoLorde95/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
170
2017-07-25T14:47:29.000Z
2022-01-26T19:16:31.000Z
Codeforces/331 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
null
null
null
Codeforces/331 Division 2/Problem C/C.cc
navodit15/Competitive-Programming
6c990656178fb0cd33354cbe5508164207012f24
[ "MIT" ]
55
2017-07-28T06:17:33.000Z
2021-10-31T03:06:22.000Z
#include <cstdio> #include <iostream> #include <cmath> #include <algorithm> #include <cstring> #include <map> #include <set> #include <vector> #include <utility> #include <queue> #include <stack> #include <cassert> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define LET(x, a) __typeof(a) x(a) #define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cerr.tie(NULL); #define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout); #define meta __FUNCTION__<<" "<<__LINE__<<" " #define tr(x) cerr<<meta<<#x<<" "<<x<<endl; #define tr2(x,y) cerr<<meta<<#x<<" "<<x<<" "<<#y<<" "<<y<<endl; #define tr3(x,y,z) cerr<<meta<<#x<<" "<<x<<" "<<#y<<" "<<y<<" "<<#z<<" "<<z<<endl; #define tr4(w,x,y,z) cerr<<meta<<#w<<" "<<w<<" "<<#x<<" " <<x<<" "<<#y<<" "<<y<<" "<<#z<<" "<<z<<endl; #define tr5(v,w,x,y,z) cerr<<meta<<#v<<" "<<v<<" "<<#w<<" "<<w<<" "<<#x<<" "<<x<<" "<<#y<<" "<<y<<" "<<#z<<" "<<z<<endl; #define tr6(u,v,w,x,y,z) cerr<<meta<<#u<<" "<<u<<" "<<#v<<" "<<v<<" "<<#w<<" "<<w<<" "<<#x<<" "<<x<<" "<<#y<<" "<<y<<" "<<#z<<" "<<z<<endl; using namespace std; const int N = 100100, off = N; typedef pair<int,int> pii; int n, w[N], inf = 1e9; vector<pii> vals[off+N]; int ptr[off+N]; pii ans[N]; map<pii, int> m; int main(){ sd(n); for(int i = 0; i < n; i++){ int x, y; sd2(x,y); if(y-x >= 0){ vals[off+y-x].pb(mp(x,y)); } else if(y-x < 0){ vals[off+y-x].pb(mp(y,x)); } m[mp(x,y)] = inf; } for(int i = 0; i < N+off; i++){ sort(vals[i].begin(), vals[i].end()); } for(int i = 0; i < n; i++){ sd(w[i]); } if(w[0] != 0){ puts("NO"); return 0; } for(int i = 0; i < n; i++){ if(ptr[off+w[i]] == vals[off+w[i]].size()){ puts("NO"); return 0; } else{ ans[i] = vals[off+w[i]][ptr[off+w[i]]]; ptr[off+w[i]]++; if(w[i] < 0){ swap(ans[i].fi, ans[i].se); } int x = ans[i].fi, y = ans[i].se; m[mp(x,y)] = i+1; if(m.count(mp(x-1,y)) and m[mp(x-1,y)] > i+1){ puts("NO"); return 0; } if(m.count(mp(x,y-1)) and m[mp(x,y-1)] > i+1){ puts("NO"); return 0; } } } puts("YES"); for(int i = 0; i < n; i++){ printf("%d %d\n", ans[i].fi, ans[i].se); } return 0; }
23.441176
139
0.491844
[ "vector" ]
038f36534693b7c3f84894d4828baf45abc969f6
1,608
cpp
C++
LeetCode/DynamicProgramming/UglyNumberII.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
LeetCode/DynamicProgramming/UglyNumberII.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
LeetCode/DynamicProgramming/UglyNumberII.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * LeetCode 264 Ugly Number II * Medium * Jiawei Wang * 2021 6.7 */ /* Revision * $1 2021.8.27 */ #include <iostream> #include <set> #include <vector> using namespace::std; // #1 BFS and Brute Force /* Back to its definition --> Ugly Number means that prime factore are limited to 2, 3 and 5. Which means that --> all Ugly Number must be obtained from other Ugly Number find all Ugly Number */ // #2 Dynamic Programming /* In #1 you can see that we do much "useless" calculations (like exceed the limits when x5). So we use dp, giving each Ugly Number 3 chances -- x2(a), x3(b) and x5(c) these 3 numbers can help us find the minimum number each time -- no sorting needed! The time complexity is O(n) */ class Solution { public: // #1 BFS int nthUglyNumber(int n) { // find all Ugly Numbers vector<int> nums; for (long a = 1; a <= INT_MAX; a *= 2) for (long b = a; b <= INT_MAX; b *= 3) for (long c = b; c <= INT_MAX; c *= 5) // 2^j * 3^k * 5^l nums.push_back(c); std::sort(nums.begin(), nums.end()); return nums[n - 1]; } // #2 DP int nthUglyNumber2(int n) { vector<long>vl({1}); int a=0, b=0, c=0; for (int i=0; i < n-1; i++) { // always find the current minimum ugly number // by using current ugly numbers vector vl * {2, 3, 5} int num = min(min(vl[a]*2, vl[b]*3), vl[c]*5); if (vl[a]*2 == num) a++; if (vl[b]*3 == num) b++; if (vl[c]*5 == num) c++; vl.push_back(num); } return vl[n-1]; } };
20.883117
93
0.556592
[ "vector" ]
038f661c2530462ac8fa5d1d2f093faf9089b211
1,323
cc
C++
concurrency/main.cc
Jiayoushi/nutshell
b0a351a60d039f106776b08e5e61164a59da059e
[ "MIT" ]
null
null
null
concurrency/main.cc
Jiayoushi/nutshell
b0a351a60d039f106776b08e5e61164a59da059e
[ "MIT" ]
null
null
null
concurrency/main.cc
Jiayoushi/nutshell
b0a351a60d039f106776b08e5e61164a59da059e
[ "MIT" ]
null
null
null
#include <iostream> #include <functional> #include <future> #include <vector> #include <thread> #include <cmath> #include <cassert> #include "concurrent_queue.h" void test_concurrent_queue() { ConcurrentQueue<int> cq; auto work = [&cq](uint64_t total_task) { std::cout << std::this_thread::get_id() << std::endl; uint64_t sum = 0; for (int i = 0; i < total_task; ++i) { std::shared_ptr<int> val; do { val = cq.try_pop(); if (val == nullptr) { std::this_thread::yield(); continue; } } while (val == nullptr); sum += *val; } return sum; }; std::vector<std::future<uint64_t>> futures; const uint64_t kWorkPerThread = 1000000; const int kTotalThreads = 10; const uint64_t kTotalWork = kWorkPerThread * kTotalThreads; for (int i = 0; i < kTotalThreads; ++i) { futures.emplace_back(std::move( std::async(std::launch::async, work, kWorkPerThread))); } for (int i = 1; i <= kTotalWork; ++i) { cq.push(i); } uint64_t sum = 0; for (int i = 0; i < kTotalThreads; ++i) { sum += futures[i].get(); } const uint64_t kExpcetedSum = (1 + kTotalWork) * (kTotalWork / 2); assert(sum == kExpcetedSum); } int main() { test_concurrent_queue(); return 0; }
21.33871
68
0.582011
[ "vector" ]
0390bec376d762bd40c53f00d2cfbb3bb24701be
3,834
hpp
C++
external/Carve/src/include/carve/debug_hooks.hpp
skrat/ifcplusplus
1e65d8e0d5e3365d4d1da399081ffaa78fd8a486
[ "MIT" ]
426
2015-04-12T10:00:46.000Z
2022-03-29T11:03:02.000Z
external/Carve/src/include/carve/debug_hooks.hpp
skrat/ifcplusplus
1e65d8e0d5e3365d4d1da399081ffaa78fd8a486
[ "MIT" ]
124
2015-05-15T05:51:00.000Z
2022-02-09T15:25:12.000Z
external/Carve/src/include/carve/debug_hooks.hpp
skrat/ifcplusplus
1e65d8e0d5e3365d4d1da399081ffaa78fd8a486
[ "MIT" ]
214
2015-05-06T07:30:37.000Z
2022-03-26T16:14:04.000Z
// Copyright 2006-2015 Tobias Sargeant (tobias.sargeant@gmail.com). // // This file is part of the Carve CSG Library (http://carve-csg.com/) // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #pragma once #include <carve/carve.hpp> #include <carve/csg.hpp> #include <carve/geom3d.hpp> #include <carve/vector.hpp> #include <iomanip> template <typename MAP> void map_histogram(std::ostream& out, const MAP& map) { std::vector<int> hist; for (typename MAP::const_iterator i = map.begin(); i != map.end(); ++i) { size_t n = (*i).second.size(); if (hist.size() <= n) { hist.resize(n + 1); } hist[n]++; } int total = (int)map.size(); std::string bar(50, '*'); for (size_t i = 0; i < hist.size(); i++) { if (hist[i] > 0) { out << std::setw(5) << i << " : " << std::setw(5) << hist[i] << " " << bar.substr((size_t)(50 - hist[i] * 50 / total)) << std::endl; } } } namespace carve { namespace csg { class IntersectDebugHooks { public: virtual void drawIntersections(const VertexIntersections& /* vint */) {} virtual void drawPoint(const carve::mesh::MeshSet<3>::vertex_t* /* v */, float /* r */, float /* g */, float /* b */, float /* a */, float /* rad */) {} virtual void drawEdge(const carve::mesh::MeshSet<3>::vertex_t* /* v1 */, const carve::mesh::MeshSet<3>::vertex_t* /* v2 */, float /* rA */, float /* gA */, float /* bA */, float /* aA */, float /* rB */, float /* gB */, float /* bB */, float /* aB */, float /* thickness */ = 1.0) {} virtual void drawFaceLoopWireframe( const std::vector<carve::mesh::MeshSet<3>::vertex_t*>& /* face_loop */, const carve::mesh::MeshSet<3>::vertex_t& /* normal */, float /* r */, float /* g */, float /* b */, float /* a */, bool /* inset */ = true) {} virtual void drawFaceLoop( const std::vector<carve::mesh::MeshSet<3>::vertex_t*>& /* face_loop */, const carve::mesh::MeshSet<3>::vertex_t& /* normal */, float /* r */, float /* g */, float /* b */, float /* a */, bool /* offset */ = true, bool /* lit */ = true) {} virtual void drawFaceLoop2( const std::vector<carve::mesh::MeshSet<3>::vertex_t*>& /* face_loop */, const carve::mesh::MeshSet<3>::vertex_t& /* normal */, float /* rF */, float /* gF */, float /* bF */, float /* aF */, float /* rB */, float /* gB */, float /* bB */, float /* aB */, bool /* offset */ = true, bool /* lit */ = true) {} virtual ~IntersectDebugHooks() {} }; IntersectDebugHooks* intersect_installDebugHooks(IntersectDebugHooks* hooks); bool intersect_debugEnabled(); } // namespace csg } // namespace carve
39.9375
79
0.60433
[ "mesh", "vector" ]
039d7019a63c0309e282d0d723a34666114fd143
42,610
hpp
C++
ThreadPool.hpp
tmlrbgfz/threadpool
684b8049820e0c46c0855bbf05723fcf4ac180b4
[ "MIT" ]
2
2018-05-30T07:59:38.000Z
2020-04-19T12:08:16.000Z
ThreadPool.hpp
tmlrbgfz/threadpool
684b8049820e0c46c0855bbf05723fcf4ac180b4
[ "MIT" ]
null
null
null
ThreadPool.hpp
tmlrbgfz/threadpool
684b8049820e0c46c0855bbf05723fcf4ac180b4
[ "MIT" ]
1
2020-04-19T12:08:19.000Z
2020-04-19T12:08:19.000Z
/* * ThreadPool.hpp * * Created on: May 24, 2016 * Author: niklas * * Copyright (c) 2018 Niklas Krafczyk * * 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. * * The permission granted above is not granted to persons developing software for * military or paramilitary uses. */ #ifndef __THREADPOOL_THREADPOOL_H__ #define __THREADPOOL_THREADPOOL_H__ #include <thread> #include <mutex> #include <condition_variable> #include <forward_list> #include <vector> #include <atomic> #include <memory> #include <map> #include <set> #include <list> #include <deque> #include <future> #include <type_traits> #include <utility> #include <functional> #include <algorithm> #include <optional> #ifndef THREADPOOL_STANDALONE #include <boost/thread/shared_mutex.hpp> #include <boost/thread/shared_lock_guard.hpp> #endif #ifdef THREADPOOL_USE_GSL #include <gsl/gsl_assert> #else #define GSL_LIKELY(x) (!!(x)) #define Expects(x) static_cast<void>(0) #endif #include <stdint.h> #include "ThreadPoolPolicies.hpp" #include "AutoCleanedForwardList.hpp" //#define CONGESTION_ANALYSIS /* * List of known flaws: * * 1. After std::numeric_limits<uint64_t>::max() tasks, the TaskIDs wrap * around. While it's not a problem that there is a point where a returned * task id is lower than the previously returned task id, it is possible that * one of the subsequently returned task ids corresponds to a task still in the * list of active tasks. * Example: * Start a task doing some computation forever. * Start std::numeric_limits<uint64_t>::max()-1 tasks. * The next task added is assigned the id still belonging to the task started first. */ template<class Policies = policies::PolicyCollection<policies::DependenciesNotRespected, policies::PassiveWaiting>> class ThreadPool { public: typedef std::vector<std::thread>::size_type size_type; typedef uint64_t TaskID; typedef std::function<void(void)> TaskDefinition; template<typename T> struct TaskHandle_t { //TODO: Make const ThreadPool<Policies>::TaskID const TaskID; std::future<T> future; TaskHandle_t(ThreadPool<Policies>::TaskID id, std::future<T> &&future) : TaskID(id), future(std::move(future)) { } TaskHandle_t(TaskHandle_t const &) = delete; TaskHandle_t(TaskHandle_t &&) = default; TaskHandle_t &operator=(TaskHandle_t const&) = delete; TaskHandle_t &operator=(TaskHandle_t &&) noexcept = default; }; template<typename T> using TaskHandle = struct TaskHandle_t<T>; typedef AutoCleanedForwardList<TaskID>::const_iterator Snapshot; class TaskPackage { private: friend class ThreadPool; std::mutex mutex; std::deque<TaskID> tasks; ThreadPool<Policies> *correspondingPool; TaskPackage(); public: template<typename T, typename ...Args> typename ThreadPool<Policies>::template TaskHandle<T> addTask(std::function<T(Args...)> &&task, const std::set<TaskID> &dependencies, Args...args); template<typename T, typename ...Args> typename ThreadPool<Policies>::template TaskHandle<T> addTask(std::function<T(Args...)> &&task, const TaskID dependency, Args...args); template<typename T, typename ...Args> typename ThreadPool<Policies>::template TaskHandle<T> addTask(std::function<T(Args...)> &&task, Args...args); //Returns true if the tasks which were in this package when calling this function // are all finished. There might be further tasks which were added while this // function was executed bool finished(); void wait(); void wait(TaskID id); std::set<TaskID> getAsDependency() const; }; typedef std::shared_ptr<TaskPackage> TaskPackagePtr; private: template<typename T, typename Enable = void> struct TaskStruct { TaskDefinition fn; std::mutex objMutex; std::condition_variable cv_done; bool done; ~TaskStruct() { std::unique_lock<std::mutex> lock(this->objMutex); } void addDependant(TaskID) {} void setNumberOfDependencies(unsigned long) {} unsigned long getNumberOfDependencies() { return 0; } std::vector<TaskID> getDependants() const { return {}; } }; template<typename T> struct TaskStruct<T, typename std::enable_if<T::respectDependencies>::type> { TaskDefinition fn; std::atomic_ulong dependencyCount; std::vector<TaskID> dependants; std::mutex objMutex; std::condition_variable cv_done; bool done; ~TaskStruct() { std::unique_lock<std::mutex> lock(this->objMutex); } void addDependant(TaskID id) { this->dependants.push_back(id); } void setNumberOfDependencies(unsigned long n) { this->dependencyCount = n; } unsigned long getNumberOfDependencies() { return this->dependencyCount.load(); } std::vector<TaskID> getDependants() const { return dependants; } }; /*template<typename T> struct TaskStruct<typename T, typename std::enable_if<!T::respectDependencies>::type> { TaskDefinition fn; std::mutex objMutex; std::condition_variable cv_done; bool done; };*/ typedef TaskStruct<Policies> Task; private: static std::shared_ptr<std::map<std::thread::id, ThreadPool<Policies>*>> threadAssociation; static std::unique_ptr<ThreadPool<Policies>> defaultInstancePtr; static std::mutex globalMutex; typedef std::list<TaskID> TaskList; typedef std::map<TaskID, std::shared_ptr<ThreadPool<Policies>::Task>> TaskContainer; std::atomic<TaskID> tIdRegistry; std::atomic<size_type> numTasksRunning; std::atomic<size_type> numTasksTotal; std::list<std::thread> threads; std::mutex instanceMutex; std::condition_variable workAvailable; std::condition_variable taskDone; std::mutex completedTasksMutex; AutoCleanedForwardList<TaskID> completedTasks; TaskList inactiveTasks; TaskList activeTasks; std::map<std::thread::id, typename TaskContainer::iterator> threadWork; TaskContainer taskDefinitions; #ifndef THREADPOOL_STANDALONE boost::shared_mutex taskDefAccessMutex; #else std::mutex taskDefAccessMutex; #endif bool stop; unsigned int numThreadsToStop; std::vector<std::thread::id> joinableThreads; size_type maxNumThreads; #ifdef CONGESTION_ANALYSIS std::atomic_ullong instanceLockCongestion, instanceLockTries; std::atomic_ullong taskDefLockCongestion, taskDefLockTries; std::atomic_ullong taskDefExLockCongestion, taskDefExLockTries; void tryLockInstanceLock() { if(this->instanceMutex.try_lock() == false) ++instanceLockCongestion; else this->instanceMutex.unlock(); ++instanceLockTries; } void tryLockTaskDefLockShared() { if(this->taskDefAccessMutex.try_lock_shared() == false) ++taskDefLockCongestion; else this->taskDefAccessMutex.unlock_shared(); ++taskDefLockTries; } void tryLockTaskDefLock() { if(this->taskDefAccessMutex.try_lock() == false) ++taskDefExLockCongestion; else this->taskDefAccessMutex.unlock(); ++taskDefExLockTries; } #endif bool checkDependencies(typename TaskContainer::iterator const &task); void notifyDependencies(Task const *task); void addDependencies(Task *task, TaskID id, const std::set<TaskID> *dependencies); void work(void); bool workOnce(void); typename TaskContainer::iterator getTaskDefinition(const TaskID id, bool lockingRequired); TaskID addTaskDetail(TaskDefinition&& task, const std::set<TaskID> *dependencies = nullptr); void removeTask(const TaskID id); TaskID findNextUnusedTaskId(TaskID id) const; static ThreadPool<Policies> *threadPoolAssociation(); static typename TaskContainer::iterator getOwnTaskIterator(); static TaskID getOwnTaskID(); bool callingThreadBelongsToPool() const; ThreadPool(); public: ThreadPool(size_type size); ThreadPool(const ThreadPool &/*other*/) = delete; ~ThreadPool(); static ThreadPool<Policies>& getDefaultInstance(); static ThreadPool<Policies>* getDefaultInstancePtr(); void setNumberOfThreads(size_type n); size_type getNumberOfThreads(); //Cleanup function joining threads that were stopped to reduce the thread //pool size. Returns the number of joined threads. size_type joinStoppedThreads(); size_type getNumTasksRunning() const; size_type getNumTasks() const; bool empty(); template<typename Fn> auto addTask(Fn task, std::set<TaskID> const &dependencies) -> ThreadPool::TaskHandle<typename std::result_of<Fn()>::type>; template<typename Fn, typename ...Args> auto addTask(Fn task, std::set<TaskID> const &dependencies, Args...args) -> ThreadPool::TaskHandle<typename std::result_of<Fn(Args...)>::type>; template<typename Fn> auto addTask(Fn task) -> ThreadPool::TaskHandle<typename std::result_of<Fn()>::type>; template<typename Fn, typename ...Args> auto addTask(Fn task, Args...args) -> ThreadPool::TaskHandle<typename std::result_of<Fn(Args...)>::type>; /* * Principle of waiting for all tasks to finish: * 1. Lock the instanceMutex. This assures that the task lists are not modified * while we examine them. * 2. If the (probably longer) list of inactive tasks is not empty, the last * task is select. As the lists are processed sequentially from front to back, * this is the task that will be selected last for execution. Note that other * tasks may be inserted after selecting it. * 3. If the list of inactive tasks is empty and the list of active tasks is not empty, * the last task of the list of active tasks is selected. Assuming all tasks to * take about the same amount of time, this is the last one to finish. * 4. If the list of inactive tasks is empty and the list of active tasks is empty, * all queues are empty for the time being, thus all tasks which were in any list when * this function was called finished. Then, this function shall return and no task is selected. * 5. Unlock the instanceMutex. As both lists have been examined, they may be modified again. * 6. If a task was selected, wait for it. Afterwards, goto 1. * 7. If no task was selected, return. */ void wait(); /* * Principle of waiting for one task to finish: * 1. Lock the task definition access mutex shared. Thus, the container mapping * task IDs to task definitions is locked and can still be read but not modified. * This means that the task definition can not be removed before the mutex is * unlocked by all readers. * 2. Get the task definition. If the task does not exist in the container, it already finished. * Therefore we may return after unlocking the mutex again. * 3. If the task definition exists in the container, lock it's internal mutex. * This lock is needed for the condition variable. * 4. When the lock is aquired, the task definition access mutex is unlocked. Thus, * the task definition can be removed from the container if no other thread is currently * locking the mutex shared. * 5. With the task definition mutex locked, this thread can wait on the task definition * condition variable and will be notified when the task is done. * 6. EITHER the task definition was removed from the container before the task * definition access mutex was locked, * OR the task definition was not removed and cannot be removed until the task definition * mutex is held. */ void wait(TaskID id); void waitOne(); bool finished(TaskID id); Snapshot getSnapshot(); std::tuple<std::vector<TaskID>, Snapshot> getCompletedTasksSinceSnapshot(Snapshot const &snapshot); TaskPackagePtr createTaskPackage(); }; template<class Policies> ThreadPool<Policies>::TaskPackage::TaskPackage() : correspondingPool(0) { } template<class Policies> template<typename T, typename ...Args> typename ThreadPool<Policies>::template TaskHandle<T> ThreadPool<Policies>::TaskPackage::addTask(std::function<T(Args...)> &&task, const std::set<TaskID> &dependencies, Args...args) { auto taskHandle = correspondingPool->addTask(std::move(task), std::forward<Args>(args)..., dependencies); std::unique_lock<std::mutex> lock(this->mutex); this->tasks.push_back(taskHandle.TaskID); return taskHandle; } template<class Policies> template<typename T, typename ...Args> typename ThreadPool<Policies>::template TaskHandle<T> ThreadPool<Policies>::TaskPackage::addTask(std::function<T(Args...)> &&task, const TaskID dependency, Args...args) { auto taskHandle = correspondingPool->addTask(std::move(task), std::forward<Args>(args)..., dependency); std::unique_lock<std::mutex> lock(this->mutex); this->tasks.push_back(taskHandle.TaskID); return taskHandle; } template<class Policies> template<typename T, typename ...Args> typename ThreadPool<Policies>::template TaskHandle<T> ThreadPool<Policies>::TaskPackage::addTask(std::function<T(Args...)> &&task, Args...args) { auto taskHandle = correspondingPool->addTask(std::move(task), std::forward<Args>(args)...); std::unique_lock<std::mutex> lock(this->mutex); this->tasks.push_back(taskHandle.TaskID); return taskHandle; } //Returns true if the tasks which were in this package when calling this function // are all finished. There might be further tasks which were added while this // function was executed template<class Policies> bool ThreadPool<Policies>::TaskPackage::finished() { std::deque<ThreadPool<Policies>::TaskID> ids; bool allDone = true; this->mutex.lock(); ids = this->tasks; this->mutex.unlock(); for(const ThreadPool<Policies>::TaskID id : ids) { allDone &= this->correspondingPool->finished(id); } return allDone; } template<class Policies> typename ThreadPool<Policies>::Snapshot ThreadPool<Policies>::getSnapshot() { std::unique_lock<std::mutex> completedTasksLock(this->completedTasksMutex); return this->completedTasks.cbegin(); } template<class Policies> std::tuple<std::vector<typename ThreadPool<Policies>::TaskID>, typename ThreadPool<Policies>::Snapshot> ThreadPool<Policies>::getCompletedTasksSinceSnapshot(typename ThreadPool<Policies>::Snapshot const &snapshot) { Snapshot newSnapshot = snapshot; std::vector<TaskID> result; std::unique_lock<std::mutex> completedTasksLock(this->completedTasksMutex); while(newSnapshot + 1 != this->completedTasks.cend()) { ++newSnapshot; result.push_back(*newSnapshot); } return std::make_tuple(result, newSnapshot); } template<class Policies> void ThreadPool<Policies>::TaskPackage::wait() { while(this->tasks.empty() == false) { TaskID id; this->mutex.lock(); //TODO: Check whether tasks should be popped or spliced to different list if(this->tasks.empty() == false) { id = this->tasks.front(); this->tasks.pop_front(); } else { //Last task finished while locking the mutex, return return; } this->mutex.unlock(); this->correspondingPool->wait(id); } } template<class Policies> void ThreadPool<Policies>::TaskPackage::wait(TaskID id) { this->correspondingPool->wait(id); } template<class Policies> std::set<typename ThreadPool<Policies>::TaskID> ThreadPool<Policies>::TaskPackage::getAsDependency() const { return std::set<TaskID>(tasks.begin(), tasks.end()); } template<class Policies> bool ThreadPool<Policies>::checkDependencies(typename ThreadPool<Policies>::TaskContainer::iterator const &task) { return task->second->getNumberOfDependencies() == 0; } //TODO: Unused template<class Policies> void ThreadPool<Policies>::notifyDependencies(ThreadPool<Policies>::Task const *task) { if(Policies::respectDependencies) { for(const ThreadPool<Policies>::TaskID depID : task->getDependants()) { typename ThreadPool<Policies>::TaskContainer::iterator dep = this->getTaskDefinition(depID, true); //NOTE: Reasoning for assert: The tasks in dependants were added to this pool // The tasks in dependants can't run before this loop finishes // Therefore, the tasks must be in the set of task definitions //BOOST_ASSERT(dep != this->taskDefinitions.end()); dep->second->setNumberOfDependencies(dep->second->getNumberOfDependencies() - 1); } } } template<class Policies> void ThreadPool<Policies>::addDependencies(ThreadPool<Policies>::Task *task, ThreadPool<Policies>::TaskID id, const std::set<ThreadPool<Policies>::TaskID> *dependencies) { if(Policies::respectDependencies && dependencies != nullptr) { std::set<ThreadPool<Policies>::TaskID>::size_type satisfiedDependencies = 0; //After obtaining this shared lock, all dependencies which are still in the task definition container // will not be removed before the dependencies were added #ifdef CONGESTION_ANALYSIS tryLockTaskDefLockShared(); #endif #ifndef THREADPOOL_STANDALONE boost::shared_lock_guard<boost::shared_mutex> tskDefLock(this->taskDefAccessMutex); #else std::lock_guard<std::mutex> tskDefLock(this->taskDefAccessMutex); #endif for(const ThreadPool<Policies>::TaskID dep : *dependencies) { typename ThreadPool<Policies>::TaskContainer::iterator dependency = this->getTaskDefinition(dep, false); if(dependency != this->taskDefinitions.end()) { dependency->second->addDependant(id); } else { //Task already finished, reduce dependency count ++satisfiedDependencies; } } task->setNumberOfDependencies(dependencies->size() - satisfiedDependencies); } else { task->setNumberOfDependencies(0); } } template<class Policies> void ThreadPool<Policies>::work(void) { //Setup std::thread::id threadID = std::this_thread::get_id(); std::weak_ptr<std::map<std::thread::id, ThreadPool<Policies>*>> poolAssociation = ThreadPool<Policies>::threadAssociation; #ifdef CONGESTION_ANALYSIS tryLockInstanceLock(); #endif { std::unique_lock<std::mutex> lock(this->instanceMutex); this->threadWork[threadID] = this->taskDefinitions.end(); } if(poolAssociation.expired() == false) { std::unique_lock<std::mutex> lock(ThreadPool<Policies>::globalMutex); (*(poolAssociation.lock()))[threadID] = this; } bool continueWorking = true; do { { std::unique_lock<std::mutex> lock(this->instanceMutex); //Annahme: Warten auf ConditionVariable findet nicht statt, // wenn das Prädikat true ist // Jeder Thread wartet also darauf, dass inactiveTasks nicht leer ist oder stop true this->workAvailable.wait(lock, [&]() -> bool { return this->inactiveTasks.empty() == false || this->stop == true || this->numThreadsToStop > 0; }); if(this->numThreadsToStop > 0) { this->numThreadsToStop -= 1; break; } if(this->stop == true) { break; } } continueWorking = workOnce(); } while(continueWorking); //Cleanup std::unique_lock<std::mutex> lock(this->instanceMutex); this->joinableThreads.push_back(threadID); this->threadWork.erase(threadID); if(poolAssociation.expired() == false) { std::unique_lock<std::mutex> lock(ThreadPool<Policies>::globalMutex); poolAssociation.lock()->erase(threadID); } } template<class Policies> bool ThreadPool<Policies>::workOnce(void) { std::thread::id threadID = std::this_thread::get_id(); ThreadPool<Policies>::TaskList::iterator front; typename ThreadPool<Policies>::TaskContainer::iterator taskIter; std::shared_ptr<ThreadPool<Policies>::Task> task; TaskID taskID; { #ifdef CONGESTION_ANALYSIS tryLockInstanceLock(); #endif std::unique_lock<std::mutex> lock(this->instanceMutex); if(this->inactiveTasks.empty()) { return true; } front = this->inactiveTasks.begin(); this->activeTasks.splice(this->activeTasks.end(), this->inactiveTasks, front); } //Get task definition taskIter = this->getTaskDefinition(*front, true); //BOOST_ASSERT(taskIter != this->taskDefinitions.end()); //We made sure that only one thread gets this task, thus we don't need locking for the Task struct //If the dependencyCount is greater than zero, this task has unfulfilled dependencies and has to be put back if(Policies::respectDependencies && checkDependencies(taskIter) == false) { #ifdef CONGESTION_ANALYSIS tryLockInstanceLock(); #endif std::unique_lock<std::mutex> lock(this->instanceMutex); this->inactiveTasks.splice(this->inactiveTasks.end(), this->activeTasks, front); return true; } { //Lock not necessary (in theory) std::unique_lock<std::mutex> lock(this->instanceMutex); this->threadWork[threadID] = taskIter; } taskID = taskIter->first; task = taskIter->second; ++(this->numTasksRunning); task->fn(); --(this->numTasksRunning); this->removeTask(taskID); this->taskDone.notify_all(); #ifdef CONGESTION_ANALYSIS tryLockInstanceLock(); #endif std::unique_lock<std::mutex> lock(this->instanceMutex); this->activeTasks.erase(front); task.reset(); this->threadWork[threadID] = this->taskDefinitions.end(); return true; } template<class Policies> typename ThreadPool<Policies>::TaskContainer::iterator ThreadPool<Policies>::getTaskDefinition(const ThreadPool<Policies>::TaskID id, bool lockingRequired) { typename ThreadPool<Policies>::TaskContainer::iterator result; if(lockingRequired) { #ifdef CONGESTION_ANALYSIS tryLockTaskDefLockShared(); #endif //NOTE: Replace with std::shared_lock as soon as C++17 is state-of-the-art #ifndef THREADPOOL_STANDALONE boost::shared_lock_guard<boost::shared_mutex> lock(this->taskDefAccessMutex); #else std::lock_guard<std::mutex> lock(this->taskDefAccessMutex); #endif result = this->taskDefinitions.find(id); } else { result = this->taskDefinitions.find(id); } return result; } template<class Policies> typename ThreadPool<Policies>::TaskID ThreadPool<Policies>::addTaskDetail(typename ThreadPool<Policies>::TaskDefinition&& task, const std::set<typename ThreadPool<Policies>::TaskID> *dependencies) { std::shared_ptr<typename ThreadPool<Policies>::Task> t = std::shared_ptr<typename ThreadPool<Policies>::Task>(new typename ThreadPool<Policies>::Task); t->fn = std::move(task); t->done = false; TaskID id = ++(this->tIdRegistry); ++(this->numTasksTotal); //Emplace Task definition #ifdef CONGESTION_ANALYSIS tryLockTaskDefLock(); #endif this->taskDefAccessMutex.lock(); this->taskDefinitions.emplace(id, t); this->taskDefAccessMutex.unlock(); //Add task dependencies this->addDependencies(t.get(), id, dependencies); //Enqueue in work queue #ifdef CONGESTION_ANALYSIS tryLockInstanceLock(); #endif this->instanceMutex.lock(); this->inactiveTasks.emplace_back(id); this->instanceMutex.unlock(); //Notify a waiting thread (if there is any) this->workAvailable.notify_one(); return id; } template<class Policies> void ThreadPool<Policies>::removeTask(const ThreadPool<Policies>::TaskID id) { typename ThreadPool<Policies>::TaskContainer::iterator taskIter = this->getTaskDefinition(id, true); if(taskIter == this->taskDefinitions.end()) { return; } TaskID taskID = taskIter->first; std::shared_ptr<ThreadPool<Policies>::Task> task = taskIter->second; //First, remove task from task definition container. This marks the task as finished for // all threads which try to obtain it's definition afterwards. //Then, all threads which already have the task definition (by pointer) are notified by the condition variable. #ifdef CONGESTION_ANALYSIS tryLockTaskDefLock(); #endif this->taskDefAccessMutex.lock(); //When this is locked, all threads which might be interested in this task either did not call wait() yet // or they aquired the task definition lock. this->taskDefinitions.erase(taskIter); this->taskDefAccessMutex.unlock(); { std::unique_lock<std::mutex> lock(this->completedTasksMutex); this->completedTasks.push_back(taskID); } //From now on, only threads already having a pointer to the object may access it task->objMutex.lock(); //Now, all threads are either not in the process of accessing the task definition object or are waiting // on the condition variable task->done = true; task->objMutex.unlock(); task->cv_done.notify_all(); //Now, notify all dependencies if(Policies::respectDependencies) { this->notifyDependencies(task.get()); } --(this->numTasksTotal); } /*TODO: template<class Policies> ThreadPool<Policies>::TaskID ThreadPool<Policies>::findNextUnusedTaskId(TaskID id) const;*/ template<class Policies> ThreadPool<Policies> *ThreadPool<Policies>::threadPoolAssociation() { std::thread::id tid = std::this_thread::get_id(); ThreadPool<Policies> *pool = nullptr; { std::unique_lock<std::mutex> lock(ThreadPool<Policies>::globalMutex); typename std::map<std::thread::id, ThreadPool<Policies>*>::iterator thread = ThreadPool<Policies>::threadAssociation->find(tid); if(thread != ThreadPool<Policies>::threadAssociation->end()) { pool = thread->second; } } return pool; } template<class Policies> typename ThreadPool<Policies>::TaskContainer::iterator ThreadPool<Policies>::getOwnTaskIterator() { std::thread::id tid = std::this_thread::get_id(); ThreadPool<Policies> *pool = ThreadPool<Policies>::threadPoolAssociation(); Expects(pool != nullptr); //No lock required, this tasks thread will not change typename ThreadPool<Policies>::TaskContainer::iterator task = pool->threadWork.at(tid); /* * Rationale: * EITHER the calling thread is not part of any thread pool. * Then, pool == 0 and this point is not reached. * OR the calling thread is part of a thread pool. * Then, it either has a task or is in the work()-function. * The work()-function does not call this function, thus the * thread must have a task assigned. */ //BOOST_ASSERT(task != pool->taskDefinitions.end()); return task; } template<class Policies> typename ThreadPool<Policies>::TaskID ThreadPool<Policies>::getOwnTaskID() { return ThreadPool<Policies>::getOwnTaskIterator()->first; } template<class Policies> bool ThreadPool<Policies>::callingThreadBelongsToPool() const { return ThreadPool<Policies>::threadPoolAssociation() == this; } template<class Policies> ThreadPool<Policies>::ThreadPool() : ThreadPool(std::thread::hardware_concurrency() - 1) { } template<class Policies> ThreadPool<Policies>::ThreadPool(size_type size) : tIdRegistry(0), numTasksRunning(0), numTasksTotal(0), completedTasks(static_cast<uint64_t>(static_cast<int64_t>(-1))), stop(false), numThreadsToStop(0), maxNumThreads(0) { #ifdef CONGESTION_ANALYSIS this->instanceLockCongestion.store(0); this->instanceLockTries.store(0); this->taskDefLockCongestion.store(0); this->taskDefLockTries.store(0); this->taskDefExLockCongestion.store(0); this->taskDefExLockTries.store(0); #endif this->setNumberOfThreads(size); } template<class Policies> ThreadPool<Policies>::~ThreadPool() { #ifdef CONGESTION_ANALYSIS tryLockInstanceLock(); #endif this->instanceMutex.lock(); this->stop = true; this->instanceMutex.unlock(); this->workAvailable.notify_all(); //Wait for all tasks to finish, then join them this->wait(); for(std::thread &thr : this->threads) { thr.join(); } #ifdef CONGESTION_ANALYSIS std::cout << this->instanceLockCongestion.load() << "/" << this->instanceLockTries.load() << std::endl; std::cout << this->taskDefLockCongestion.load() << "/" << this->taskDefLockTries.load() << std::endl; std::cout << this->taskDefExLockCongestion.load() << "/" << this->taskDefExLockTries.load() << std::endl; #endif } template<class Policies> ThreadPool<Policies>& ThreadPool<Policies>::getDefaultInstance() { return *ThreadPool<Policies>::getDefaultInstancePtr(); } template<class Policies> ThreadPool<Policies>* ThreadPool<Policies>::getDefaultInstancePtr() { if(ThreadPool<Policies>::defaultInstancePtr.get() == nullptr) { ThreadPool<Policies>::defaultInstancePtr.reset(new ThreadPool<Policies>); } return ThreadPool<Policies>::defaultInstancePtr.get(); } template<class Policies> void ThreadPool<Policies>::setNumberOfThreads(size_type n) { std::unique_lock<std::mutex> lock(this->instanceMutex); if(n < this->maxNumThreads) { this->numThreadsToStop = (this->maxNumThreads - n); this->maxNumThreads = n; } while(n > this->maxNumThreads) { this->threads.emplace_back(std::bind(&ThreadPool<Policies>::work, this)); ++this->maxNumThreads; } } template<class Policies> typename ThreadPool<Policies>::size_type ThreadPool<Policies>::getNumberOfThreads() { std::unique_lock<std::mutex> lock(this->instanceMutex); return this->maxNumThreads; } //Cleanup function joining threads that were stopped to reduce the thread //pool size. Returns the number of joined threads. template<class Policies> typename ThreadPool<Policies>::size_type ThreadPool<Policies>::joinStoppedThreads() { std::list<std::thread> threadList; std::vector<std::list<std::thread>::iterator> listItemsToRemove; listItemsToRemove.reserve(this->threads.size()); { std::unique_lock<std::mutex> lock(this->instanceMutex); for(auto iter = this->threads.begin(); iter != this->threads.end(); ++iter) { if(std::any_of(this->joinableThreads.begin(), this->joinableThreads.end(), [&iter](std::thread::id id)->bool{ return id == iter->get_id(); })) { listItemsToRemove.push_back(iter); } } //Splicing invalidates the iterator in question thus we cannot do this in the loop above for(auto &iter : listItemsToRemove) { threadList.splice(threadList.end(), this->threads, iter); } } for(auto &thread : threadList) { thread.join(); } return threadList.size(); } template<class Policies> typename ThreadPool<Policies>::size_type ThreadPool<Policies>::getNumTasksRunning() const { return this->numTasksRunning.load(); } template<class Policies> typename ThreadPool<Policies>::size_type ThreadPool<Policies>::getNumTasks() const { return this->numTasksTotal.load(); } template<class Policies> bool ThreadPool<Policies>::empty() { if(this->activeTasks.empty() and this->inactiveTasks.empty()) { std::unique_lock<std::mutex> lock(this->instanceMutex); return this->activeTasks.empty() and this->inactiveTasks.empty(); } return false; } template<class Policies> template<typename Fn> auto ThreadPool<Policies>::addTask(Fn task, std::set<typename ThreadPool<Policies>::TaskID> const &dependencies) -> ThreadPool<Policies>::TaskHandle<typename std::result_of<Fn()>::type> { typedef typename std::result_of<Fn()>::type ReturnType; std::packaged_task<ReturnType()> *packagedTask = new std::packaged_task<ReturnType()>(task); auto future = std::move(packagedTask->get_future()); auto TaskID = this->addTaskDetail([packagedTask]()->void{ (*packagedTask)(); delete packagedTask; }, &dependencies); return ThreadPool<Policies>::TaskHandle<ReturnType>{TaskID, std::move(future)}; } template<class Policies> template<typename Fn, typename ...Args> auto ThreadPool<Policies>::addTask(Fn task, std::set<ThreadPool<Policies>::TaskID> const &dependencies, Args...args) -> ThreadPool<Policies>::TaskHandle<typename std::result_of<Fn(Args...)>::type> { return this->addTask(std::bind(task, std::forward<Args>(args)...), dependencies); } template<class Policies> template<typename Fn> auto ThreadPool<Policies>::addTask(Fn task) -> ThreadPool<Policies>::TaskHandle<typename std::result_of<Fn()>::type> { typedef typename std::result_of<Fn()>::type ReturnType; std::packaged_task<ReturnType()> *packagedTask = new std::packaged_task<ReturnType()>(task); auto future = std::move(packagedTask->get_future()); auto TaskID = this->addTaskDetail([packagedTask]()->void{ (*packagedTask)(); delete packagedTask; }); return ThreadPool<Policies>::TaskHandle<ReturnType>{TaskID, std::move(future)}; } template<class Policies> template<typename Fn, typename ...Args> auto ThreadPool<Policies>::addTask(Fn task, Args...args) -> ThreadPool<Policies>::TaskHandle<typename std::result_of<Fn(Args...)>::type> { return this->addTask(std::bind(task, std::forward<Args>(args)...)); } /* * Principle of waiting for all tasks to finish: * 1. Lock the instanceMutex. This assures that the task lists are not modified * while we examine them. * 2. If the (probably longer) list of inactive tasks is not empty, the last * task is select. As the lists are processed sequentially from front to back, * this is the task that will be selected last for execution. Note that other * tasks may be inserted after selecting it. * 3. If the list of inactive tasks is empty and the list of active tasks is not empty, * the last task of the list of active tasks is selected. Assuming all tasks to * take about the same amount of time, this is the last one to finish. * 4. If the list of inactive tasks is empty and the list of active tasks is empty, * all queues are empty for the time being, thus all tasks which were in any list when * this function was called finished. Then, this function shall return and no task is selected. * 5. Unlock the instanceMutex. As both lists have been examined, they may be modified again. * 6. If a task was selected, wait for it. Afterwards, goto 1. * 7. If no task was selected, return. */ template<class Policies> void ThreadPool<Policies>::wait() { ThreadPool<Policies>::TaskID lastTask; bool allQueuesEmpty = false; bool inactiveTasksEmpty = true; while(not allQueuesEmpty) { { #ifdef CONGESTION_ANALYSIS tryLockInstanceLock(); #endif std::unique_lock<std::mutex> lock(this->instanceMutex); inactiveTasksEmpty = this->inactiveTasks.empty(); allQueuesEmpty = inactiveTasksEmpty && this->activeTasks.empty(); } if(Policies::activeWaiting and not inactiveTasksEmpty) { this->workOnce(); } else if(not allQueuesEmpty) { TaskID lastTask; { std::unique_lock<std::mutex> lock(this->instanceMutex); //instance mutex was unlocked in between, empty status could // have changed, needs to be checked again if(not this->activeTasks.empty()) { lastTask = this->activeTasks.back(); } else { //activeTasks now empty, do another loop to check again continue; } } //Wait for the last task to finish. Then check again as other tasks // could have been added/started in the meantime this->wait(lastTask); } } } /* * Principle of waiting for one task to finish: * 1. Lock the task definition access mutex shared. Thus, the container mapping * task IDs to task definitions is locked and can still be read but not modified. * This means that the task definition can not be removed before the mutex is * unlocked by all readers. * 2. Get the task definition. If the task does not exist in the container, it already finished. * Therefore we may return after unlocking the mutex again. * 3. If the task definition exists in the container, lock it's internal mutex. * This lock is needed for the condition variable. * 4. When the lock is aquired, the task definition access mutex is unlocked. Thus, * the task definition can be removed from the container if no other thread is currently * locking the mutex shared. * 5. With the task definition mutex locked, this thread can wait on the task definition * condition variable and will be notified when the task is done. * 6. EITHER the task definition was removed from the container before the task * definition access mutex was locked, * OR the task definition was not removed and cannot be removed until the task definition * mutex is held. */ template<class Policies> void ThreadPool<Policies>::wait(TaskID id) { #ifdef CONGESTION_ANALYSIS tryLockTaskDefLockShared(); #endif #ifndef THREADPOOL_STANDALONE this->taskDefAccessMutex.lock_shared(); #else this->taskDefAccessMutex.lock(); #endif typename ThreadPool<Policies>::TaskContainer::iterator task = this->getTaskDefinition(id, false); if(task == this->taskDefinitions.end()) { #ifndef THREADPOOL_STANDALONE this->taskDefAccessMutex.unlock_shared(); #else this->taskDefAccessMutex.unlock(); #endif return; } std::shared_ptr<ThreadPool<Policies>::Task> taskPtr = task->second; #ifndef THREADPOOL_STANDALONE this->taskDefAccessMutex.unlock_shared(); #else this->taskDefAccessMutex.unlock(); #endif /* * In wait(), we simply used the calling thread to do some work to speed up * the work. Here, this is not possible as using a thread which is not * part of the pool to wait for a task inside the pool to finish to work on * a different task could make the waiting thread miss the end of the task * it's waiting for. Thus, tasks inside the pool can work on other tasks * inside the same pool while waiting and tasks outside the pool simply * wait. */ /*unsafe for now (workOnce could start working on an infinite task): if(Policies::activeWaiting) { while([&]()->bool{ std::unique_lock<std::mutex> lock(taskPtr->objMutex); return not taskPtr->done; }()) { workOnce(); } } else*/ { std::unique_lock<std::mutex> lock(taskPtr->objMutex); taskPtr->cv_done.wait(lock, [&]() -> bool { return taskPtr->done; }); } } template<class Policies> void ThreadPool<Policies>::waitOne() { if(this->getNumTasks() == 0) { return; } auto snapshot = this->getSnapshot(); if(not this->callingThreadBelongsToPool()) { std::unique_lock<std::mutex> lock(this->instanceMutex); this->taskDone.wait(lock, [&snapshot,this]() -> bool { return snapshot != this->getSnapshot(); }); } else { workOnce(); } } template<class Policies> bool ThreadPool<Policies>::finished(TaskID id) { return this->getTaskDefinition(id, true) == this->taskDefinitions.end(); } template<class Policies> typename ThreadPool<Policies>::TaskPackagePtr ThreadPool<Policies>::createTaskPackage() { ThreadPool<Policies>::TaskPackage *pkg = new ThreadPool<Policies>::TaskPackage; //TODO: Maybe use a weak ptr and initialise it from a private shared_ptr of the Pool? pkg->correspondingPool = this; return std::shared_ptr<ThreadPool<Policies>::TaskPackage>(pkg); } template<typename Policies> std::shared_ptr<std::map<std::thread::id, ThreadPool<Policies>*>> ThreadPool<Policies>::threadAssociation { new std::map<std::thread::id, ThreadPool<Policies>*> }; template<typename Policies> std::unique_ptr<ThreadPool<Policies>> ThreadPool<Policies>::defaultInstancePtr = nullptr; template<typename Policies> std::mutex ThreadPool<Policies>::globalMutex; /*template<class Iterator, class R, class Policies> std::tuple<typename ThreadPool<Policies>::TaskPackagePtr, std::vector<typename ThreadPool<Policies>::TaskHandle<typename R>>> distributeContainerOperationOnPool(ThreadPool<Policies> &pool, Iterator begin, Iterator end, std::function<R(Iterator,Iterator)> fn) { auto const poolsize = pool.getNumberOfThreads(); auto const numElements = std::distance(begin, end); auto const numElementsPerThread = std::max(1, numElements/poolsize); Iterator intermediate = begin; typename ThreadPool<Policies>::TaskPackagePtr package = pool.createTaskPackage(); std::vector<typename ThreadPool<Policies>::TaskHandle<R>> handles; for(unsigned int i = 0; i < (numElements/numElementsPerThread); ++i) { Iterator intermediateEnd = intermediate; std::advance(intermediateEnd, numElementsPerThread); handles.push_back(package->addTask(fn, intermediate, intermediateEnd)); } handles.push_back(package->addTask(fn, intermediateEnd, end)); return std::make_tuple<typename ThreadPool<Policies>::TaskPackagePtr, std::vector<typename ThreadPool<Policies>::TaskHandle<R>>>(package, handles); }*/ #endif /* __THREADPOOL_THREADPOOL_H__ */
40.619638
187
0.695025
[ "object", "vector" ]
03aa76385b72abb715b6ad343ff77fd02c69a4b4
970
cpp
C++
jp.atcoder/abc112/abc112_c/11951184.cpp
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-09T03:06:25.000Z
2022-02-09T03:06:25.000Z
jp.atcoder/abc112/abc112_c/11951184.cpp
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
1
2022-02-05T22:53:18.000Z
2022-02-09T01:29:30.000Z
jp.atcoder/abc112/abc112_c/11951184.cpp
kagemeka/atcoder-submissions
91d8ad37411ea2ec582b10ba41b1e3cae01d4d6e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<int> x(n); vector<int> y(n); vector<int> h(n); for (int i = 0; i < n; i++) cin >> x[i] >> y[i] >> h[i]; int x0, y0, h0; for (int i = 0; i < n; i++) { if (h[i]) { x0 = x[i]; y0 = y[i]; h0 = h[i]; break; } } vector<vector<int>> cand; for (int cx = 0; cx < 101; cx++) { for (int cy = 0; cy < 101; cy++) { int ch = h0 + abs(cx - x0) + abs(cy - y0); bool flag = true; for (int i = 0; i < n; i++) { if (max(ch - abs(x[i] - cx) - abs(y[i] - cy), 0) != h[i]) { flag = false; break; } } if (flag) { cand.push_back({ch, cx, cy}); } } } sort(cand.begin(), cand.end(), greater<vector<int>>()); printf("%d %d %d\n", cand[0][1], cand[0][2], cand[0][0]); return 0; }
23.095238
68
0.413402
[ "vector" ]
03adb6315b4074aa646c7782f6733fa9db4561c6
425
hpp
C++
src/utils/js_utils.hpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
13
2017-01-07T07:48:54.000Z
2021-09-29T05:33:38.000Z
src/utils/js_utils.hpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
27
2016-11-24T11:35:22.000Z
2022-02-14T14:38:09.000Z
src/utils/js_utils.hpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
3
2017-10-19T10:12:11.000Z
2019-10-11T16:21:09.000Z
#pragma once #include "../flac_addon.hpp" #include <napi.h> namespace flac_bindings { static inline Napi::Object objectFreeze(Napi::Object& obj) { #if NAPI_VERSION < 8 auto Object = obj.Env().Global().Get("Object").As<Napi::Object>(); auto freeze = Object.Get("freeze").As<Napi::Function>(); return freeze.Call({obj}).As<Napi::Object>(); return obj; #else obj.Freeze(); return obj; #endif } }
20.238095
70
0.647059
[ "object" ]
03ae3f993bce530aef007fbebefb45dcee55b1ba
936
cpp
C++
libvermilion/core/src/window.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/window.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/window.cpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#include "window.hpp" #include <vermilion/instance.hpp> #include "platform/glfw/window.hpp" #include <stdexcept> const int Vermilion::Core::windowPlatform[] = { #ifdef VMCORE_GLFW Vermilion::Core::WindowPlatform::WINDOW_PLATFORM_GLFW, #endif Vermilion::Core::WindowPlatform::WINDOW_PLATFORM_NONE }; Vermilion::Core::Window * Vermilion::Core::Window::create(int platform, int renderPlatform, Vermilion::Core::WindowCallbackFunctions windowCallbackFunctions, Vermilion::Core::Instance * instance){ switch(platform){ #ifdef VMCORE_GLFW case Vermilion::Core::WindowPlatform::WINDOW_PLATFORM_GLFW: return new Vermilion::Core::GLFW::Window(renderPlatform, windowCallbackFunctions, instance); break; #endif default: instance->logger.log(VMCORE_LOGLEVEL_FATAL, "Render platform not supported"); throw std::runtime_error("Vermilion::Core::Windor::create() - Render platform not supported"); break; } return nullptr; }
33.428571
196
0.775641
[ "render" ]
03ae836baaee9eed36dc831eda9f50bea31d1f28
6,198
hpp
C++
Includes/boost-di/di/core/dependency.hpp
webfinesse/veritas-engine
de771f2dcaa1a58550d07500e33e50940e3f5e58
[ "MIT" ]
null
null
null
Includes/boost-di/di/core/dependency.hpp
webfinesse/veritas-engine
de771f2dcaa1a58550d07500e33e50940e3f5e58
[ "MIT" ]
null
null
null
Includes/boost-di/di/core/dependency.hpp
webfinesse/veritas-engine
de771f2dcaa1a58550d07500e33e50940e3f5e58
[ "MIT" ]
null
null
null
// // Copyright (c) 2012-2017 Kris Jusiak (kris at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_DI_CORE_DEPENDENCY_HPP #define BOOST_DI_CORE_DEPENDENCY_HPP #include "boost/di/aux_/compiler.hpp" #include "boost/di/aux_/type_traits.hpp" #include "boost/di/aux_/utility.hpp" #include "boost/di/concepts/boundable.hpp" #include "boost/di/concepts/scopable.hpp" #include "boost/di/core/array.hpp" #include "boost/di/fwd.hpp" #include "boost/di/scopes/deduce.hpp" #include "boost/di/scopes/instance.hpp" namespace core { template <class, class> struct dependency_concept {}; template <class T, class TDependency> struct dependency_impl : aux::pair<T, TDependency> {}; template <class T> struct make_dependency_concept { using type = dependency_concept<T, no_name>; }; template <class TName, class T> struct make_dependency_concept<named<TName, T>> { using type = dependency_concept<T, TName>; }; template <class... Ts, class TName, class TDependency> struct dependency_impl<dependency_concept<concepts::any_of<Ts...>, TName>, TDependency> : aux::pair<dependency_concept<Ts, TName>, TDependency>... {}; template <class... Ts, class TDependency> struct dependency_impl<dependency_concept<aux::type_list<Ts...>, no_name>, TDependency> : aux::pair<typename make_dependency_concept<Ts>::type, TDependency>... {}; struct override {}; template <class TScope, class TExpected, class TGiven, class TName, class TPriority> class dependency : dependency_base, __BOOST_DI_ACCESS_WKND TScope::template scope<TExpected, TGiven>, public dependency_impl<dependency_concept<TExpected, TName>, dependency<TScope, TExpected, TGiven, TName, TPriority>> { template <class, class, class, class, class> friend class dependency; using scope_t = typename TScope::template scope<TExpected, TGiven>; template <class T> using externable = aux::integral_constant< bool, aux::always<T>::value && aux::is_same<TScope, scopes::deduce>::value && aux::is_same<TExpected, TGiven>::value>; template <class T> struct ref_traits { using type = T; }; template <int N> struct ref_traits<const char (&)[N]> { using type = TExpected; }; template <class R, class... Ts> struct ref_traits<R (&)(Ts...)> { using type = TExpected; }; template <class T> struct ref_traits<std::shared_ptr<T>&> { using type = std::shared_ptr<T>; }; template <class T, class> struct deduce_traits { using type = T; }; template <class T> struct deduce_traits<deduced, T> { using type = aux::decay_t<T>; }; template <class T, class U> using deduce_traits_t = typename deduce_traits<T, U>::type; public: using scope = TScope; using expected = TExpected; using given = TGiven; using name = TName; using priority = TPriority; dependency() noexcept {} template <class T> explicit dependency(T&& object) noexcept : scope_t(static_cast<T&&>(object)) {} template <class T, __BOOST_DI_REQUIRES(aux::is_same<TName, no_name>::value && !aux::is_same<T, no_name>::value) = 0> auto named() noexcept { return dependency<TScope, TExpected, TGiven, T, TPriority>{static_cast<dependency&&>(*this)}; } template <class T, __BOOST_DI_REQUIRES(aux::is_same<TName, no_name>::value && !aux::is_same<T, no_name>::value) = 0> auto named(const T&) noexcept { return dependency<TScope, TExpected, TGiven, T, TPriority>{static_cast<dependency&&>(*this)}; } template <class T, __BOOST_DI_REQUIRES_MSG(concepts::scopable<T>) = 0> auto in(const T&)noexcept { return dependency<T, TExpected, TGiven, TName, TPriority>{}; } template <class T, __BOOST_DI_REQUIRES(!aux::is_array<TExpected, T>::value) = 0, __BOOST_DI_REQUIRES_MSG(concepts::boundable<TExpected, T>) = 0> auto to() noexcept { return dependency<TScope, TExpected, T, TName, TPriority>{}; } template <class... Ts, __BOOST_DI_REQUIRES(aux::is_array<TExpected, Ts...>::value) = 0> auto to() noexcept { using type = aux::remove_pointer_t<aux::remove_extent_t<TExpected>>; return dependency<TScope, array<type>, array<type, Ts...>, TName, TPriority>{}; } template <class T, __BOOST_DI_REQUIRES_MSG(concepts::boundable<TExpected, T>) = 0> auto to(std::initializer_list<T>&& object) noexcept { using type = aux::remove_pointer_t<aux::remove_extent_t<TExpected>>; using dependency = dependency<scopes::instance, array<type>, std::initializer_list<T>, TName, TPriority>; return dependency{object}; } template <class T, __BOOST_DI_REQUIRES(externable<T>::value) = 0, __BOOST_DI_REQUIRES_MSG(concepts::boundable<deduce_traits_t<TExpected, T>, aux::decay_t<T>, aux::valid<>>) = 0> auto to(T&& object) noexcept { using dependency = dependency<scopes::instance, deduce_traits_t<TExpected, T>, typename ref_traits<T>::type, TName, TPriority>; return dependency{static_cast<T&&>(object)}; } template <class TConcept, class T, __BOOST_DI_REQUIRES(externable<T>::value) = 0, __BOOST_DI_REQUIRES_MSG(concepts::boundable<deduce_traits_t<TExpected, T>, aux::decay_t<T>, aux::valid<>>) = 0> auto to(T&& object) noexcept { using dependency = dependency<scopes::instance, deduce_traits_t<concepts::any_of<TExpected, TConcept>, T>, typename ref_traits<T>::type, TName, TPriority>; return dependency{static_cast<T&&>(object)}; } template <template <class...> class T> auto to() noexcept { return dependency<TScope, TExpected, aux::identity<T<>>, TName, TPriority>{}; } template <class...> dependency& to(...) const noexcept; auto operator[](const override&) noexcept { return dependency<TScope, TExpected, TGiven, TName, override>{static_cast<dependency&&>(*this)}; } #if defined(__cpp_variable_templates) // __pph__ dependency& operator()() noexcept { return *this; } #endif // __pph__ public: using scope_t::is_referable; using scope_t::create; using scope_t::try_create; template <class, class> static void try_create(...); }; } // core #endif
33.868852
125
0.702646
[ "object" ]
03c3e33c1cd0e51574a4eba191a16b19a17a5e51
222
cpp
C++
main.cpp
ozgurozkan01/2DSnakeGame
ab51acb9a4b1c4ac6b7fa762fdf9f5b15fb43946
[ "MIT" ]
null
null
null
main.cpp
ozgurozkan01/2DSnakeGame
ab51acb9a4b1c4ac6b7fa762fdf9f5b15fb43946
[ "MIT" ]
null
null
null
main.cpp
ozgurozkan01/2DSnakeGame
ab51acb9a4b1c4ac6b7fa762fdf9f5b15fb43946
[ "MIT" ]
null
null
null
#include <iostream> #include "SFML/Graphics.hpp" #include "Game.h" int main() { srand(time(NULL)); Game game; while(game.IsOpen()) { game.Update(); game.Render(); } return 0; }
11.1
28
0.536036
[ "render" ]
03c4b1ea77d253a286aa7c8058767a13a461b303
13,533
cpp
C++
src/metriclearn/largemargin.cpp
JoOkuma/segm
6d3ea82c4ee6dcc94c26db8e9d03392397646449
[ "MIT" ]
1
2020-04-27T13:00:31.000Z
2020-04-27T13:00:31.000Z
src/metriclearn/largemargin.cpp
JoOkuma/segm
6d3ea82c4ee6dcc94c26db8e9d03392397646449
[ "MIT" ]
null
null
null
src/metriclearn/largemargin.cpp
JoOkuma/segm
6d3ea82c4ee6dcc94c26db8e9d03392397646449
[ "MIT" ]
null
null
null
#include <cmath> #include <iostream> #include <limits> #include "metriclearn/largemargin.h" #include "math/statistics.h" #ifdef _OPENMP #include "omp.h" #endif using namespace Eigen; using namespace segm; LargeMargin::LargeMargin(MatrixXd &_data, VectorXi &_label, int output_dim, int _k_targets, int _k_impostors, int _iterations, double _learn_rate, bool _verbose) : data(_data), label(_label), L(output_dim, _data.cols()), size(static_cast<int>(_data.rows())), d_in(static_cast<int>(_data.cols())), d_out(output_dim), k_targets(_k_targets), k_impostors(_k_impostors), initial_learn_rate(_learn_rate), iterations(_iterations), verbose(_verbose) { checkKTargets(); } void LargeMargin::train() { L = MatrixXd(PCA(data, d_out)); createDistTable(&data); if (verbose && dist_table_computed) std::cout << "Distance matrix computed" << std::endl; MatrixXi target = findTargets(); MatrixXd target_grad = computeTargetGrad(target); if (verbose) std::cout << "Target neighbours found and target static gradient computed" << std::endl; MatrixXd next_L(L); MatrixXd next_Ldata = transform(data); createDistTable(&next_Ldata); std::vector<LargeMargin::impSet> impostors = findImpostors(target); MatrixXd imp_grad = computeImpGrad(impostors); /* buffers */ MatrixXd next_imp_grad(d_in, d_in); MatrixXd gradient(d_in, d_in); MatrixXd grad_prod(d_out, d_in); const double epsilon = 1e-7; const double min_learn_rate = 1e-22; current_learn_rate = initial_learn_rate; int ite = 0; double delta; double loss = gradLoss(target_grad, next_L) + gradLoss(imp_grad, next_L) + impostors.size(); do { ite++; do { updateTransform(target_grad, imp_grad, gradient, grad_prod, next_L); next_Ldata.noalias() = data.lazyProduct(next_L.transpose()); createDistTable(&next_Ldata); std::vector<LargeMargin::impSet> next_imp = findImpostors(target); std::vector<LargeMargin::impSet> missing; std::vector<LargeMargin::impSet> extra; findDifference(impostors, next_imp, missing, extra); computeImpGrad(imp_grad, next_imp_grad, missing, extra); double next_loss = gradLoss(target_grad, next_L) + gradLoss(next_imp_grad, next_L) + next_imp.size(); delta = next_loss - loss; if (delta > 0.0) { current_learn_rate /= 2; } else { current_learn_rate *= 1.01; loss = next_loss; L.swap(next_L); imp_grad.swap(next_imp_grad); impostors = next_imp; } } while (current_learn_rate > min_learn_rate && delta > 0.0); if (verbose) std::cout << "Iteration: " << ite << std::endl << "Loss: " << loss << std::endl << "Delta: " << delta << std::endl << "Active Impostors: " << impostors.size() << std::endl << "Learning Rate: " << current_learn_rate << std::endl; } while (ite < iterations && !impostors.empty() && fabs(delta) > epsilon && current_learn_rate > min_learn_rate); delete[] dist_table; } void LargeMargin::createDistTable(MatrixXd *current) { current_data = current; if (dist_table_computed) { delete[] dist_table; dist_table_computed = false; } dist_table = new (std::nothrow) double[(size * (size - 1)) / 2]; if (!dist_table) { dist_table_computed = false; return; } #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 1; i < size; i++) { int row_id = (i * (i - 1)) / 2; for (int j = 0; j < i; j++) { dist_table[row_id + j] = squaredNorm(current->row(i), current->row(j)); } } if (verbose) std::cout << "Computed triangular distance matrix" << std::endl; dist_table_computed = true; } double LargeMargin::distance(int i, int j) { // very unlikely to happen if (i == j) return std::numeric_limits<double>::max(); if (!dist_table_computed) return squaredNorm(current_data->row(i), current_data->row(j)); int greater = (i > j) ? i : j; int lower = (i > j) ? j : i; int row_id = (greater * (greater - 1) / 2); return dist_table[row_id + lower]; } MatrixXi LargeMargin::findTargets() { VectorXd max_dist(size); MatrixXi target(size, k_targets); MatrixXd target_dist(size, k_targets); target_dist.setConstant(std::numeric_limits<double>::max()); target.setConstant(-1); max_dist.setConstant(std::numeric_limits<double>::max()); int last = k_targets - 1; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (label[i] == label[j] && i != j) { double dist = distance(i, j); if (dist < max_dist[i]) { int idx = last; while (idx > 0 && dist < target_dist(i, idx - 1)) { target_dist(i, idx) = target_dist(i, idx - 1); target(i, idx) = target(i, idx - 1); idx--; } target_dist(i, idx) = dist; target(i, idx) = j; max_dist[i] = target_dist(i, last); } } } } return target; } void LargeMargin::checkKTargets() { int max_lab = -1; for (int i = 0; i < size; i++) { if (max_lab < label[i]) max_lab = label[i]; } max_lab += 1; int *lab_count = new int[max_lab](); for (int i = 0; i < size; i++) { lab_count[label[i]] += 1; } int min = std::numeric_limits<int>::max(); for (int i = 0; i < max_lab; i++) { if (min > lab_count[i]) min = lab_count[i]; } min -=1; if (min < k_targets) { k_targets = min; std::cout << "Number of neighbors reduced to " << min << ", number of samples " "with same class not sufficient." << std::endl; } delete[] lab_count; } MatrixXd LargeMargin::computeTargetGrad(const MatrixXi &target) { MatrixXd target_grad(d_in, d_in); #ifdef _OPENMP #pragma omp parallel for #endif for (int di = 0; di < d_in; di++) { for (int dj = 0; dj < d_in; dj++) { for (int i = 0; i < size; i++) { for (int k = 0; k < k_targets; k++) { int tk = target(i, k); target_grad(di, dj) += + data(i, di) * data(i, dj) + data(tk, di) * data(tk, dj) - data(i, di) * data(tk, dj) - data(tk, di) * data(i, dj); } } } } return target_grad; } std::vector<LargeMargin::impSet> LargeMargin::findImpostors(const MatrixXi &target) { #ifndef _OPENMP unsigned long n_threads = 1; std::vector<std::vector<LargeMargin::impSet>> imp_arr(1); #else unsigned long n_threads = 8; std::vector<std::vector<LargeMargin::impSet>> imp_arr(n_threads); #pragma omp parallel for num_threads(n_threads) #endif for (int i = 0; i < size; i++) { #ifdef _OPENMP int thread_id = omp_get_thread_num(); #else int thread_id = 0; #endif int count = 0; for (int ik = 0; ik < size; ik++) { if (count >= k_impostors) break; if (label[i] != label[ik]) { double imp_dist = distance(i, ik); bool is_imp = false; for (int j = 0; j < k_targets; j++) { int tk = target(i, j); double diff = distance(i, tk) + 1.0 - imp_dist; if (diff > 0) { LargeMargin::impSet s = {.example = i, .impostor = ik, .target = tk}; imp_arr[thread_id].push_back(s); is_imp = true; } } if (is_imp) count++; } } } std::vector<LargeMargin::impSet> out; for (unsigned long i = 0; i < n_threads; i++) { out.insert(out.end(), imp_arr[i].begin(), imp_arr[i].end()); } return out; } /* find extra and missing impostors from `next_imp to `impostors` */ void LargeMargin::findDifference(const std::vector<LargeMargin::impSet> &impostors, const std::vector<LargeMargin::impSet> &next_imp, std::vector<LargeMargin::impSet> &missing, std::vector<LargeMargin::impSet> &extra) { unsigned long smaller_size = (next_imp.size() < impostors.size()) ? next_imp.size() : impostors.size(); missing.clear(); extra.clear(); unsigned long i = 0, j = 0; for (i = 0, j = 0; i < smaller_size && j < smaller_size; i++, j++) { if (next_imp.at(i) != impostors.at(j)) { if (next_imp.at(i) < impostors.at(j)) { missing.push_back(next_imp.at(i)); j--; } else { extra.push_back(impostors.at(j)); i--; } } } for (; i < next_imp.size(); i++) { missing.push_back(next_imp.at(i)); } for (; j < impostors.size(); j++) { extra.push_back(impostors.at(j)); } } MatrixXd LargeMargin::computeImpGrad(const std::vector<LargeMargin::impSet> &impostors) { MatrixXd imp_grad(d_in, d_in); #ifdef _OPENMP #pragma omp parallel for #endif for (int di = 0; di < d_in; di++) { for (int dj = 0; dj < d_in; dj++) { /* adding */ for (impSet s : impostors) { int e = s.example; int ik = s.impostor; int tk = s.target; /* impostors */ imp_grad(di, dj) += - data(e, di) * data(e, dj) - data(ik, di) * data(ik, dj) + data(e, di) * data(ik, dj) + data(ik, di) * data(e, dj); /* target */ imp_grad(di, dj) += + data(e, di) * data(e, dj) + data(tk, di) * data(tk, dj) - data(e, di) * data(tk, dj) - data(tk, di) * data(e, dj); } } } return imp_grad; } void LargeMargin::computeImpGrad(const MatrixXd &imp_grad, MatrixXd &next_imp_grad, const std::vector<LargeMargin::impSet> &missing, const std::vector<LargeMargin::impSet> &extra) { next_imp_grad = imp_grad; #ifdef _OPENMP #pragma omp parallel for #endif for (int di = 0; di < d_in; di++) { for (int dj = 0; dj < d_in; dj++) { /* adding */ for (impSet s : missing) { int e = s.example; int ik = s.impostor; int tk = s.target; /* impostors */ next_imp_grad(di, dj) += - data(e, di) * data(e, dj) - data(ik, di) * data(ik, dj) + data(e, di) * data(ik, dj) + data(ik, di) * data(e, dj); /* target */ next_imp_grad(di, dj) += + data(e, di) * data(e, dj) + data(tk, di) * data(tk, dj) - data(e, di) * data(tk, dj) - data(tk, di) * data(e, dj); } /* subtracting */ for (impSet s : extra) { int e = s.example; int ik = s.impostor; int tk = s.target; /* impostors */ next_imp_grad(di, dj) -= - data(e, di) * data(e, dj) - data(ik, di) * data(ik, dj) + data(e, di) * data(ik, dj) + data(ik, di) * data(e, dj); /* target */ next_imp_grad(di, dj) -= + data(e, di) * data(e, dj) + data(tk, di) * data(tk, dj) - data(e, di) * data(tk, dj) - data(tk, di) * data(e, dj); } } } } void LargeMargin::updateTransform(const MatrixXd &target_grad, const MatrixXd &imp_grad, MatrixXd &gradient, MatrixXd &grad_prod, MatrixXd &next_L) { gradient.noalias() = target_grad + imp_grad; grad_prod.noalias() = L * gradient; grad_prod *= 2 * current_learn_rate; next_L.noalias() = L - grad_prod; } double LargeMargin::gradLoss(const MatrixXd &grad, const MatrixXd &L_trans) { MatrixXd M = L_trans.transpose().lazyProduct(L_trans); double loss = 0.0f; for (int i = 0; i < d_in; i++) for (int j = 0; j < d_in; j++) loss += M(i, j) * grad(i, j); return loss; }
31.182028
114
0.487623
[ "vector", "transform" ]
03c57de17e5d2135023456cbb3f09411d3286b6c
1,386
hpp
C++
include/lug/Graphics/Vulkan/API/Builder/DeviceMemory.hpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
275
2016-10-08T15:33:17.000Z
2022-03-30T06:11:56.000Z
include/lug/Graphics/Vulkan/API/Builder/DeviceMemory.hpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
24
2016-09-29T20:51:20.000Z
2018-05-09T21:41:36.000Z
include/lug/Graphics/Vulkan/API/Builder/DeviceMemory.hpp
Lugdunum3D/Lugdunum3D
b6d6907d034fdba1ffc278b96598eba1d860f0d4
[ "MIT" ]
37
2017-02-25T05:03:48.000Z
2021-05-10T19:06:29.000Z
#pragma once #include <memory> #include <vector> #include <lug/Graphics/Vulkan/API/DeviceMemory.hpp> namespace lug { namespace Graphics { namespace Vulkan { namespace API { class Buffer; class Device; class Image; namespace Builder { class DeviceMemory { public: DeviceMemory(const API::Device& deviceMemory); DeviceMemory(const DeviceMemory&) = delete; DeviceMemory(DeviceMemory&&) = delete; DeviceMemory& operator=(const DeviceMemory&) = delete; DeviceMemory& operator=(DeviceMemory&&) = delete; ~DeviceMemory() = default; // Setters void setMemoryFlags(VkMemoryPropertyFlags flags); bool addBuffer(API::Buffer& buffer); bool addImage(API::Image& image); // Build methods bool build(API::DeviceMemory& instance, VkResult* returnResult = nullptr); std::unique_ptr<API::DeviceMemory> build(VkResult* returnResult = nullptr); public: static uint32_t findMemoryType(const API::Device& device, uint32_t memoryTypeBits, VkMemoryPropertyFlags requiredFlags); private: const API::Device& _device; VkMemoryPropertyFlags _memoryFlags{VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT}; uint32_t _memoryTypeBits{0xFFFFFFFF}; std::vector<API::Buffer*> _buffers; std::vector<API::Image*> _images; }; #include <lug/Graphics/Vulkan/API/Builder/DeviceMemory.inl> } // Builder } // API } // Vulkan } // Graphics } // lug
22.721311
124
0.727273
[ "vector" ]
03ca05c54efc11455eb49dee62709a09fb6cc6c8
9,859
cpp
C++
source/utopian/core/ModelLoader.cpp
simplerr/UtopianEngine
6fbafed1c379993c23d870ba252efa87514d43bc
[ "MIT" ]
62
2020-11-06T17:29:24.000Z
2022-03-21T19:21:16.000Z
source/utopian/core/ModelLoader.cpp
simplerr/UtopianEngine
6fbafed1c379993c23d870ba252efa87514d43bc
[ "MIT" ]
134
2017-02-25T20:47:43.000Z
2022-03-14T06:54:58.000Z
source/utopian/core/ModelLoader.cpp
simplerr/UtopianEngine
6fbafed1c379993c23d870ba252efa87514d43bc
[ "MIT" ]
6
2021-02-19T07:20:19.000Z
2021-12-27T09:07:27.000Z
#include <vector> #include <vulkan/vulkan_core.h> #include "core/renderer/Primitive.h" #include "core/Log.h" #include "core/AssimpLoader.h" #include "core/glTFLoader.h" #include "core/ModelLoader.h" #include "core/renderer/Model.h" #include "vulkan/handles/Device.h" #include "vulkan/handles/DescriptorSetLayout.h" #include "vulkan/handles/DescriptorSet.h" #include "vulkan/TextureLoader.h" #include "utility/Utility.h" namespace Utopian { using Vk::Vertex; bool ModelLoader::mFlipWindingOrder = false; ModelLoader::ModelLoader(Vk::Device* device) : mDevice(device) { mAssimpLoader = std::make_shared<AssimpLoader>(device); mglTFLoader = std::make_shared<glTFLoader>(device); mMeshTexturesDescriptorSetLayout = std::make_shared<Vk::DescriptorSetLayout>(device); mMeshTexturesDescriptorSetLayout->AddCombinedImageSampler(0, VK_SHADER_STAGE_ALL, 1); // diffuseSampler mMeshTexturesDescriptorSetLayout->AddCombinedImageSampler(1, VK_SHADER_STAGE_ALL, 1); // normalSampler mMeshTexturesDescriptorSetLayout->AddCombinedImageSampler(2, VK_SHADER_STAGE_ALL, 1); // specularSampler mMeshTexturesDescriptorSetLayout->AddCombinedImageSampler(3, VK_SHADER_STAGE_ALL, 1); // metallicRoughnessSampler mMeshTexturesDescriptorSetLayout->AddCombinedImageSampler(4, VK_SHADER_STAGE_ALL, 1); // occlusionSampler mMeshTexturesDescriptorSetLayout->AddUniformBuffer(20, VK_SHADER_STAGE_ALL, 1); // material properties mMeshTexturesDescriptorSetLayout->Create(); mMeshTexturesDescriptorPool = std::make_shared<Vk::DescriptorPool>(device); mMeshTexturesDescriptorPool->AddDescriptor(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 512); mMeshTexturesDescriptorPool->AddDescriptor(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 512); mMeshTexturesDescriptorPool->Create(); } ModelLoader::~ModelLoader() { } ModelLoader& gModelLoader() { return ModelLoader::Instance(); } Vk::DescriptorSetLayout* ModelLoader::GetMeshTextureDescriptorSetLayout() { return mMeshTexturesDescriptorSetLayout.get(); } Vk::DescriptorPool* ModelLoader::GetMeshTextureDescriptorPool() { return mMeshTexturesDescriptorPool.get(); } SharedPtr<Model> ModelLoader::LoadModel(std::string filename) { // Check if the model already is loaded // if (mModelMap.find(filename) != mModelMap.end()) // return mModelMap[filename]; SharedPtr<Model> model = nullptr; std::string extension = GetFileExtension(filename); if (extension == ".gltf") model = mglTFLoader->LoadModel(filename, mDevice); else model = mAssimpLoader->LoadModel(filename); if (model == nullptr) { if (mPlaceholderModel == nullptr) mPlaceholderModel = LoadModel(PLACEHOLDER_MODEL_PATH); model = mPlaceholderModel; } else mModelMap[filename] = model; return model; } SharedPtr<Model> ModelLoader::LoadGrid(float cellSize, int numCells) { Primitive primitive; for (int x = 0; x < numCells; x++) { for (int z = 0; z < numCells; z++) { Vk::Vertex vertex; const float originOffset = (cellSize * numCells) / 2.0f - cellSize / 2; vertex.pos = glm::vec3(x * cellSize - originOffset, 0.0f, z * cellSize - originOffset); vertex.normal = glm::vec3(0.0f, 1.0f, 0.0f); vertex.tangent = glm::vec4(1.0f, 0.0f, 0.0f, 1.0f); vertex.uv = glm::vec2((float)x / (numCells - 1), (float)z / (numCells - 1)); primitive.AddVertex(vertex); } } for (int x = 0; x < numCells - 1; x++) { for (int z = 0; z < numCells - 1; z++) { primitive.AddTriangle(x * numCells + z, x * numCells + z + 1, (x + 1) * numCells + z); primitive.AddTriangle((x + 1) * numCells + z, x * numCells + z + 1, (x + 1) * numCells + (z + 1)); } } primitive.BuildBuffers(mDevice); SharedPtr<Model> model = std::make_shared<Model>(); Primitive* prim = model->AddPrimitive(primitive); Material* mat = model->AddMaterial(GetDefaultMaterial()); Node* node = model->CreateNode(); node->mesh = Mesh(prim, mat); model->AddRootNode(node); return model; } SharedPtr<Model> ModelLoader::LoadBox() { Primitive primitive; // Front primitive.AddVertex(Vertex(glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(0.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(1.0f, 0.0f))); primitive.AddVertex(Vertex(glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec2(0.0f, 0.0f))); // Back primitive.AddVertex(Vertex(glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec2(0.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, -0.5f, -0.5f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec2(1.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec2(1.0f, 0.0f))); primitive.AddVertex(Vertex(glm::vec3(-0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 0.0f, -1.0f), glm::vec2(0.0f, 0.0f))); // Top primitive.AddVertex(Vertex(glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec2(0.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, -0.5f, -0.5f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec2(1.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec2(1.0f, 0.0f))); primitive.AddVertex(Vertex(glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(0.0f, -1.0f, 0.0f), glm::vec2(0.0f, 0.0f))); // Bottom primitive.AddVertex(Vertex(glm::vec3(-0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, 0.5f, -0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(1.0f, 0.0f))); primitive.AddVertex(Vertex(glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec2(0.0f, 0.0f))); // Left primitive.AddVertex(Vertex(glm::vec3(-0.5f, -0.5f, -0.5f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(-0.5f, 0.5f, -0.5f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(-0.5f, 0.5f, 0.5f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f))); primitive.AddVertex(Vertex(glm::vec3(-0.5f, -0.5f, 0.5f), glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f))); // Right primitive.AddVertex(Vertex(glm::vec3(0.5f, -0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, 0.5f, -0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 1.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, 0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f))); primitive.AddVertex(Vertex(glm::vec3(0.5f, -0.5f, 0.5f), glm::vec3(1.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f))); // Front primitive.AddTriangle(2, 0, 1); primitive.AddTriangle(0, 2, 3); // Back primitive.AddTriangle(4, 6, 5); primitive.AddTriangle(6, 4, 7); // Top primitive.AddTriangle(10, 8, 9); primitive.AddTriangle(8, 10, 11); // Bottom primitive.AddTriangle(12, 14, 13); primitive.AddTriangle(14, 12, 15); // Left primitive.AddTriangle(16, 18, 17); primitive.AddTriangle(18, 16, 19); // Right primitive.AddTriangle(22, 20, 21); primitive.AddTriangle(20, 22, 23); primitive.BuildBuffers(mDevice); SharedPtr<Model> model = std::make_shared<Model>(); Primitive* prim = model->AddPrimitive(primitive); Material* material = model->AddMaterial(GetDefaultMaterial()); Node* node = model->CreateNode(); node->mesh = Mesh(prim, material); model->AddRootNode(node); model->Init(); return model; } SharedPtr<Model> ModelLoader::LoadQuad() { Primitive primitive; Vk::Vertex vertex = {}; vertex.pos = glm::vec3(-0.5f, -0.5f, 0.5f); vertex.normal = glm::vec3(0.0f, 0.0f, 1.0f); vertex.uv = glm::vec2(0.0f, 1.0f); primitive.AddVertex(vertex); vertex.pos = glm::vec3(0.5f, -0.5f, 0.5f); vertex.uv = glm::vec2(1.0f, 1.0f); primitive.AddVertex(vertex); vertex.pos = glm::vec3(0.5f, 0.5f, 0.5f); vertex.uv = glm::vec2(1.0f, 0.0f); primitive.AddVertex(vertex); vertex.pos = glm::vec3(-0.5f, 0.5f, 0.5f); vertex.uv = glm::vec2(0.0f, 0.0f); primitive.AddVertex(vertex); primitive.AddTriangle(2, 0, 1); primitive.AddTriangle(0, 2, 3); primitive.BuildBuffers(mDevice); SharedPtr<Model> model = std::make_shared<Model>(); Primitive* prim = model->AddPrimitive(primitive); Material* mat = model->AddMaterial(GetDefaultMaterial()); Node* node = model->CreateNode(); node->mesh = Mesh(prim, mat); model->AddRootNode(node); return model; } Material ModelLoader::GetDefaultMaterial() { return mglTFLoader->GetDefaultMaterial(); } void ModelLoader::SetInverseTranslation(bool inverse) { mglTFLoader->SetInverseTranslation(inverse); } void ModelLoader::SetFlipWindingOrder(bool flipWindingOrder) { mFlipWindingOrder = flipWindingOrder; } bool ModelLoader::GetFlipWindingOrder() { return mFlipWindingOrder; } }
36.650558
119
0.622173
[ "mesh", "vector", "model" ]
03d3b48507e06a4f928559e193865a3f1fe931df
2,642
cpp
C++
2020/days/day1.cpp
Gnarwhal/AdventOfCode
c6ef3db530e8a6eb599d81b3c26132d6dac345f7
[ "MIT" ]
null
null
null
2020/days/day1.cpp
Gnarwhal/AdventOfCode
c6ef3db530e8a6eb599d81b3c26132d6dac345f7
[ "MIT" ]
null
null
null
2020/days/day1.cpp
Gnarwhal/AdventOfCode
c6ef3db530e8a6eb599d81b3c26132d6dac345f7
[ "MIT" ]
null
null
null
/******************************************************************************* * * Copyright (c) 2020 Gnarwhal * * ----------------------------------------------------------------------------- * * 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 <vector> #include <algorithm> #include <string> #include <iostream> #include <fstream> #include "../misc/types.hpp" #include "../misc/print.hpp" // Find 2 numbers that sum to 2020 auto find_2020_x2(const std::vector<i32> & list) -> void { auto begin = 0; auto end = list.size() - 1; auto sum = 0; while ((sum = list[begin] + list[end]) != 2020) { if (sum < 2020) { ++begin; } else { --end; } } print((list[begin] * list[end])); } // Find 3 numbers that sum to 2020 auto find_2020_x3(const std::vector<i32> & list) -> void { for (auto n0 = 0; n0 < list.size() - 2; ++n0) { for (auto n1 = 1; n1 < list.size() - 1; ++n1) { auto low = n0 + 1; auto high = n1; while (low < high) { auto n2 = (low + high) / 2; auto sum = 0; if ((sum = list[n0] + list[n1] + list[n2]) == 2020) { print((list[n0] * list[n1] * list[n2])); return; } else if (sum < 2020) { low = n2 + 1; } else { high = n2; } } } } } auto day1() -> void { auto list = std::vector<i32>(); { auto line = std::string(); auto file = std::ifstream("inputs/day1.input"); while (getline(file, line)) { list.push_back(std::stoi(line)); } } std::sort(list.begin(), list.end()); find_2020_x2(list); find_2020_x3(list); }
30.367816
81
0.590462
[ "vector" ]
03d56930f22ab6661c4f58c805f88bb1271649d4
4,663
cpp
C++
ThirdParty/poco/Util/testsuite/src/ValidatorTest.cpp
gregmedlock/roadrunnerwork
11f18f78ef3e381bc59c546a8d5e3ed46d8ab596
[ "Apache-2.0" ]
1
2021-11-29T08:30:19.000Z
2021-11-29T08:30:19.000Z
ThirdParty/poco/Util/testsuite/src/ValidatorTest.cpp
gregmedlock/roadrunnerwork
11f18f78ef3e381bc59c546a8d5e3ed46d8ab596
[ "Apache-2.0" ]
null
null
null
ThirdParty/poco/Util/testsuite/src/ValidatorTest.cpp
gregmedlock/roadrunnerwork
11f18f78ef3e381bc59c546a8d5e3ed46d8ab596
[ "Apache-2.0" ]
6
2016-06-04T08:15:01.000Z
2022-01-17T07:54:46.000Z
// // ValidatorTest.cpp // // $Id: //poco/1.4/Util/testsuite/src/ValidatorTest.cpp#1 $ // // Copyright (c) 2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #include "ValidatorTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/Util/RegExpValidator.h" #include "Poco/Util/IntValidator.h" #include "Poco/Util/Option.h" #include "Poco/Util/OptionException.h" #include "Poco/AutoPtr.h" using Poco::Util::Validator; using Poco::Util::RegExpValidator; using Poco::Util::IntValidator; using Poco::Util::Option; using Poco::Util::InvalidArgumentException; using Poco::AutoPtr; ValidatorTest::ValidatorTest(const std::string& name): CppUnit::TestCase(name) { } ValidatorTest::~ValidatorTest() { } void ValidatorTest::testRegExpValidator() { Option option("option", "o"); AutoPtr<Validator> pVal(new RegExpValidator("[0-9]+")); pVal->validate(option, "0"); pVal->validate(option, "12345"); try { pVal->validate(option, " 234"); fail("does not match - must throw"); } catch (InvalidArgumentException& exc) { std::string s(exc.message()); assert (s == "argument for option does not match regular expression [0-9]+"); } try { pVal->validate(option, "234asdf"); fail("does not match - must throw"); } catch (InvalidArgumentException& exc) { std::string s(exc.message()); assert (s == "argument for option does not match regular expression [0-9]+"); } try { pVal->validate(option, "abc"); fail("does not match - must throw"); } catch (InvalidArgumentException& exc) { std::string s(exc.message()); assert (s == "argument for option does not match regular expression [0-9]+"); } try { pVal->validate(option, ""); fail("does not match - must throw"); } catch (InvalidArgumentException& exc) { std::string s(exc.message()); assert (s == "argument for option does not match regular expression [0-9]+"); } } void ValidatorTest::testIntValidator() { Option option("option", "o"); AutoPtr<Validator> pVal(new IntValidator(0, 100)); pVal->validate(option, "0"); pVal->validate(option, "100"); pVal->validate(option, "55"); try { pVal->validate(option, "-1"); fail("out of range - must throw"); } catch (InvalidArgumentException& exc) { std::string s(exc.message()); assert (s == "argument for option must be in range 0 to 100"); } try { pVal->validate(option, "101"); fail("out of range - must throw"); } catch (InvalidArgumentException& exc) { std::string s(exc.message()); assert (s == "argument for option must be in range 0 to 100"); } try { pVal->validate(option, "asdf"); fail("not a number - must throw"); } catch (InvalidArgumentException& exc) { std::string s(exc.message()); assert (s == "argument for option must be an integer"); } } void ValidatorTest::setUp() { } void ValidatorTest::tearDown() { } CppUnit::Test* ValidatorTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ValidatorTest"); CppUnit_addTest(pSuite, ValidatorTest, testRegExpValidator); CppUnit_addTest(pSuite, ValidatorTest, testIntValidator); return pSuite; }
26.196629
80
0.682179
[ "object" ]
03d99787590f5c0c0ad32bef2f906b2fe45089a3
1,951
cpp
C++
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/ContainerActionButtonHandler.cpp
psy-repos-c/o3de
42d917e4726b1cae8c39c10834b0e621c9e8300d
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/ContainerActionButtonHandler.cpp
psy-repos-c/o3de
42d917e4726b1cae8c39c10834b0e621c9e8300d
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzToolsFramework/AzToolsFramework/UI/DocumentPropertyEditor/ContainerActionButtonHandler.cpp
psy-repos-c/o3de
42d917e4726b1cae8c39c10834b0e621c9e8300d
[ "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 <AzToolsFramework/UI/DocumentPropertyEditor/ContainerActionButtonHandler.h> namespace AzToolsFramework { ContainerActionButtonHandler::ContainerActionButtonHandler() { setAutoRaise(true); connect( this, &QToolButton::clicked, this, [this]() { using AZ::DocumentPropertyEditor::Nodes::ContainerActionButton; ContainerActionButton::OnActivate.InvokeOnDomNode(m_node); }); } void ContainerActionButtonHandler::SetValueFromDom(const AZ::Dom::Value& node) { static QIcon s_iconAdd(QStringLiteral(":/stylesheet/img/UI20/add-16.svg")); static QIcon s_iconRemove(QStringLiteral(":/stylesheet/img/UI20/delete-16.svg")); static QIcon s_iconClear(QStringLiteral(":/stylesheet/img/UI20/delete-16.svg")); using AZ::DocumentPropertyEditor::Nodes::ContainerAction; using AZ::DocumentPropertyEditor::Nodes::ContainerActionButton; // Cache the node so we can query OnActivate on it when we're pressed. m_node = node; ContainerAction action = ContainerActionButton::Action.ExtractFromDomNode(node).value_or(ContainerAction::AddElement); switch (action) { case ContainerAction::AddElement: setIcon(s_iconAdd); setToolTip("Add new child element"); break; case ContainerAction::RemoveElement: setIcon(s_iconRemove); setToolTip(tr("Remove this element")); break; case ContainerAction::Clear: setIcon(s_iconClear); setToolTip(tr("Remove all elements")); break; } } } // namespace AzToolsFramework
34.839286
126
0.655049
[ "3d" ]
03dd1d0303cf20ccf5bc66ae713458698fadd3be
876
cpp
C++
src/DataMap.cpp
stringbasic/datamerger
8c5977ffea97018d7bce4c043df28f3b3356d48d
[ "MIT" ]
null
null
null
src/DataMap.cpp
stringbasic/datamerger
8c5977ffea97018d7bce4c043df28f3b3356d48d
[ "MIT" ]
null
null
null
src/DataMap.cpp
stringbasic/datamerger
8c5977ffea97018d7bce4c043df28f3b3356d48d
[ "MIT" ]
null
null
null
/** * * DataMap.cpp * */ #include "DataMap.h" using namespace datamerger; using namespace std; DataMap::DataMap(string columnName, int columnIndex) : columnName(move(columnName)), columnIndex(columnIndex), maxSize(0) { } const string& DataMap::getColumnName() { return this->columnName; } const int& DataMap::getColumnIndex() const { return this->columnIndex; } void DataMap::addDataRow(const vector<string>& row) { vector<string> newRow(row); newRow.erase(newRow.begin() + this->columnIndex); if (newRow.size() > this->maxSize) this->maxSize = newRow.size(); this->data.insert( pair<string, vector<string>>(row[this->columnIndex], newRow)); } vector<string> DataMap::getMappedValue(const string& value) { auto index = this->data.find(value); if (index != this->data.end()) { return index->second; } return {this->maxSize, ""}; }
21.9
74
0.684932
[ "vector" ]
03e1d83997ba03f2b558e1f1afaac6657c16e683
2,263
cpp
C++
examples/Cuda/Experiment/ExtractVoxelsNearSurfaceCuda.cpp
devshank3/Open3D
91611eb562680a41be8a52497bb45d278f2c9377
[ "MIT" ]
113
2018-11-12T03:32:52.000Z
2022-03-29T13:58:54.000Z
examples/Cuda/Experiment/ExtractVoxelsNearSurfaceCuda.cpp
llp45135/Open3D
ff7003d542c4fcf88a2d9e7fe08508b3e52dc702
[ "MIT" ]
3
2018-10-19T12:09:57.000Z
2020-04-22T11:55:54.000Z
examples/Cuda/Experiment/ExtractVoxelsNearSurfaceCuda.cpp
llp45135/Open3D
ff7003d542c4fcf88a2d9e7fe08508b3e52dc702
[ "MIT" ]
27
2018-10-16T20:01:18.000Z
2021-07-26T08:02:20.000Z
// // Created by wei on 4/4/19. // #include <Open3D/Open3D.h> #include <Cuda/Open3DCuda.h> #include <Cuda/Experiment/ScalableTSDFVolumeProcessorCuda.h> #include "../ReconstructionSystem/DatasetConfig.h" using namespace open3d; using namespace open3d::registration; using namespace open3d::geometry; using namespace open3d::io; using namespace open3d::utility; void ReadAndComputeGradient(int fragment_id, DatasetConfig &config) { PoseGraph pose_graph; ReadPoseGraph(config.GetPoseGraphFileForFragment(fragment_id, true), pose_graph); float voxel_length = config.tsdf_cubic_size_ / 512.0; cuda::TransformCuda trans = cuda::TransformCuda::Identity(); cuda::ScalableTSDFVolumeCuda tsdf_volume( 8, voxel_length, (float) config.tsdf_truncation_ * 4, trans); Timer timer; timer.Start(); std::string filename = config.GetBinFileForFragment(fragment_id); io::ReadScalableTSDFVolumeFromBIN("target.bin", tsdf_volume); timer.Stop(); utility::LogInfo("Read takes {} ms\n", timer.GetDuration()); utility::SetVerbosityLevel(utility::VerbosityLevel::Debug); tsdf_volume.GetAllSubvolumes(); cuda::ScalableMeshVolumeCuda mesher( cuda::VertexWithNormalAndColor, 8, tsdf_volume.active_subvolume_entry_array_.size()); mesher.MarchingCubes(tsdf_volume); auto mesh = mesher.mesh().Download(); visualization::DrawGeometries({mesh}); cuda::ScalableTSDFVolumeProcessorCuda gradient_volume( 8, tsdf_volume.active_subvolume_entry_array_.size()); gradient_volume.ComputeGradient(tsdf_volume); cuda::PointCloudCuda pcl = gradient_volume.ExtractVoxelsNearSurface( tsdf_volume, 0.5f); auto pcl_cpu = pcl.Download(); visualization::DrawGeometries({pcl_cpu}); } int main(int argc, char **argv) { DatasetConfig config; std::string config_path = argc > 1 ? argv[1] : kDefaultDatasetConfigDir + "/stanford/lounge.json"; bool is_success = io::ReadIJsonConvertible(config_path, config); if (!is_success) return 1; config.GetFragmentFiles(); for (int i = 0; i < config.fragment_files_.size(); ++i) { utility::LogInfo("{}\n", i); ReadAndComputeGradient(i, config); } }
33.279412
81
0.708794
[ "mesh", "geometry" ]
03e31c6f24d6a629b92efc5ce28d6c5591d3b14a
2,961
cc
C++
fully_dynamic_submodular_maximization/random_subset_algorithm.cc
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
23,901
2018-10-04T19:48:53.000Z
2022-03-31T21:27:42.000Z
fully_dynamic_submodular_maximization/random_subset_algorithm.cc
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
891
2018-11-10T06:16:13.000Z
2022-03-31T10:42:34.000Z
fully_dynamic_submodular_maximization/random_subset_algorithm.cc
deepneuralmachine/google-research
d2ce2cf0f5c004f8d78bfeddf6e88e88f4840231
[ "Apache-2.0" ]
6,047
2018-10-12T06:31:02.000Z
2022-03-31T13:59:28.000Z
// Copyright 2020 The Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "random_subset_algorithm.h" #include "utilities.h" using std::vector; void RandomSubsetAlgorithm::Initialization(const SubmodularFunction& sub_func_f, int cardinality_k) { cardinality_k_ = cardinality_k; sub_func_f_ = sub_func_f.Clone(); universe_elements_.clear(); solution_.clear(); } void RandomSubsetAlgorithm::Insert(int element) { if (static_cast<int>(solution_.size()) < cardinality_k_) { solution_.push_back(element); } else { universe_elements_.push_back(element); const double probability_in_random_solution = static_cast<double>(cardinality_k_) / (cardinality_k_ + static_cast<int>(universe_elements_.size())); const double random_value = static_cast<double>(RandomHandler::generator_()) / RandomHandler::generator_.max(); if (random_value < probability_in_random_solution) { // Swap e with a random element from the solution. std::swap(universe_elements_.back(), solution_[RandomHandler::generator_() % cardinality_k_]); } } } void RandomSubsetAlgorithm::Erase(int element) { auto it_element = find(solution_.begin(), solution_.end(), element); if (it_element != solution_.end()) { solution_.erase(it_element); // Find a replacement in other_elements. if (!universe_elements_.empty()) { size_t random_index = RandomHandler::generator_() % universe_elements_.size(); solution_.push_back(universe_elements_[random_index]); universe_elements_.erase(universe_elements_.begin() + random_index); } return; } it_element = find(universe_elements_.begin(), universe_elements_.end(), element); if (it_element != universe_elements_.end()) { universe_elements_.erase(it_element); } } double RandomSubsetAlgorithm::GetSolutionValue() { sub_func_f_->Reset(); double obj_val = 0.0; for (int element_in_solution : solution_) { obj_val += sub_func_f_->AddAndIncreaseOracleCall(element_in_solution, -1); } SubmodularFunction::oracle_calls_ -= 2 * static_cast<int>(solution_.size()) - 1; // Should be just one call in our model. return obj_val; } vector<int> RandomSubsetAlgorithm::GetSolutionVector() { return solution_; } std::string RandomSubsetAlgorithm::GetAlgorithmName() const { return "totally random algorithm"; }
34.430233
80
0.712259
[ "vector", "model" ]
03e3ce280379bcbe38b42b5564bfda20cf2e2ef7
14,702
cpp
C++
SRC/element/joint/MP_Joint2D.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
SRC/element/joint/MP_Joint2D.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
SRC/element/joint/MP_Joint2D.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.7 $ // $Date: 2010-04-23 22:53:56 $ // $Source: /usr/local/cvs/OpenSees/SRC/element/joint/MP_Joint2D.cpp,v $ // Written: Arash Altoontash, Gregory Deierlein // Created: 08/01 // Revision: Arash // Purpose: This file contains the implementation of class MP_TimeVary. #include <MP_Joint2D.h> #include <stdlib.h> #include <math.h> #include <Matrix.h> #include <ID.h> #include <Channel.h> #include <FEM_ObjectBroker.h> // main degree of freedom for rotation // constructor for FEM_ObjectBroker MP_Joint2D::MP_Joint2D() :MP_Constraint(CNSTRNT_TAG_MP_Joint2D ),thisDomain(0), nodeRetained(0),nodeConstrained(0), MainDOF(0), AuxDOF(0), FixedEnd(0), constraint(0), constrDOF(0),retainDOF(0),dbTag1(0), dbTag2(0), dbTag3(0), RetainedNode(0), ConstrainedNode(0), LargeDisplacement(0), Length0(0.0) { } // general constructor for ModelBuilder MP_Joint2D::MP_Joint2D(Domain *theDomain, int nodeRetain, int nodeConstr, int Maindof, int fixedend, int LrgDsp ) :MP_Constraint(CNSTRNT_TAG_MP_Joint2D ), thisDomain(theDomain), nodeRetained(nodeRetain), nodeConstrained(nodeConstr), MainDOF(Maindof), AuxDOF(0), FixedEnd(fixedend), constraint(0), constrDOF(0), retainDOF(0), dbTag1(0), dbTag2(0), dbTag3(0), RetainedNode(0), ConstrainedNode(0), LargeDisplacement( LrgDsp ), Length0(0.0) { if( thisDomain == NULL ) { opserr << "WARNING MP_Joint2D(): Specified domain does not exist"; opserr << "Domain = 0\n"; return; } // get node pointers of constrainted and retained nodes ConstrainedNode = theDomain->getNode(nodeConstrained); if (ConstrainedNode == NULL) { opserr << "MP_Joint2D::MP_Joint2D: nodeConstrained: "; opserr << nodeConstrained << "does not exist in model\n"; exit(0); } RetainedNode = theDomain->getNode(nodeRetained); if (RetainedNode == NULL) { opserr << "MP_Joint2D::MP_Joint2D: nodeRetained: "; opserr << nodeRetained << "does not exist in model\n"; exit(0); } // check for proper degrees of freedom int RnumDOF = RetainedNode->getNumberDOF(); int CnumDOF = ConstrainedNode->getNumberDOF(); if (RnumDOF != 4 || CnumDOF != 3 ){ opserr << "MP_Joint2D::MP_Joint2D - mismatch in numDOF\n DOF not supported by this type of constraint"; return; } // check the main degree of freedom. Assign auxiliary DOF if ( MainDOF!= 2 && MainDOF!=3 ) { opserr << "MP_Joint2D::MP_Joint2D - Wrong main degree of freedom" ; return; } if ( MainDOF == 2 ) AuxDOF = 3; if ( MainDOF == 3 ) AuxDOF = 2; // check the fixed end flag if ( FixedEnd!= 0 && FixedEnd!=1 ) { opserr << "MP_Joint2D::MP_Joint2D - Wrong fixed end flag"; return; } // check for proper dimensions of coordinate space const Vector &crdR = RetainedNode->getCrds(); int dimR = crdR.Size(); const Vector &crdC = ConstrainedNode->getCrds(); int dimC = crdC.Size(); if (dimR != 2 || dimC != 2 ){ opserr << "MP_Joint2D::MP_Joint2D - mismatch in dimnesion\n dimension not supported by this type of constraint"; return; } // calculate the initial length of the rigid link double deltaX = crdC(0) - crdR(0); double deltaY = crdC(1) - crdR(1); Length0 = sqrt( deltaX*deltaX + deltaY*deltaY ); if ( Length0 <= 1.0e-12 ) { opserr << "MP_Joint2D::MP_Joint2D - The constraint length is zero\n"; } // allocate and set up the constranted and retained id's // allocate and set up the constraint matrix if ( FixedEnd == 0 ) { // the end is released constrDOF = new ID(CnumDOF-1); retainDOF = new ID(RnumDOF-1); (*constrDOF)(0) = 0; (*constrDOF)(1) = 1; (*retainDOF)(0) = 0; (*retainDOF)(1) = 1; (*retainDOF)(2) = MainDOF; constraint = new Matrix( CnumDOF-1 , RnumDOF-1 ); (*constraint) (0,0) = 1.0 ; (*constraint) (0,2) = -deltaY ; (*constraint) (1,1) = 1.0 ; (*constraint) (1,2) = deltaX ; } else { // the end is fixed constrDOF = new ID(CnumDOF); retainDOF = new ID(RnumDOF); (*constrDOF)(0) = 0; (*constrDOF)(1) = 1; (*constrDOF)(2) = 2; (*retainDOF)(0) = 0; (*retainDOF)(1) = 1; (*retainDOF)(2) = 2; (*retainDOF)(3) = 3; constraint = new Matrix( CnumDOF , RnumDOF ); (*constraint) (0,0) = 1.0 ; (*constraint) (0,MainDOF) = -deltaY ; (*constraint) (1,1) = 1.0 ; (*constraint) (1,MainDOF) = deltaX ; (*constraint) (2,AuxDOF) = 1.0 ; } if (constrDOF == NULL || retainDOF == NULL ) { opserr << "MP_Joint2D::MP_Joint2D - ran out of memory \ncan not generate ID for nodes\n"; exit(-1); } if (constraint == NULL ) { opserr << "MP_Joint2D::MP_Joint2D - ran out of memory \ncan not generate the constraint matrix"; exit(-1); } } MP_Joint2D::~MP_Joint2D() { // invoke the destructor on the matrix and the two ID objects if (constraint != NULL) delete constraint; if (constrDOF != NULL) delete constrDOF; if (retainDOF != NULL) delete retainDOF; } int MP_Joint2D::getNodeRetained(void) const { // return id of retained node return nodeRetained; } int MP_Joint2D::getNodeConstrained(void) const { // return id of constrained node return nodeConstrained; } const ID & MP_Joint2D::getConstrainedDOFs(void) const { if (constrDOF == NULL) { opserr << "MP_Joint2D::getConstrainedDOF - no ID was set, "; opserr << "was recvSelf() ever called? or subclass incorrect?\n"; exit(-1); } // return the ID corresponding to constrained DOF of Ccr return (*constrDOF); } const ID & MP_Joint2D::getRetainedDOFs(void) const { if (retainDOF == NULL) { opserr << "MP_Joint2D::getRetainedDOFs - no ID was set\n "; opserr << "was recvSelf() ever called? or subclass incorrect?\n"; exit(-1); } // return the ID corresponding to retained DOF of Ccr return (*retainDOF); } int MP_Joint2D::applyConstraint(double timeStamp) { if ( LargeDisplacement != 0 ) { // calculate the constraint at this moment // get the coordinates of the two nodes - check dimensions are the same FOR THE MOMENT const Vector &crdR = RetainedNode->getCrds(); const Vector &crdC = ConstrainedNode->getCrds(); // get committed displacements of nodes to get updated coordinates const Vector &dispR = RetainedNode->getDisp(); const Vector &dispC = ConstrainedNode->getDisp(); double deltaX = dispC(0) + crdC(0) - dispR(0) - crdR(0); double deltaY = dispC(1) + crdC(1) - dispR(1) - crdR(1); constraint->Zero(); if ( FixedEnd == 0 ) { // the end is released (*constraint) (0,0) = 1.0 ; (*constraint) (0,2) = -deltaY ; (*constraint) (1,1) = 1.0 ; (*constraint) (1,2) = deltaX ; } else { // the end is fixed (*constraint) (0,0) = 1.0 ; (*constraint) (0,MainDOF) = -deltaY ; (*constraint) (1,1) = 1.0 ; (*constraint) (1,MainDOF) = deltaX ; (*constraint) (2,AuxDOF) = 1.0 ; } } return 0; } bool MP_Joint2D::isTimeVarying(void) const { if ( LargeDisplacement != 0 ) return true; return false; } int MP_Joint2D::sendSelf(int commitTag, Channel &theChannel) { Vector data(15); int dataTag = this->getDbTag(); data(0) = this->getTag(); data(1) = nodeRetained; data(2) = nodeConstrained; data(3) = MainDOF; data(4) = AuxDOF; data(5) = FixedEnd; if (constrDOF == 0) data(6) = 0; else data(6) = constrDOF->Size(); if (retainDOF == 0) data(7) = 0; else data(7) = retainDOF->Size(); if (constraint == 0) data(8) = 0; else data(8) = constraint->noRows(); if (constraint == 0) data(9) = 0; else data(9) = constraint->noCols(); // need two database tags for ID objects if (constrDOF != 0 && dbTag1 == 0) dbTag1 = theChannel.getDbTag(); if (retainDOF != 0 && dbTag2 == 0) dbTag2 = theChannel.getDbTag(); if (constraint != 0 && dbTag3 == 0) dbTag3 = theChannel.getDbTag(); data(10) = dbTag1; data(11) = dbTag2; data(12) = dbTag3; data(13) = LargeDisplacement; data(14) = Length0; // now send the data vector int result = theChannel.sendVector(dataTag, commitTag, data); if (result < 0) { opserr << "WARNING MP_Joint2D::sendSelf - error sending ID data\n"; return result; } // send constrDOF if (constrDOF != 0 && constrDOF->Size() != 0) { int result = theChannel.sendID(dbTag1, commitTag, *constrDOF); if (result < 0) { opserr << "WARNING MP_Joint2D::sendSelf "; opserr << "- error sending constrained DOF data\n"; return result; } } // send retainDOF if (retainDOF != 0 && retainDOF->Size() != 0) { int result = theChannel.sendID(dbTag2, commitTag, *retainDOF); if (result < 0) { opserr << "WARNING MP_Joint2D::sendSelf "; opserr << "- error sending retained DOF data\n"; return result; } } // send constraint matrix if (constraint != 0 && constraint->noRows() != 0) { int result = theChannel.sendMatrix(dbTag3, commitTag, *constraint); if (result < 0) { opserr << "WARNING MP_Joint2D::sendSelf "; opserr << "- error sending constraint Matrix data\n"; return result; } } return 0; } int MP_Joint2D::recvSelf(int commitTag, Channel &theChannel, FEM_ObjectBroker &theBroker) { int dataTag = this->getDbTag(); Vector data(15); int result = theChannel.recvVector(dataTag, commitTag, data); if (result < 0) { opserr << "WARNING MP_Joint2D::recvSelf - error receiving ID data\n"; return result; } this->setTag( (int) data(0)); nodeRetained = (int) data(1); nodeConstrained = (int) data(2); MainDOF = (int) data(3); AuxDOF = (int) data(4); FixedEnd = (int) data(5); int constrDOFsize = (int) data(6); int retainDOFsize = (int) data(7); int numRows = (int) data(8); int numCols = (int) data(9); dbTag1 = (int) data(10); dbTag2 = (int) data(11); dbTag3 = (int) data(12); LargeDisplacement = (int) data(13); Length0 = data(14); // receive constrDOF ID if (constrDOFsize != 0) { constrDOF = new ID(constrDOFsize); int result = theChannel.recvID(dbTag1, commitTag, *constrDOF); if (result < 0) { opserr << "WARNING MP_Joint2D::recvSelf "; opserr << "- error receiving constrained data\n"; return result; } } // receive retainDOF ID if (retainDOFsize != 0) { retainDOF = new ID(retainDOFsize); int result = theChannel.recvID(dbTag2, commitTag, *retainDOF); if (result < 0) { opserr << "WARNING MP_Joint2D::recvSelf "; opserr << "- error receiving retained data\n"; return result; } } // receive the constraint matrix if (numRows != 0 && numCols != 0) { constraint = new Matrix(numRows,numCols); int result = theChannel.recvMatrix(dbTag3, commitTag, *constraint); if (result < 0) { opserr << "WARNING MP_Joint2D::recvSelf "; opserr << "- error receiving Matrix data\n"; return result; } } return 0; } const Matrix &MP_Joint2D::getConstraint(void) { if (constraint == 0) { opserr << "MP_Joint2D::getConstraint - no Matrix was set\n"; exit(-1); } // Length correction // to correct the trial displacement if ( LargeDisplacement == 2 ) { // get the coordinates of the two nodes - check dimensions are the same FOR THE MOMENT const Vector &crdR = RetainedNode->getCrds(); const Vector &crdC = ConstrainedNode->getCrds(); // get committed displacements of nodes to get updated coordinates const Vector &dispR = RetainedNode->getTrialDisp(); const Vector &dispC = ConstrainedNode->getTrialDisp(); double deltaX = dispC(0) + crdC(0) - dispR(0) - crdR(0); double deltaY = dispC(1) + crdC(1) - dispR(1) - crdR(1); Vector Direction(2); Direction(0) = deltaX; Direction(1) = deltaY; double NewLength = Direction.Norm(); if ( NewLength < 1e-12 ) opserr << "MP_Joint2D::applyConstraint : length of rigid link is too small or zero"; Direction = Direction * (Length0/NewLength); // correct the length // find new displacements of the constrainted node Vector NewLocation(3); NewLocation(0) = Direction(0) + dispR(0) + crdR(0) - crdC(0); NewLocation(1) = Direction(1) + dispR(1) + crdR(1) - crdC(1); NewLocation(2) = dispC(2); int dummy = ConstrainedNode->setTrialDisp( NewLocation ); } // end of length correction procedure // return the constraint matrix Ccr return (*constraint); } void MP_Joint2D::Print(OPS_Stream &s, int flag ) { s << "MP_Joint2D: " << this->getTag() << "\n"; s << "\tConstrained Node: " << nodeConstrained; s << " Retained Node: " << nodeRetained ; s << " Fixed end: " << FixedEnd << " Large Disp: " << LargeDisplacement; if (constrDOF != 0) s << " constrained dof: " << *constrDOF; if (retainDOF != 0) s << " retained dof: " << *retainDOF; if (constraint != 0) s << " constraint matrix: " << *constraint << "\n"; } void MP_Joint2D::setDomain(Domain *theDomain) { this->DomainComponent::setDomain(theDomain); thisDomain = theDomain; RetainedNode = thisDomain->getNode(nodeRetained); ConstrainedNode = thisDomain->getNode(nodeConstrained); }
29.170635
116
0.600054
[ "vector", "model" ]
03e81d1e37e210eda0b9123d88e3275fcd935ed8
5,893
cpp
C++
src/apps/colmap2adop.cpp
lfranke/ADOP
14314b832e1f93069d21bd789e7fb57f0692b8b0
[ "MIT" ]
null
null
null
src/apps/colmap2adop.cpp
lfranke/ADOP
14314b832e1f93069d21bd789e7fb57f0692b8b0
[ "MIT" ]
null
null
null
src/apps/colmap2adop.cpp
lfranke/ADOP
14314b832e1f93069d21bd789e7fb57f0692b8b0
[ "MIT" ]
null
null
null
/** * Copyright (c) 2021 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "saiga/core/util/commandLineArguments.h" #include "saiga/core/util/exif/TinyEXIF.h" #include "saiga/core/util/file.h" #include "saiga/vision/cameraModel/OCam.h" #define SAIGA_VISION_API //colmap reader is exported with dll declspec, this removes this #include "saiga/vision/util/ColmapReader.h" #include "data/SceneData.h" std::vector<float> ExposureValuesFromImages(std::vector<std::string> files, std::string image_dir) { std::vector<float> exposures; for (auto f : files) { auto path = image_dir + "/" + f; if (!std::filesystem::exists(path)) { SAIGA_EXIT_ERROR("Could not find image file " + path); } auto data = File::loadFileBinary(path); TinyEXIF::EXIFInfo info; info.parseFrom((unsigned char*)data.data(), data.size()); if (info.FNumber == 0 || info.ExposureTime == 0 || info.ISOSpeedRatings == 0) { std::cout << "No EXIF exposure value found for image " << f << std::endl; exposures.push_back(0); } else { double EV_log2 = log2((info.FNumber * info.FNumber) / info.ExposureTime) + log2(info.ISOSpeedRatings / 100.0) - info.ExposureBiasValue; exposures.push_back(EV_log2); } } std::cout << "EV Statistic:" << std::endl; Statistics stat(exposures); std::cout << stat << std::endl; std::cout << "dynamic range: " << exp2(stat.max - stat.min) << std::endl; return exposures; } static std::shared_ptr<SceneData> ColmapScene(std::string sparse_dir, std::string image_dir, std::string point_cloud_file, std::string output_scene_path, double scale_intrinsics = 1., double render_scale = 1.) { std::cout << "Preprocessing Colmap scene " << sparse_dir << " -> " << output_scene_path << std::endl; std::filesystem::create_directories(output_scene_path); ColmapReader reader(sparse_dir); std::map<int, int> col_cam_to_id; std::vector<std::string> camera_files; std::vector<std::string> image_files; for (auto s : reader.images) { image_files.push_back(s.name); } std::vector<float> exposures = ExposureValuesFromImages(image_files, image_dir); { SceneCameraParams params; for (int i = 0; i < reader.cameras.size(); ++i) { auto c = reader.cameras[i]; params.w = c.w * scale_intrinsics; params.h = c.h * scale_intrinsics; params.K = c.K.scale(scale_intrinsics).cast<float>(); params.distortion = c.dis.cast<float>(); col_cam_to_id[c.camera_id] = i; auto f = "camera" + std::to_string(i) + ".ini"; std::filesystem::remove(output_scene_path + "/" + f); params.Save(output_scene_path + "/" + f); camera_files.push_back(f); } } { std::filesystem::remove(output_scene_path + "/dataset.ini"); SceneDatasetParams params; params.file_model = ""; params.image_dir = image_dir; params.camera_files = camera_files; params.scene_exposure_value = Statistics(exposures).mean; params.render_scale = render_scale; params.scene_up_vector = vec3(0, -1, 0); params.Save(output_scene_path + "/dataset.ini"); } { std::ofstream ostream1(output_scene_path + "/images.txt"); std::ofstream ostream2(output_scene_path + "/camera_indices.txt"); for (auto s : reader.images) { ostream1 << s.name << std::endl; ostream2 << col_cam_to_id[s.camera_id] << std::endl; } } { auto pc_in = point_cloud_file; auto pc_out = output_scene_path + "/point_cloud.ply"; std::filesystem::remove(pc_out); std::filesystem::remove(output_scene_path + "/point_cloud.bin"); SAIGA_ASSERT(std::filesystem::exists(pc_in)); SAIGA_ASSERT(std::filesystem::is_regular_file(pc_in)); std::string command = "cp -v -n " + pc_in + " " + pc_out; auto res = system(command.c_str()); if (res != 0) { SAIGA_EXIT_ERROR("Copy failed!"); } } std::vector<SE3> poses; for (int i = 0; i < reader.images.size(); ++i) { SE3 view(reader.images[i].q, reader.images[i].t); poses.push_back(view.inverse()); } SceneData::SavePoses(poses, output_scene_path + "/poses.txt"); std::shared_ptr<SceneData> sd = std::make_shared<SceneData>(output_scene_path); { SAIGA_ASSERT(sd->frames.size() == reader.images.size()); for (int i = 0; i < reader.images.size(); ++i) { sd->frames[i].exposure_value = exposures[i]; } } sd->Save(); return sd; } int main(int argc, char* argv[]) { std::string sparse_dir; std::string image_dir; std::string point_cloud_file; std::string output_path; double scale_intrinsics = 1; double render_scale = 1; CLI::App app{"COLMAP to ADOP Scene Converter", "colmap2adop"}; app.add_option("--sparse_dir", sparse_dir)->required(); app.add_option("--image_dir", image_dir)->required(); app.add_option("--point_cloud_file", point_cloud_file)->required(); app.add_option("--output_path", output_path)->required(); app.add_option("--scale_intrinsics", scale_intrinsics)->required(); app.add_option("--render_scale", render_scale)->required(); CLI11_PARSE(app, argc, argv); ColmapScene(sparse_dir, image_dir, point_cloud_file, output_path, scale_intrinsics, render_scale); return 0; }
30.220513
134
0.597489
[ "vector" ]
03f533747d6044690b42340c46482dc2c163d78c
14,839
cpp
C++
CursedHeaven/Motor2D/j1Scene1.cpp
golden-rhino-studio/CursedHeaven
16e7bd3e82b64302564251d4856be570add0f98e
[ "MIT" ]
null
null
null
CursedHeaven/Motor2D/j1Scene1.cpp
golden-rhino-studio/CursedHeaven
16e7bd3e82b64302564251d4856be570add0f98e
[ "MIT" ]
1
2019-03-05T18:25:36.000Z
2019-03-05T18:26:39.000Z
CursedHeaven/Motor2D/j1Scene1.cpp
golden-rhino-studio/CursedHeaven
16e7bd3e82b64302564251d4856be570add0f98e
[ "MIT" ]
null
null
null
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Collisions.h" #include "j1Render.h" #include "j1Window.h" #include "j1Map.h" #include "j1DragoonKnight.h" #include "j1BlackMage.h" #include "j1Tank.h" #include "j1Rogue.h" #include "j1Judge.h" #include "j1SceneMenu.h" #include "j1Scene1.h" #include "j1Scene2.h" #include "j1FadeToBlack.h" #include "j1Pathfinding.h" #include "j1Gui.h" #include "j1SceneMenu.h" #include "j1Label.h" #include "j1Button.h" #include "j1Box.h" #include "j1ChooseCharacter.h" #include "j1DialogSystem.h" #include "j1Particles.h" #include "j1SceneLose.h" #include "j1Shop.h" #include "j1Minimap.h" #include "j1TransitionManager.h" #include "j1SceneKeyConfig.h" #include "j1Video.h" #include "Brofiler/Brofiler.h" j1Scene1::j1Scene1() : j1Module() { name.assign("scene1"); } // Destructor j1Scene1::~j1Scene1() {} // Called before render is available bool j1Scene1::Awake(pugi::xml_node& config) { LOG("Loading Scene 1"); bool ret = true; if (App->video->active == true) active = false; if (App->menu->active == true) active = false; if (active == false) LOG("Scene1 not active."); return ret; } // Called before the first frame bool j1Scene1::Start() { if (active) { App->map->draw_with_quadtrees = true; // The map is loaded if (App->map->Load("greenmount.tmx")) { int w, h; uchar* data = NULL; if (App->map->CreateWalkabilityMap(w, h, &data)) { App->path->SetMap(w, h, data); } RELEASE_ARRAY(data); } // The audio is played App->audio->PlayMusic("audio/music/song034.ogg", 1.0f); // Textures are loaded debug_tex = App->tex->Load("maps/path2.png"); gui_tex = App->tex->Load("gui/uipack_rpg_sheet.png"); lvl1_tex = App->tex->Load("maps/minimap_lvl1.png"); bg = App->tex->Load("maps/Background.png"); // Creating UI SDL_Rect section = { 9,460,315,402 }; App->scene1->settings_window = App->gui->CreateBox(&scene1Boxes, BOX, App->gui->settingsPosition.x, App->gui->settingsPosition.y, section, gui_tex); App->scene1->settings_window->visible = false; SDL_Rect idle = { 631, 12, 151, 38 }; SDL_Rect hovered = { 963, 12, 151, 38 }; SDL_Rect clicked = { 797, 14, 151, 37 }; SDL_Rect idle2 = { 1181, 12, 99, 38 }; SDL_Rect hovered2 = { 1386, 12, 99, 38 }; SDL_Rect clicked2 = { 1283, 12, 99, 38 }; SDL_Rect slider_r = { 860,334,180,5 }; App->gui->CreateButton(&scene1Buttons, BUTTON, 20, 65, slider_r, slider_r, slider_r, gui_tex, NO_FUNCTION, (j1UserInterfaceElement*)settings_window); App->gui->CreateButton(&scene1Buttons, BUTTON, 20, 100, slider_r, slider_r, slider_r, gui_tex, NO_FUNCTION, (j1UserInterfaceElement*)settings_window); App->gui->CreateBox(&scene1Boxes, BOX, 50, 55, { 388, 455, 28, 42 }, gui_tex, (j1UserInterfaceElement*)settings_window, 20, 92); App->gui->CreateBox(&scene1Boxes, BOX, 50, 90, { 388, 455, 28, 42 }, gui_tex, (j1UserInterfaceElement*)settings_window, 20, 92); App->gui->CreateButton(&scene1Buttons, BUTTON, 10, 20, idle2, hovered2, clicked2, gui_tex, CLOSE_SETTINGS, (j1UserInterfaceElement*)settings_window); App->gui->CreateButton(&scene1Buttons, BUTTON, 70, 20, idle2, hovered2, clicked2, gui_tex, SAVE_GAME, (j1UserInterfaceElement*)settings_window); App->gui->CreateButton(&scene1Buttons, BUTTON, 30, 120, idle, hovered, clicked, gui_tex, GO_TO_MENU, (j1UserInterfaceElement*)settings_window); App->gui->CreateLabel(&scene1Labels, LABEL, 25, 40, App->gui->font2, "SOUND", App->gui->brown, (j1UserInterfaceElement*)settings_window); App->gui->CreateLabel(&scene1Labels, LABEL, 25, 75, App->gui->font2, "MUSIC", App->gui->brown, (j1UserInterfaceElement*)settings_window); App->gui->CreateLabel(&scene1Labels, LABEL, 48, 122, App->gui->font2, "MAIN MENU", App->gui->beige, (j1UserInterfaceElement*)settings_window); App->gui->CreateLabel(&scene1Labels, LABEL, 20, 22, App->gui->font2, "RESUME", App->gui->beige, (j1UserInterfaceElement*)settings_window); App->gui->CreateLabel(&scene1Labels, LABEL, 83, 22, App->gui->font2, "SAVE", App->gui->beige, (j1UserInterfaceElement*)settings_window); PlaceEntities(6); App->shop->PlaceShopScene1(); App->entity->CreateEntity(JUDGE, 210, 760); startup_time.Start(); windowTime.Start(); } return true; } // Called each loop iteration bool j1Scene1::PreUpdate() { BROFILER_CATEGORY("Level1PreUpdate", Profiler::Color::Orange) current_points.erase(); return true; } // Called each loop iteration bool j1Scene1::Update(float dt) { BROFILER_CATEGORY("Level1Update", Profiler::Color::LightSeaGreen) time_scene1 = startup_time.ReadSec(); // --------------------------------------------------------------------------------------------------------------------- // USER INTERFACE MANAGEMENT // --------------------------------------------------------------------------------------------------------------------- App->gui->UpdateButtonsState(&scene1Buttons, App->gui->buttonsScale); App->gui->UpdateWindow(settings_window, &scene1Buttons, &scene1Labels, &scene1Boxes); score_player = App->entity->currentPlayer->coins; current_points = std::to_string(score_player); if (App->scene1->active && App->scene1->startup_time.Read() > 1700) { if (App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN || closeSettings || (SDL_GameControllerGetButton(App->input->controller, SDL_CONTROLLER_BUTTON_START) == KEY_DOWN && windowTime.Read() >= lastWindowTime + 200)) { settings_window->visible = !settings_window->visible; App->gamePaused = !App->gamePaused; lastWindowTime = windowTime.Read(); settings_window->position = { App->gui->settingsPosition.x - App->render->camera.x / (int)App->win->GetScale(), App->gui->settingsPosition.y - App->render->camera.y / (int)App->win->GetScale() }; for (std::list<j1Button*>::iterator item = scene1Buttons.begin(); item != scene1Buttons.end(); ++item) { if ((*item)->parent == settings_window) { (*item)->visible = !(*item)->visible; (*item)->position.x = settings_window->position.x + (*item)->initialPosition.x; (*item)->position.y = settings_window->position.y + (*item)->initialPosition.y; } } for (std::list<j1Label*>::iterator item = scene1Labels.begin(); item != scene1Labels.end(); ++item) { if ((*item)->parent == settings_window) { (*item)->visible = !(*item)->visible; (*item)->position.x = settings_window->position.x + (*item)->initialPosition.x; (*item)->position.y = settings_window->position.y + (*item)->initialPosition.y; } } for (std::list<j1Box*>::iterator item = scene1Boxes.begin(); item != scene1Boxes.end(); ++item) { if ((*item)->parent == settings_window) { (*item)->visible = !(*item)->visible; (*item)->position.x = settings_window->position.x + (*item)->initialPosition.x; (*item)->position.y = settings_window->position.y + (*item)->initialPosition.y; (*item)->minimum = (*item)->originalMinimum + settings_window->position.x; (*item)->maximum = (*item)->originalMaximum + settings_window->position.x; (*item)->distanceCalculated = false; } } if (!settings_window->visible) closeSettings = false; } } App->gui->UpdateSliders(&scene1Boxes); // Save if (App->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN || mustSave) { App->SaveGame("save_game.xml"); mustSave = false; } // Button actions for (std::list<j1Button*>::iterator item = scene1Buttons.begin(); item != scene1Buttons.end(); ++item) { switch ((*item)->state) { case IDLE: (*item)->situation = (*item)->idle; break; case HOVERED: (*item)->situation = (*item)->hovered; break; case RELEASED: (*item)->situation = (*item)->idle; if ((*item)->bfunction == GO_TO_MENU) { backToMenu = true; App->gamePaused = false; settings_window->visible = false; App->fade->FadeToBlack(); } else if ((*item)->bfunction == CLOSE_SETTINGS) { closeSettings = true; } else if ((*item)->bfunction == OTHER_LEVEL) { changingScene = true; App->gamePaused = false; settings_window->visible = false; App->fade->FadeToBlack(); } else if ((*item)->bfunction == SAVE_GAME) { mustSave = true; closeSettings = true; } else if ((*item)->bfunction == CLOSE_GAME) { continueGame = false; } break; case CLICKED: (*item)->situation = (*item)->clicked; break; } } if (App->input->GetKey(SDL_SCANCODE_F4) == KEY_DOWN) App->entity->currentPlayer->victory = true; // Managing scene transitions if (App->input->GetKey(SDL_SCANCODE_F3) == KEY_DOWN || changingScene) { changingScene = true; App->fade->FadeToBlack(); if (App->fade->IsFading() == 0) ChangeSceneMenu(); } if (App->input->GetKey(App->key_config->TABULADOR) == KEY_DOWN || (SDL_GameControllerGetButton(App->input->controller, SDL_CONTROLLER_BUTTON_BACK) == KEY_DOWN && statsTime.Read() >= lastStatsTime + 200)) { lastStatsTime = statsTime.Read(); if (profile_active) profile_active = false; else profile_active = true; } if (App->entity->currentPlayer->dead == true) { toLoseScene = true; App->fade->FadeToBlack(); if (App->fade->IsFading() == 0) ChangeSceneDeath(); } if (App->entity->currentPlayer->victory == true) { App->fade->FadeToBlack(); if (App->fade->IsFading() == 0) ChangeScene2(); } if (backToMenu && App->fade->IsFading() == 0) ChangeSceneMenu(); // --------------------------------------------------------------------------------------------------------------------- // DRAWING EVERYTHING ON THE SCREEN // --------------------------------------------------------------------------------------------------------------------- App->render->Blit(bg, 0, 0, NULL, SDL_FLIP_NONE, false, 0.7f); App->map->Draw(); App->entity->DrawEntityOrder(dt); App->render->reOrder(); App->render->OrderBlit(App->render->OrderToRender); if (App->entity->player_type == KNIGHT && App->entity->currentPlayer->active_Q && App->entity->knight != nullptr) App->render->Blit(App->entity->knight->shieldTex, App->entity->currentPlayer->position.x + 2, App->entity->currentPlayer->position.y + 8, NULL, SDL_FLIP_NONE, true, 0.13f); return true; } // Called each loop iteration bool j1Scene1::PostUpdate() { BROFILER_CATEGORY("Level1PostUpdate", Profiler::Color::Yellow) if (finishedDialog) App->render->Blit(lvl1_tex, App->win->width - 400, App->win->height - 200, &rect, SDL_FLIP_NONE, false, 0.3333333f); return continueGame; } bool j1Scene1::Load(pugi::xml_node& node) { active = node.child("activated").attribute("value").as_bool(); finishedDialog = node.child("dialogs").attribute("dialog").as_bool(); ableSellerDialog = node.child("dialogs").attribute("sellerDialog").as_bool(); potionCounter = node.child("potions").attribute("counter").as_uint(); return true; } bool j1Scene1::Save(pugi::xml_node& node) const { pugi::xml_node activated = node.append_child("activated"); activated.append_attribute("value") = active; pugi::xml_node dialogs = node.append_child("dialogs"); dialogs.append_attribute("dialog") = finishedDialog; dialogs.append_attribute("sellerDialog") = ableSellerDialog; pugi::xml_node potions = node.append_child("potions"); potions.append_attribute("counter") = potionCounter; return true; } void j1Scene1::PlaceEntities(int room) { App->entity->AddEnemy(6, 57, SLIME); App->entity->AddEnemy(15, 54, SLIME); App->entity->AddEnemy(17, 61, SLIME); App->entity->AddEnemy(31, 65, SLIME); App->entity->AddEnemy(28, 65, SLIME); App->entity->AddEnemy(28, 53, SLIME); App->entity->AddEnemy(29, 40, SLIME); App->entity->AddEnemy(33, 41, SLIME); App->entity->AddEnemy(14, 41, SLIME); App->entity->AddEnemy(45, 45, SLIME); App->entity->AddEnemy(43, 39, SLIME); App->entity->AddEnemy(38, 41, SLIME); App->entity->AddEnemy(29, 19, SLIME); App->entity->AddEnemy(28, 22, SLIME); App->entity->AddEnemy(26, 26, SLIME); App->entity->AddEnemy(46, 25, SLIME); App->entity->AddEnemy(45, 32, SLIME); App->entity->AddEnemy(38, 28, SLIME); App->entity->AddEnemy(23, 4, SLIME); App->entity->AddEnemy(12, 4, SLIME); App->entity->AddEnemy(17, 13, SLIME); App->entity->AddEnemy(49, 4, SLIME); App->entity->AddEnemy(60, 7, SLIME); App->entity->AddEnemy(59, 11, SLIME); App->entity->AddEnemy(70, 8, SLIME); App->entity->AddEnemy(85, 23, SLIME); App->entity->AddEnemy(80, 19, SLIME); App->entity->AddEnemy(70, 25, SLIME); App->entity->AddEnemy(88, 46, SLIME); App->entity->AddEnemy(80, 42, SLIME); App->entity->AddEnemy(85, 60, SLIME); App->entity->AddEnemy(80, 65, SLIME); App->entity->AddEnemy(53, 68, MINDFLYER); } // Called before quitting bool j1Scene1::CleanUp() { LOG("Freeing scene"); App->tex->UnLoad(bg); App->tex->UnLoad(lvl1_tex); App->tex->UnLoad(gui_tex); App->tex->UnLoad(debug_tex); App->map->CleanUp(); App->collisions->CleanUp(); App->tex->CleanUp(); App->entity->DestroyEntities(); App->gui->CleanUp(); App->particles->CleanUp(); potionCounter = 0; finishedDialog = false; ableSellerDialog = true; if (App->entity->knight) App->entity->knight->CleanUp(); if (App->entity->mage) App->entity->mage->CleanUp(); for (std::list<j1Button*>::iterator item = scene1Buttons.begin(); item != scene1Buttons.end();) { (*item)->CleanUp(); scene1Buttons.erase(item++); } for (std::list<j1Label*>::iterator item = scene1Labels.begin(); item != scene1Labels.end();) { (*item)->CleanUp(); scene1Labels.erase(item++); } for (std::list<j1Box*>::iterator item = scene1Boxes.begin(); item != scene1Boxes.end();) { (*item)->CleanUp(); scene1Boxes.erase(item++); } delete settings_window; if (settings_window != nullptr) settings_window = nullptr; App->path->CleanUp(); App->entity->CleanUp(); App->dialog->active = false; App->dialog->CleanUp(); return true; } void j1Scene1::ChangeSceneMenu() { App->scene1->active = false; App->menu->active = true; changingScene = false; CleanUp(); App->shop->restartingShop = true; App->shop->CleanUp(); App->entity->active = false; App->menu->Start(); App->render->camera = { 0,0 }; App->entity->player_type = NO_PLAYER; backToMenu = false; } void j1Scene1::ChangeSceneDeath() { App->scene1->active = false; App->lose->active = true; CleanUp(); App->shop->restartingShop = true; App->shop->CleanUp(); App->entity->active = false; App->lose->Start(); App->render->camera = { 0,0 }; toLoseScene = false; } void j1Scene1::ChangeScene2() { App->scene1->active = false; App->scene2->active = true; CleanUp(); App->shop->CleanUp(); App->entity->active = false; App->scene2->Start(); App->gui->Start(); App->entity->active = true; App->entity->CreatePlayer2(); App->entity->Start(); App->particles->Start(); App->entity->currentPlayer->victory = false; }
30.532922
174
0.657187
[ "render" ]
03f90760e970a7d70b8f929b369a36961c37c80e
991
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/geometry/policies/robustness/rescale_policy_tags.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
326
2015-02-08T13:47:49.000Z
2022-03-16T02:13:59.000Z
ReactNativeFrontend/ios/Pods/boost/boost/geometry/policies/robustness/rescale_policy_tags.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
623
2015-01-02T23:45:23.000Z
2022-03-09T11:15:23.000Z
ReactNativeFrontend/ios/Pods/boost/boost/geometry/policies/robustness/rescale_policy_tags.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
215
2015-01-14T15:50:38.000Z
2022-02-23T03:58:36.000Z
// Boost.Geometry // Copyright (c) 2019-2019 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_POLICIES_ROBUSTNESS_RESCALE_POLICY_TYPE_HPP #define BOOST_GEOMETRY_POLICIES_ROBUSTNESS_RESCALE_POLICY_TYPE_HPP #include <boost/geometry/policies/robustness/no_rescale_policy.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { struct no_rescale_policy_tag {}; struct rescale_policy_tag {}; template <typename RobustPolicy> struct rescale_policy_type { typedef rescale_policy_tag type; }; // Specialization template <> struct rescale_policy_type<no_rescale_policy> { typedef no_rescale_policy_tag type; }; } // namespace detail #endif }} // namespace boost::geometry #endif // BOOST_GEOMETRY_POLICIES_ROBUSTNESS_RESCALE_POLICY_TYPE_HPP
22.522727
79
0.806256
[ "geometry" ]
03ff522509d995584b86a1ca89b9931fdd777c29
14,283
cpp
C++
common/texture.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
2
2019-10-25T10:00:07.000Z
2019-11-11T07:03:14.000Z
common/texture.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
null
null
null
common/texture.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
null
null
null
#include "texture.h" #include <stb_image.h> namespace es { Texture::Texture() :mID(0), mTarget(GL_TEXTURE_2D), mInternalFormat(GL_RGBA8), mFormat(GL_RGBA), mType(GL_UNSIGNED_BYTE), mComponents(4), mArraySize(1) { GLES_CHECK_ERROR(glGenTextures(1, &mID)); } Texture::~Texture() { GLES_CHECK_ERROR(glDeleteTextures(1, &mID)); } void Texture::bind(uint32_t unit) { GLES_CHECK_ERROR(glActiveTexture(GL_TEXTURE0 + unit)); GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); } void Texture::unbind(uint32_t unit) { GLES_CHECK_ERROR(glActiveTexture(GL_TEXTURE0 + unit)); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } void Texture::generateMipmaps() { GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); GLES_CHECK_ERROR(glGenerateMipmap(mTarget)); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } GLuint Texture::getID() { return mID; } GLenum Texture::getTarget() { return mTarget; } GLenum Texture::getInternalFormat() { return mInternalFormat; } GLenum Texture::getFormat() { return mFormat; } GLenum Texture::getType() { return mType; } uint32_t Texture::getArraySize() { return mArraySize; } void Texture::setWrapping(GLenum s, GLenum t, GLenum r) { GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); GLES_CHECK_ERROR(glTexParameteri(mTarget, GL_TEXTURE_WRAP_S, s)); GLES_CHECK_ERROR(glTexParameteri(mTarget, GL_TEXTURE_WRAP_T, t)); GLES_CHECK_ERROR(glTexParameteri(mTarget, GL_TEXTURE_WRAP_R, r)); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } void Texture::setBorderColor(float r, float g, float b, float a) { std::array<float, 4> borderColor = { r, g, b, a }; GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); GLES_CHECK_ERROR(glTexParameterfv(mTarget, GL_TEXTURE_BORDER_COLOR_NV, borderColor.data())); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } void Texture::setMinFilter(GLenum filter) { GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); GLES_CHECK_ERROR(glTexParameteri(mTarget, GL_TEXTURE_MIN_FILTER, filter)); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } void Texture::setMagFilter(GLenum filter) { GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); GLES_CHECK_ERROR(glTexParameteri(mTarget, GL_TEXTURE_MAG_FILTER, filter)); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } void Texture::bindImage(uint32_t unit, uint32_t mipLevel, uint32_t layer, GLenum access, GLenum format) { bind(unit); if (mArraySize > 1) glBindImageTexture(unit, mID, mipLevel, GL_TRUE, layer, access, format); else glBindImageTexture(unit, mID, mipLevel, GL_FALSE, 0, access, format); } void Texture::setCompareMode(GLenum mode) { GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); GLES_CHECK_ERROR(glTexParameteri(mTarget, GL_TEXTURE_COMPARE_MODE, mode)); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } void Texture::setCompareFunc(GLenum func) { GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); GLES_CHECK_ERROR(glTexParameteri(mTarget, GL_TEXTURE_COMPARE_FUNC, func)); GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } // ------------------------------------------------------------------------------------------------------------------------------------------ std::unordered_map<std::string, std::shared_ptr<Texture2D>> Texture2D::mTexture2DCache; Texture2D::Texture2D(std::string path, int mipLevels, bool srgb) : Texture() { initFromFile(path, mipLevels, srgb); } Texture2D::Texture2D(uint32_t w, uint32_t h, uint32_t arraySize, int32_t mipLevels, uint32_t numSamples, GLenum internalFormat, GLenum format, GLenum type) : Texture() { initFromData(w, h, arraySize, mipLevels, numSamples, internalFormat, format, type); } Texture2D::~Texture2D() { } std::shared_ptr<Texture2D> Texture2D::createFromFile(std::string path, int mipLevels, bool srgb) { if (mTexture2DCache.find(path) == mTexture2DCache.end()) { std::shared_ptr<Texture2D> tex2d = std::make_shared<Texture2D>(path, mipLevels, srgb); mTexture2DCache[path] = tex2d; return tex2d; } else { return mTexture2DCache[path]; } } std::shared_ptr<Texture2D> Texture2D::createFromData(uint32_t w, uint32_t h, uint32_t arraySize, int32_t mipLevels, uint32_t numSamples, GLenum internalFormat, GLenum format, GLenum type) { return std::make_shared<Texture2D>(w, h, arraySize, mipLevels, numSamples, internalFormat, format, type); } void Texture2D::setData(int arrayIndex, int mipLevel, void* data) { if (mNumSamples > 1) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "OpenGL ES : Multisampled texture data only can be assigned through shaders or FBOs"); } else { int width = mWidth; int height = mHeight; for (int i = 0; i < mipLevel; i++) { width = std::max(1, width / 2); height = std::max(1, height / 2); } GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); if (mArraySize > 1) { GLES_CHECK_ERROR(glTexImage3D(mTarget, mipLevel, mInternalFormat, width, height, arrayIndex, 0, mFormat, mType, data)); } else { GLES_CHECK_ERROR(glTexImage2D(mTarget, mipLevel, mInternalFormat, width, height, 0, mFormat, mType, data)); } GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } } void Texture2D::initFromFile(std::string path, int mipLevels, bool srgb) { int width, height, components; stbi_uc* data = stbi_load(path.c_str(), &width, &height, &components, 0); if (!data) { stbi_image_free(data); return; } GLenum internalFormat, format; switch (components) { case 1: { internalFormat = GL_R8; format = GL_RED; break; } case 2: { internalFormat = GL_RG8; format = GL_RG; break; } case 3: { if (srgb) { internalFormat = GL_SRGB8; } else { internalFormat = GL_RGB8; } format = GL_RGB; break; } case 4: { if (srgb) { internalFormat = GL_SRGB8_ALPHA8; } else { internalFormat = GL_RGBA8; } format = GL_RGBA; break; } default: { internalFormat = GL_RGBA8; format = GL_RGBA; break; } } mArraySize = 1; mInternalFormat = internalFormat; mFormat = format; mType = GL_UNSIGNED_BYTE; mWidth = width; mHeight = height; mNumSamples = 1; if (mipLevels == -1) { mMipLevels = 1; while (width > 1 && height > 1) { width = std::max(1, (width / 2)); height = std::max(1, (height / 2)); mMipLevels++; } } else { mMipLevels = mipLevels; } if (mArraySize > 1) { mTarget = GL_TEXTURE_2D_ARRAY; width = mWidth; height = mHeight; GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); for (int i = 0; i < mMipLevels; i++) { GLES_CHECK_ERROR(glTexImage3D(mTarget, i, mInternalFormat, width, height, mArraySize, 0, mFormat, mType, nullptr)); width = std::max(1, (width / 2)); height = std::max(1, (height / 2)); } GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } else { if (mNumSamples > 1) { mTarget = GL_TEXTURE_2D_MULTISAMPLE; } else { mTarget = GL_TEXTURE_2D; } width = mWidth; height = mHeight; GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); for (int i = 0; i < mMipLevels; i++) { GLES_CHECK_ERROR(glTexImage2D(mTarget, i, mInternalFormat, width, height, 0, mFormat, mType, nullptr)); width = std::max(1, (width / 2)); height = std::max(1, (height / 2)); } GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } setWrapping(GL_REPEAT, GL_REPEAT, GL_REPEAT); setMinFilter(GL_LINEAR_MIPMAP_LINEAR); setMagFilter(GL_LINEAR); setData(0, 0, data); generateMipmaps(); stbi_image_free(data); } void Texture2D::initFromData(uint32_t w, uint32_t h, uint32_t arraySize, int32_t mipLevels, uint32_t numSamples, GLenum internalFormat, GLenum format, GLenum type) { mArraySize = arraySize; mInternalFormat = internalFormat; mFormat = format; mType = type; mWidth = w; mHeight = h; mNumSamples = numSamples; if (mipLevels == -1) { mMipLevels = 1; int width = mWidth; int height = mHeight; while (width > 1 && height > 1) { width = std::max(1, (width / 2)); height = std::max(1, (height / 2)); mMipLevels++; } } else { mMipLevels = mipLevels; } if (arraySize > 1) { mTarget = GL_TEXTURE_2D_ARRAY; int width = mWidth; int height = mHeight; GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); for (int i = 0; i < mMipLevels; i++) { GLES_CHECK_ERROR(glTexImage3D(mTarget, i, mInternalFormat, width, height, mArraySize, 0, mFormat, mType, nullptr)); width = std::max(1, (width / 2)); height = std::max(1, (height / 2)); } GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } else { if (mNumSamples > 1) { mTarget = GL_TEXTURE_2D_MULTISAMPLE; } else { mTarget = GL_TEXTURE_2D; } int width = mWidth; int height = mHeight; GLES_CHECK_ERROR(glBindTexture(mTarget, mID)); if (mNumSamples > 1) { } else { for (int i = 0; i < mMipLevels; i++) { GLES_CHECK_ERROR(glTexImage2D(mTarget, i, mInternalFormat, width, height, 0, mFormat, mType, nullptr)); width = std::max(1, (width / 2)); height = std::max(1, (height / 2)); } } GLES_CHECK_ERROR(glBindTexture(mTarget, 0)); } setWrapping(GL_REPEAT, GL_REPEAT, GL_REPEAT); setMinFilter(GL_LINEAR_MIPMAP_LINEAR); setMagFilter(GL_LINEAR); generateMipmaps(); } uint32_t Texture2D::getWidth() { return mWidth; } uint32_t Texture2D::getHeight() { return mHeight; } uint32_t Texture2D::getMipLevels() { return mMipLevels; } uint32_t Texture2D::getNumSamples() { return mNumSamples; } // ------------------------------------------------------------------------------------------------------------------------------------------------- TextureCube::TextureCube() : Texture() { } TextureCube::~TextureCube() { } TextureCube* TextureCube::createFromFiles(std::vector<std::string> paths, int mipLevels, bool srgb) { TextureCube* texture = new (std::nothrow) TextureCube(); if (texture && texture->initFromFiles(paths, mipLevels, srgb)) { return texture; } delete(texture); return nullptr; } void TextureCube::setData(int faceIndex, int layerIndex, int mipLevel, void* data) { } bool TextureCube::initFromFiles(std::vector<std::string> paths, int mipLevels, bool srgb) { return false; } uint32_t TextureCube::getWidth() { return mWidth; } uint32_t TextureCube::getHeight() { return mHeight; } uint32_t TextureCube::getMipLevels() { return mMipLevels; } /* Texture::Texture() { } Texture::~Texture() { glDeleteTextures(1, &ID); } Texture* Texture::createWithFile(const std::string& path, Type type) { Texture* texture = new (std::nothrow) Texture(); if (texture && texture->initWithFile(path, type)) { return texture; } delete(texture); return nullptr; } GLuint Texture::getID() const { return ID; } glm::vec2 Texture::getSize() const { return glm::vec2(width, height); } GLint Texture::getChannelCount() const { return channelCount; } GLenum Texture::getFormat() const { return format; } std::string Texture::getFilePath() const { return filePath; } Texture::Type Texture::getType() const { return type; } GLboolean Texture::initWithFile(const std::string& path, Texture::Type type) { this->filePath = path; this->type = type; glGenTextures(1, &ID); stbi_set_flip_vertically_on_load(true); unsigned char* data = stbi_load(path.c_str(), &width, &height, &channelCount, 0); if (data) { switch (channelCount) { case 1: { format = GL_RED; break; } case 3: { format = GL_RGB; break; } case 4: { format = GL_RGBA; break; } } glBindTexture(GL_TEXTURE_2D, ID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "failed to load texture at path: " + path << std::endl; stbi_image_free(data); return false; } return true; } TextureCube::TextureCube() { } TextureCube::~TextureCube() { glDeleteTextures(1, &ID); } TextureCube* TextureCube::createWithFiles(const std::vector<std::string>& filePaths) { TextureCube* textureCube = new (std::nothrow) TextureCube(); if (textureCube && textureCube->initWithFiles(filePaths)) { return textureCube; } delete(textureCube); return nullptr; } GLuint TextureCube::getID() const { return ID; } GLboolean TextureCube::initWithFiles(const std::vector<std::string>& filePaths) { this->filePaths = filePaths; glGenTextures(1, &ID); glBindTexture(GL_TEXTURE_CUBE_MAP, ID); int width, height, nrChannels; for (size_t i = 0; i < filePaths.size(); i++) { unsigned char* data = stbi_load(filePaths[i].c_str(), &width, &height, &nrChannels, 0); if (data) { if (nrChannels == 1) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RED, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, data); else if (nrChannels == 3) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); else if (nrChannels == 4) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cout << "failed to create cubemap texture at path : " << filePaths[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); return true; } */ }
21.706687
188
0.666037
[ "vector" ]
ff093562c550018c3066c36b22c6fe3bcd09480b
23,172
hpp
C++
include/Network/NetworkHandling.hpp
mjshakir/circle_predictor
63774bbfa0c86d4faa06201f154154a141994a27
[ "MIT" ]
null
null
null
include/Network/NetworkHandling.hpp
mjshakir/circle_predictor
63774bbfa0c86d4faa06201f154154a141994a27
[ "MIT" ]
null
null
null
include/Network/NetworkHandling.hpp
mjshakir/circle_predictor
63774bbfa0c86d4faa06201f154154a141994a27
[ "MIT" ]
null
null
null
#pragma once //-------------------------------------------------------------- // Standard cpp library //-------------------------------------------------------------- #include <future> #include <algorithm> #include <execution> //-------------------------------------------------------------- // LibTorch library //-------------------------------------------------------------- #include <torch/torch.h> //-------------------------------------------------------------- // User Defined library //-------------------------------------------------------------- #include "Timing/TimeIT.hpp" //-------------------------------------------------------------- // LibFort library (enable table printing) //-------------------------------------------------------------- #include "fort.hpp" //-------------------------------------------------------------- // Progressbar library //-------------------------------------------------------------- #include "progressbar/include/progressbar.hpp" //-------------------------------------------------------------- template<typename Network> class NetworkHandling{ public: //-------------------------------------------------------------- NetworkHandling() = delete; //-------------------------- /** * @brief A constructor * * @tparam model: A torch network struct that inherits from torch::nn::Module. * @tparam device torch::Device cpu or gpu. */ NetworkHandling(Network& model, const torch::Device& device): m_model(model), m_device(device){ //-------------------------- }// end NetworkHandling(Network& model, torch::Device& device) //-------------------------- /** * @brief A constructor * * @tparam model: A torch network struct that inherits from torch::nn::Module. * @tparam device torch::Device cpu or gpu. */ NetworkHandling(Network&& model, const torch::Device& device): m_model(std::move(model)), m_device(device){ //-------------------------- }// end NetworkHandling(Network& model, torch::Device& device) //-------------------------- /** * @brief Train the model with fix epoch iteration * * @tparam data_loader: A torch dataloader. * @tparam optimizer: torch::optim::Optimizer. * @tparam epoch: How many iteration to train. * @return vector of float */ template <typename Dataloader> std::vector<float> train(Dataloader&& data_loader, torch::optim::Optimizer& optimizer, const size_t& epoch = 100UL){ //-------------------------- return network_train(std::move(data_loader), optimizer, epoch); //-------------------------- }// end std::vector<float> train(Dataloader&& data_loader, torch::optim::Optimizer& optimizer, const size_t& epoch) //-------------------------- /** * @brief Train the model with a validation set. The training stop when precision is hit * * @tparam data_loader: A torch dataloader. * @tparam data_loader_validation: A torch dataloader. * @tparam optimizer: torch::optim::Optimizer. * @tparam precision: a value that will stop the training once hit. * * @return vector of float */ template <typename Dataloader, typename Validation_Dataloader> std::vector<float> train( Dataloader&& data_loader, Validation_Dataloader&& data_loader_validation, torch::optim::Optimizer& optimizer, long double precision = 1E-2L){ //-------------------------- return network_train(std::move(data_loader), std::move(data_loader_validation), optimizer, precision); //-------------------------- }// end std::vector<float> train(Dataloader&& data_loader, Validation_Dataloader&& data_loader_validation, torch::optim::Optimizer& optimizer, float precision = 10) //-------------------------- /** * @brief Run a validation set on the modal * * @tparam data_loader: A torch dataloader. * * @return vector of float */ template <typename Dataset> std::vector<float> validation(Dataset&& data_loader){ //-------------------------- return network_validation(std::move(data_loader)); //-------------------------- }// end std::vector<float> validation(Dataset&& data_loader) //-------------------------------------------------------------- /** * @brief Run a test set on the modal * * @tparam data_loader: A torch dataloader. * * @return vector of tuples * 1) torch::Tensor: Original targets set * 2) torch::Tensor: Results set * 3) float: Set Loss */ template <typename Dataset> std::vector<std::tuple<torch::Tensor, torch::Tensor, float>> test(Dataset&& data_loader){ //-------------------------- return network_test(std::move(data_loader)); //-------------------------- }// end std::vector<std::tuple<torch::Tensor, torch::Tensor, float>> test(Dataset&& data_loader) //-------------------------------------------------------------- protected: //-------------------------- template <typename Batch> float network_train_batch(Batch&& batch, torch::optim::Optimizer& optimizer, bool *tensorIsNan){ //-------------------------- m_model.train(true); //-------------------------- auto data = batch.data.to(m_device), targets = batch.target.to(m_device); //-------------------------- optimizer.zero_grad(); //-------------------------- auto output = m_model.forward(data); //-------------------------- torch::Tensor loss = torch::mse_loss(output, targets); // AT_ASSERT(!std::isnan(loss.template item<float>())); //-------------------------- *tensorIsNan = at::isnan(loss).any().item<bool>(); // will be of type bool //-------------------------- loss.backward({},c10::optional<bool>(true), false); optimizer.step(); //-------------------------- return loss.template item<float>(); //-------------------------- }// end float network_train_batch(Batch&& batch, torch::optim::Optimizer& optimizer) //-------------------------- template <typename Batch> float network_validation_batch(Batch&& batch){ //-------------------------- torch::NoGradGuard no_grad; m_model.eval(); //-------------------------- auto data = batch.data.to(m_device), targets = batch.target.to(m_device); auto output = m_model.forward(data); //-------------------------- return torch::mse_loss(output, targets, torch::Reduction::Sum).template item<double>(); //-------------------------- }// end float network_validation_batch(Batch&& batch) //-------------------------- template <typename Batch> std::tuple<torch::Tensor, torch::Tensor, float> network_test_batch(Batch&& batch){ //-------------------------- torch::NoGradGuard no_grad; m_model.eval(); //-------------------------- auto data = batch.data.to(m_device), targets = batch.target.to(m_device); auto output = m_model.forward(data); //-------------------------- return {targets, output, torch::mse_loss(output, targets, torch::Reduction::Sum).template item<float>()}; //-------------------------- }// end std::tuple<torch::Tensor, torch::Tensor, float> network_test_batch(Batch&& batch) //-------------------------- template <typename Dataloader> std::vector<float> network_train(Dataloader&& data_loader, torch::optim::Optimizer& optimizer, const size_t& epoch){ //-------------------------- auto data_loader_size = std::distance(data_loader->begin(), data_loader->end()); //-------------------------- bool tensorIsNan = false; //-------------------------- std::vector<float> Loss(data_loader_size*epoch); //-------------------------- torch::optim::StepLR _scheduler(optimizer, 30, 1E-2); //-------------------------- for (size_t i = 0; i < epoch; ++i){ //-------------------------- progressbar bar(data_loader_size); //-------------------------- std::cout << "Training: "; //-------------------------- TimeIT _timer; //-------------------------- for (const auto& batch : *data_loader){ //-------------------------- bar.update(); //------------ Loss.push_back(network_train_batch(std::move(batch), optimizer, &tensorIsNan)); //-------------------------- if(tensorIsNan){ std::cout << "\n\x1b[33m\033[1mTensor is [nan]\033[0m\x1b[0m" << std::endl; break; }// end if(tensorIsNan) //-------------------------- }// end for (const auto& batch : *data_loader) //-------------------------- if(tensorIsNan){ break; }// end if(tensorIsNan) //-------------------------- _scheduler.step(); //-------------------------- auto printing_threads = std::async(std::launch::async, [&Loss, &data_loader_size, &_timer, this](){ //-------------------------- std::vector<float> _loss(data_loader_size); std::copy(std::execution::par_unseq, Loss.end()-data_loader_size, Loss.end(), _loss.begin()); loss_display(_loss, _timer.get_time_seconds()); //-------------------------- }); //-------------------------- }// end for (size_t i = 0; i < epoch; ++i) //-------------------------- return Loss; //-------------------------- }// end std::vector<float> network_train(Dataloader&& data_loader, torch::optim::Optimizer& optimizer, const size_t& epoch) //-------------------------- template <typename Dataloader, typename Validation_Dataloader, typename R> std::vector<float> network_train(Dataloader&& data_loader, Validation_Dataloader&& data_loader_validation, torch::optim::Optimizer& optimizer, const R& precision){ //-------------------------- double _element_sum{100}; //-------------------------- size_t _training_limiter{3}; //-------------------------- auto data_loader_size = std::distance(data_loader->begin(), data_loader->end()); //-------------------------- bool _learning{true}, tensorIsNan{false}; std::vector<double> _learning_elements; _learning_elements.reserve(_training_limiter); //-------------------------- std::vector<float> Loss; Loss.reserve(data_loader_size*_training_limiter); //-------------------------- torch::optim::StepLR _scheduler(optimizer, 30, 1E-2); //-------------------------- do{ //-------------------------- progressbar bar(data_loader_size); //-------------------------- std::cout << "Training: "; //-------------------------- TimeIT _timer; //-------------------------- for (const auto& batch : *data_loader){ //-------------------------- bar.update(); //------------ Loss.push_back(network_train_batch(std::move(batch), optimizer, &tensorIsNan)); //-------------------------- if(tensorIsNan){ std::cout << "\n\x1b[33m\033[1mTensor is [nan]\033[0m\x1b[0m" << std::endl; break; }// end if(tensorIsNan) //-------------------------- }// end for (const auto& batch : *data_loader) //-------------------------- _scheduler.step(); //-------------------------- auto validation_loss = network_validation(std::move(data_loader_validation)); //-------------------------- if (!validation_loss.empty()){ //-------------------------- _element_sum = 0.f; //-------------------------- for (const auto& _loss : validation_loss){ //-------------------------- _element_sum += _loss; //-------------------------- }// end for (const auto& _loss : validation_loss) //-------------------------- }// end if (!validation_loss.empty()) //-------------------------- _learning_elements.push_back(_element_sum); //-------------------------- auto printing_threads = std::async(std::launch::async, [&validation_loss, &_element_sum, &_timer, this](){ loss_display(validation_loss, _element_sum, _timer.get_time_seconds()); }); //-------------------------- if (_learning_elements.size() > (_training_limiter-1)){ //-------------------------- _learning = check_learning(_learning_elements, precision); _learning_elements.clear(); //-------------------------- printing_threads = std::async(std::launch::async, [&_learning](){ if(_learning){ printf("\n\x1b[32m\033[1m-----------------Learning:[True]-----------------\033[0m\x1b[0m\n"); }// end if(_learning) else{ printf("\n\x1b[36m\033[1m-----------------Learning:[False]-----------------\033[0m\x1b[0m\n"); }// end else }); //-------------------------- }// end if (_learning_elements.size > 2) //-------------------------- } while(_learning and !tensorIsNan); //-------------------------- return Loss; //-------------------------- }// end std::vector<float> network_train(Dataloader&& data_loader, Validation_Dataloader&& data_loader_validation, torch::optim::Optimizer& optimizer, const R& precision) //-------------------------- template <typename Dataset> std::vector<float> network_validation(Dataset&& data_loader){ //-------------------------- auto data_loader_size = std::distance(data_loader->begin(), data_loader->end()); //-------------------------- progressbar bar(data_loader_size); //-------------------------- std::vector<float> test_loss; test_loss.reserve(data_loader_size); //-------------------------- std::cout << "\nValidation: "; //-------------------------- for (const auto& batch : *data_loader){ //-------------------------- bar.update(); //------------ test_loss.push_back(network_validation_batch(std::move(batch))); //-------------------------- }// end for (const auto& batch : *data_loader) //-------------------------- return test_loss; //-------------------------- }// end std::vector<float> network_validation(Dataset&& data_loader) //-------------------------------------------------------------- template <typename Dataset> std::vector<std::tuple<torch::Tensor, torch::Tensor, float>> network_test(Dataset&& data_loader){ //-------------------------- auto data_loader_size = std::distance(data_loader->begin(), data_loader->end()); //-------------------------- progressbar bar(data_loader_size); //-------------------------- std::vector<std::tuple<torch::Tensor, torch::Tensor, float>> results; results.reserve(data_loader_size); //-------------------------- std::cout << "Test data: "; //-------------------------- for (const auto& batch : *data_loader){ //-------------------------- bar.update(); //------------ results.emplace_back(network_test_batch(std::move(batch))); //-------------------------- }// end for (const auto& batch : data_loader) //-------------------------- return results; //-------------------------- }// end std::vector<std::tuple<torch::Tensor, torch::Tensor, float>> network_test(Dataset&& data_loader) //-------------------------------------------------------------- private: //-------------------------- Network m_model; torch::Device m_device; //-------------------------- template <typename T, typename R> bool check_learning(const std::vector<T>& elements, const R& tolerance) const{ //-------------------------- long double average = std::reduce(std::execution::par_unseq, elements.begin(), elements.end(), 0.L) / elements.size(); //-------------------------- if (std::abs(average - elements.front()) <= tolerance){ return false; }// end std::abs(average - elements.front()) <= tolerance) //-------------------------- return true; //-------------------------- }// end bool check_learning(const std::vector<T>& elements, const R& tolerance) //-------------------------------------------------------------- template <typename T, typename R> void loss_display(const std::vector<T>& loss, const R& run_time) const{ //-------------------------- double elements_sum = std::reduce(std::execution::par_unseq, loss.begin(), loss.end(), 0.L); auto _max_element = std::max_element(std::execution::par_unseq, loss.begin(), loss.end()); auto _min_element = std::min_element(std::execution::par_unseq, loss.begin(), loss.end()); //-------------------------- fort::char_table table; //-------------------------- // Change border style //-------------------------- table.set_border_style(FT_NICE_STYLE); //-------------------------- table << fort::header << "Sum Loss" << "Min Position" << "Min loss" << "Max Position" << "Max loss" << "Execution time [s]" << fort::endr << elements_sum << std::distance(loss.begin(), _min_element) << *_min_element << std::distance(loss.begin(), _max_element) << *_max_element << run_time << fort::endr; //-------------------------- // Set center alignment for the 1st and 3rd columns //-------------------------- table.column(1).set_cell_text_align(fort::text_align::center); table.column(3).set_cell_text_align(fort::text_align::center); table.column(5).set_cell_text_align(fort::text_align::center); table.column(5).set_cell_content_fg_color(fort::color::red); //-------------------------- std::cout << "\n" << table.to_string() << std::endl; //-------------------------- }// end void loss_display(const std::vector<T>& loss, const R& ns_time) //-------------------------------------------------------------- template <typename T, typename D, typename R> void loss_display(const std::vector<T>& loss, const D& elements_sum, const R& run_time) const{ //-------------------------- auto _max_element = std::max_element(std::execution::par_unseq, loss.begin(), loss.end()); auto _min_element = std::min_element(std::execution::par_unseq, loss.begin(), loss.end()); //-------------------------- fort::char_table table; //-------------------------- // Change border style //-------------------------- table.set_border_style(FT_NICE_STYLE); //-------------------------- table << fort::header << "Loss Sum" << "Min Position" << "Min loss" << "Max Position" << "Max loss" << "Execution time [s]" << fort::endr << elements_sum << std::distance(loss.begin(), _min_element) << *_min_element << std::distance(loss.begin(), _max_element) << *_max_element << run_time << fort::endr; //-------------------------- // Set center alignment for the 1st and 3rd columns //-------------------------- table.column(1).set_cell_text_align(fort::text_align::center); table.column(3).set_cell_text_align(fort::text_align::center); table.column(5).set_cell_text_align(fort::text_align::center); table.column(5).set_cell_content_fg_color(fort::color::red); //-------------------------- std::cout << "\n" << table.to_string() << std::endl; //-------------------------- }// end void loss_display(const std::vector<T>& loss, const D& elements_sum, const R& ns_time) //-------------------------------------------------------------- }; //--------------------------------------------------------------
53.025172
178
0.396038
[ "vector", "model" ]
ff0ac530d63a8d1ea1693aa524a6d5b5227f3639
54,083
cpp
C++
tests/das_tests/daspay_tests.cpp
powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
1
2021-07-26T02:42:01.000Z
2021-07-26T02:42:01.000Z
tests/das_tests/daspay_tests.cpp
green-powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
null
null
null
tests/das_tests/daspay_tests.cpp
green-powerchain-ltd/greenpower-blockchain
ff04c37f2de11677c3a34889fdede1256a3e5e02
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2018 Tech Solutions Malta LTD * * 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 <boost/test/unit_test.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/access_layer.hpp> #include <graphene/chain/exceptions.hpp> #include <graphene/chain/daspay_object.hpp> #include <graphene/chain/market_object.hpp> #include "../common/database_fixture.hpp" using namespace graphene::chain; using namespace graphene::chain::test; BOOST_FIXTURE_TEST_SUITE( dascoin_tests, database_fixture ) BOOST_FIXTURE_TEST_SUITE( daspay_tests, database_fixture ) BOOST_AUTO_TEST_CASE( set_daspay_transaction_ratio_test ) { try { // Try to set daspay transaction ratio by using the wrong authority: GRAPHENE_REQUIRE_THROW( do_op(set_daspay_transaction_ratio_operation(get_pi_validator_id(), 150, 130)), fc::exception ); // Try to set daspay transaction ratio with debit and credit ratio illegal (< 10000): GRAPHENE_REQUIRE_THROW( do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 10000, 10000)), fc::exception ); do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 150, 130)); auto daspay_debit_transaction_ratio = db.get_dynamic_global_properties().daspay_debit_transaction_ratio; auto daspay_credit_transaction_ratio = db.get_dynamic_global_properties().daspay_credit_transaction_ratio; BOOST_CHECK_EQUAL( daspay_debit_transaction_ratio.value, 150 ); BOOST_CHECK_EQUAL( daspay_credit_transaction_ratio.value, 130 ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( das_payment_service_provider_test ) { try { // Check for empty payment service providers BOOST_CHECK_EQUAL(get_payment_service_providers().size(), 0); // Create two clearing accounts and one provider account ACTORS((provideraccount)(clearingaccount1)(clearingaccount2)); VAULT_ACTOR(foo); vector<account_id_type> v; // Require throw (empty clearing_accounts) GRAPHENE_REQUIRE_THROW(do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), provideraccount_id, v)), fc::exception ); v.emplace_back( clearingaccount1_id ); v.emplace_back( clearingaccount2_id ); // Require throw (wrong authority) GRAPHENE_REQUIRE_THROW(do_op(create_payment_service_provider_operation(get_pi_validator_id(), provideraccount_id, v)), fc::exception ); // Payment service provider create do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), provideraccount_id, v)); // Check if providers size is 1 BOOST_CHECK_EQUAL(get_payment_service_providers().size(), 1); FC_ASSERT(get_payment_service_providers()[0].payment_service_provider_account == provideraccount_id); FC_ASSERT(get_payment_service_providers()[0].payment_service_provider_clearing_accounts == v); // Payment service provider delete do_op(delete_payment_service_provider_operation(get_daspay_administrator_id(), provideraccount_id)); BOOST_CHECK_EQUAL(get_payment_service_providers().size(), 0); do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), provideraccount_id, v)); BOOST_CHECK_EQUAL(get_payment_service_providers().size(), 1); // Remove one clearing account v.erase(std::remove(v.begin(), v.end(), clearingaccount2_id), v.end()); BOOST_CHECK_EQUAL(v.size(), 1); // Fails: payment service provider must be a wallet: GRAPHENE_REQUIRE_THROW( do_op(update_payment_service_provider_operation(get_daspay_administrator_id(), foo_id, v)), fc::exception ); // Payment service provider update (new clearing_accounts) do_op(update_payment_service_provider_operation(get_daspay_administrator_id(), provideraccount_id, v)); FC_ASSERT(get_payment_service_providers()[0].payment_service_provider_clearing_accounts.size() == 1); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_authority_index_test ) { try { VAULT_ACTORS((foo)(bar)); ACTORS((wa1)(wa2)); db.create<daspay_authority_object>([&](daspay_authority_object& dao){ dao.daspay_user = foo_id; dao.payment_provider = wa1_id; }); // This will fail - the same user cannot register the same payment provider twice GRAPHENE_REQUIRE_THROW( db.create<daspay_authority_object>([&](daspay_authority_object& dao){ dao.daspay_user = foo_id; dao.payment_provider = wa1_id; }), fc::exception ); // Success - different payment provider db.create<daspay_authority_object>([&](daspay_authority_object& dao){ dao.daspay_user = foo_id; dao.payment_provider = wa2_id; }); // Success - different user db.create<daspay_authority_object>([&](daspay_authority_object& dao){ dao.daspay_user = bar_id; dao.payment_provider = wa1_id; }); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( delayed_operations_index_test ) { try { ACTORS((wa1)(wa2)); db.create<delayed_operation_object>([&](delayed_operation_object& dlo){ dlo.account = wa1_id; dlo.issued_time = db.head_block_time(); dlo.op = unreserve_asset_on_account_operation{wa1_id, asset{ 0, db.get_dascoin_asset_id() } }; }); // Fails: cannot create delayed operation of the same type GRAPHENE_REQUIRE_THROW( db.create<delayed_operation_object>([&](delayed_operation_object& dlo){ dlo.account = wa1_id; dlo.issued_time = db.head_block_time(); dlo.op = unreserve_asset_on_account_operation{wa1_id, asset{ 0, db.get_dascoin_asset_id() } }; }), fc::exception ); // Success: different operation db.create<delayed_operation_object>([&](delayed_operation_object& dlo){ dlo.account = wa1_id; dlo.issued_time = db.head_block_time(); dlo.op = reserve_asset_on_account_operation{wa1_id, asset{ 0, db.get_dascoin_asset_id() } }; }); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( register_daspay_authority_test ) { try { ACTORS((foo)(bar)(foobar)(payment)); public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); const auto& root_id = db.get_global_properties().authorities.daspay_administrator; // Cannot register because payment provider is not registered: GRAPHENE_REQUIRE_THROW( do_op(register_daspay_authority_operation(foo_id, bar_id, pk, {})), fc::exception ); vector<account_id_type> v{foo_id, bar_id}; do_op(create_payment_service_provider_operation(root_id, payment_id, v)); do_op(create_payment_service_provider_operation(root_id, foobar_id, v)); // Success - payment provider registered do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})); // This fails - payment provider already set: GRAPHENE_REQUIRE_THROW( do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})), fc::exception ); // This works - payment provider is different: do_op(register_daspay_authority_operation(foo_id, foobar_id, pk, {})); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( unregister_daspay_authority_test ) { try { ACTORS((foo)(bar)(foobar)); public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); // This fails - none registered: GRAPHENE_REQUIRE_THROW( do_op(unregister_daspay_authority_operation(foo_id, bar_id)), fc::exception ); const auto& root_id = db.get_global_properties().authorities.daspay_administrator; vector<account_id_type> v{foo_id, bar_id}; do_op(create_payment_service_provider_operation(root_id, bar_id, v)); do_op(register_daspay_authority_operation(foo_id, bar_id, pk, {})); // This fails - not registered: GRAPHENE_REQUIRE_THROW( do_op(unregister_daspay_authority_operation(foo_id, foobar_id)), fc::exception ); // Success: do_op(unregister_daspay_authority_operation(foo_id, bar_id)); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( reserve_asset_on_account_test ) { try { ACTOR(foo); VAULT_ACTOR(bar); tether_accounts(foo_id, bar_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); BOOST_CHECK_EQUAL( get_balance(bar_id, get_dascoin_asset_id()), 605 * DASCOIN_DEFAULT_ASSET_PRECISION ); // Fails: only dascoin can be reserved: GRAPHENE_REQUIRE_THROW( do_op(reserve_asset_on_account_operation(foo_id, asset{ 10, db.get_web_asset_id() })), fc::exception ); // Fails: cannot reserve 0 dascoins: GRAPHENE_REQUIRE_THROW( do_op(reserve_asset_on_account_operation(foo_id, asset{ 0, db.get_dascoin_asset_id() })), fc::exception ); // Fails: cannot reserve 0.0001 dascoins, since balance is 0: GRAPHENE_REQUIRE_THROW( do_op(reserve_asset_on_account_operation(foo_id, asset{ 10, db.get_dascoin_asset_id() })), fc::exception ); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 100 * DASCOIN_DEFAULT_ASSET_PRECISION); BOOST_CHECK_EQUAL( get_balance(foo_id, get_dascoin_asset_id()), 100 * DASCOIN_DEFAULT_ASSET_PRECISION ); // Fails: only 100 dascoin on balance: GRAPHENE_REQUIRE_THROW( do_op(reserve_asset_on_account_operation(foo_id, asset{ 101 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })), fc::exception ); // Success: do_op(reserve_asset_on_account_operation(foo_id, asset{ 50 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); BOOST_CHECK_EQUAL( get_balance(foo_id, get_dascoin_asset_id()), 50 * DASCOIN_DEFAULT_ASSET_PRECISION ); BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), 50 * DASCOIN_DEFAULT_ASSET_PRECISION ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( unreserve_asset_on_account_test ) { try { ACTOR(foo); VAULT_ACTOR(bar); tether_accounts(foo_id, bar_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); BOOST_CHECK_EQUAL( get_balance(bar_id, get_dascoin_asset_id()), 605 * DASCOIN_DEFAULT_ASSET_PRECISION ); // Fails: delayed operations resolver is not running: GRAPHENE_REQUIRE_THROW( do_op(unreserve_asset_on_account_operation(foo_id, asset{ 10 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })), fc::exception ); do_op(update_delayed_operations_resolver_parameters_operation(db.get_global_properties().authorities.root_administrator, true, 600)); // Fails: only dascoin can be unreserved: GRAPHENE_REQUIRE_THROW( do_op(unreserve_asset_on_account_operation(foo_id, asset{ 10, db.get_web_asset_id() })), fc::exception ); // Fails: cannot unreserve 0 dascoins: GRAPHENE_REQUIRE_THROW( do_op(unreserve_asset_on_account_operation(foo_id, asset{ 0, db.get_dascoin_asset_id() })), fc::exception ); // Fails: cannot unreserve 0.0001 dascoins, since reserved balance is 0: GRAPHENE_REQUIRE_THROW( do_op(unreserve_asset_on_account_operation(foo_id, asset{ 10, db.get_dascoin_asset_id() })), fc::exception ); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 100 * DASCOIN_DEFAULT_ASSET_PRECISION); // Reserve 50: do_op(reserve_asset_on_account_operation(foo_id, asset{ 50 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); // Fails: cannot unreserve 60 dascoins, since reserved balance is 50: GRAPHENE_REQUIRE_THROW( do_op(unreserve_asset_on_account_operation(foo_id, asset{ 60 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })), fc::exception ); do_op(unreserve_asset_on_account_operation(foo_id, asset{ 10 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); // Fails: cannot issue another unreserve operation before the first one is resolved: GRAPHENE_REQUIRE_THROW( do_op(unreserve_asset_on_account_operation(foo_id, asset{ 10 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })), fc::exception ); // Unreserve resolver is not working, so no change on the balance: BOOST_CHECK_EQUAL( get_balance(foo_id, get_dascoin_asset_id()), 50 * DASCOIN_DEFAULT_ASSET_PRECISION ); BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), 50 * DASCOIN_DEFAULT_ASSET_PRECISION ); // Wait for delayed operations resolver to kick in: generate_blocks(db.head_block_time() + fc::seconds(660)); auto history = get_operation_history( foo_id ); BOOST_CHECK( !history.empty() ); // unreserve_completed should be on top: unreserve_completed_operation op = history[0].op.get<unreserve_completed_operation>(); BOOST_CHECK_EQUAL ( op.asset_to_unreserve.amount.value, asset( 10 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() ).amount.value ); BOOST_CHECK_EQUAL( get_balance(foo_id, get_dascoin_asset_id()), 60 * DASCOIN_DEFAULT_ASSET_PRECISION ); BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), 40 * DASCOIN_DEFAULT_ASSET_PRECISION ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_debit_test ) { try { ACTORS((foo)(clearing1)(payment1)(clearing2)(payment2)(foobar)); VAULT_ACTOR(bar); tether_accounts(foo_id, bar_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); public_key_type pk1 = public_key_type(generate_private_key("foo").get_public_key()); vector<account_id_type> v1{clearing1_id}; // Fails: only web euro can be used to debit: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{0, db.get_dascoin_asset_id()}, clearing1_id, "", {})), fc::exception ); // Fails: service provider not found: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(bar_id, pk1, foo_id, asset{0, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), payment1_id, v1)); // Fails: user has not enabled daspay: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{1, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); do_op(register_daspay_authority_operation(foo_id, payment1_id, pk1, {})); // Fails: clearing account not found: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{1, db.get_web_asset_id()}, foo_id, "", {})), fc::exception ); // Fails: cannot debit vault account: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk1, bar_id, asset{1, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); // Fails: no funds on user account: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{1, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 600 * DASCOIN_DEFAULT_ASSET_PRECISION); do_op(reserve_asset_on_account_operation(foo_id, asset{ 600 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); public_key_type pk2 = public_key_type(generate_private_key("foo2").get_public_key()); // Fails: wrong key used: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk2, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); // Set debit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 200, 0)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); // Fails: cannot debit negative amount: GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{-1, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); // Success, we can debit 0 amount: do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{0, db.get_web_asset_id()}, clearing1_id, "", {})); issue_webasset("1", foobar_id, 1 * DASCOIN_FIAT_ASSET_PRECISION, 0); do_op(limit_order_create_operation(foobar_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Debit one web euro: do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing1_id, "", {})); const auto& dgpo = db.get_dynamic_global_properties(); share_type debit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; debit_amount_with_fee += debit_amount_with_fee * db.get_dynamic_global_properties().daspay_debit_transaction_ratio / 10000; const auto& debit_amount = asset{debit_amount_with_fee, db.get_web_asset_id()} * dgpo.last_dascoin_price; BOOST_CHECK_EQUAL( get_dascoin_balance(clearing1_id), debit_amount.amount.value ); vector<account_id_type> v2{clearing2_id}; do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), payment2_id, v2)); do_op(register_daspay_authority_operation(foo_id, payment2_id, pk2, {})); do_op(daspay_debit_account_operation(payment2_id, pk2, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing2_id, "", {})); BOOST_CHECK_EQUAL( get_dascoin_balance(clearing2_id), debit_amount.amount.value ); // Fails: wrong key used (pk2 is registered with payment2_id): GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk2, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_credit_test ) { try { ACTORS((foo)(clearing)(payment)(payment2)(foobar)); VAULT_ACTORS((bar)(foobar2)); tether_accounts(clearing_id, bar_id); tether_accounts(foobar_id, foobar2_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); // Fails: cannot credit 0 amount GRAPHENE_REQUIRE_THROW( do_op(daspay_credit_account_operation(bar_id, foo_id, asset{0, db.get_dascoin_asset_id()}, foo_id, "", {})), fc::exception ); // Fails: only web euro can be used to credit: GRAPHENE_REQUIRE_THROW( do_op(daspay_credit_account_operation(bar_id, foo_id, asset{1, db.get_dascoin_asset_id()}, foo_id, "", {})), fc::exception ); // Fails: service provider not found: GRAPHENE_REQUIRE_THROW( do_op(daspay_credit_account_operation(bar_id, foo_id, asset{1, db.get_web_asset_id()}, foo_id, "", {})), fc::exception ); vector<account_id_type> v{clearing_id}; const auto& root_id = db.get_global_properties().authorities.daspay_administrator; public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); do_op(create_payment_service_provider_operation(root_id, payment_id, v)); do_op(create_payment_service_provider_operation(root_id, payment2_id, v)); do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})); // Fails: clearing account not found: GRAPHENE_REQUIRE_THROW( do_op(daspay_credit_account_operation(payment_id, foo_id, asset{1, db.get_web_asset_id()}, foo_id, "", {})), fc::exception ); // Fails: cannot credit vault account: GRAPHENE_REQUIRE_THROW( do_op(daspay_credit_account_operation(payment_id, bar_id, asset{1, db.get_web_asset_id()}, clearing_id, "", {})), fc::exception ); // Fails: no funds on clearing account: GRAPHENE_REQUIRE_THROW( do_op(daspay_credit_account_operation(payment_id, foo_id, asset{1, db.get_web_asset_id()}, clearing_id, "", {})), fc::exception ); transfer_dascoin_vault_to_wallet(bar_id, clearing_id, 200 * DASCOIN_DEFAULT_ASSET_PRECISION); // Set credit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 0, 200)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); issue_dascoin(foobar2_id, 1000); disable_vault_to_wallet_limit(foobar2_id); transfer_dascoin_vault_to_wallet(foobar2_id, foobar_id, 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); do_op(limit_order_create_operation(foobar_id, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Credit one web euro: do_op(daspay_credit_account_operation(payment_id, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); const auto& dgpo = db.get_dynamic_global_properties(); share_type credit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; credit_amount_with_fee += credit_amount_with_fee * db.get_dynamic_global_properties().daspay_credit_transaction_ratio / 10000; const auto& credit_amount = asset{credit_amount_with_fee, db.get_web_asset_id()} * dgpo.last_dascoin_price; BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), credit_amount.amount.value ); // Fails: use has not enabled payment2 as a payment provider: GRAPHENE_REQUIRE_THROW( do_op(daspay_credit_account_operation(payment2_id, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})), fc::exception ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( update_daspay_clearing_parameters_unit_test ) { try { do_op(update_daspay_clearing_parameters_operation(get_daspay_administrator_id(), {true}, {600}, {90000 * DASCOIN_FIAT_ASSET_PRECISION}, {250000 * DASCOIN_DEFAULT_ASSET_PRECISION})); const auto& daspay_params = get_daspay_parameters(); BOOST_CHECK_EQUAL( daspay_params.clearing_enabled, true ); BOOST_CHECK_EQUAL( daspay_params.clearing_interval_time_seconds, 600 ); BOOST_CHECK_EQUAL( daspay_params.collateral_dascoin.value, 90000 * DASCOIN_FIAT_ASSET_PRECISION ); BOOST_CHECK_EQUAL( daspay_params.collateral_webeur.value, 250000 * DASCOIN_DEFAULT_ASSET_PRECISION ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_clearing_test ) { try { ACTORS((foo)(clearing)(payment)(buyer)); VAULT_ACTORS((bar)(foobar)); tether_accounts(foo_id, bar_id); tether_accounts(clearing_id, foobar_id); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); db.adjust_balance_limit(foobar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); issue_dascoin(bar_id, 1000); issue_dascoin(foobar_id, 500); vector<account_id_type> v{clearing_id}; const auto& root_id = db.get_global_properties().authorities.daspay_administrator; public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); do_op(create_payment_service_provider_operation(root_id, payment_id, v)); do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})); generate_blocks(HARDFORK_FIX_DASPAY_PRICE_TIME); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); db.adjust_balance_limit(foobar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 200 * DASCOIN_DEFAULT_ASSET_PRECISION); transfer_dascoin_vault_to_wallet(foobar_id, clearing_id, 200 * DASCOIN_DEFAULT_ASSET_PRECISION); do_op(reserve_asset_on_account_operation(foo_id, asset{ 200 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); // Set debit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 200, 0)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); issue_webasset("1", buyer_id, 1 * DASCOIN_FIAT_ASSET_PRECISION, 0); do_op(limit_order_create_operation(buyer_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Debit one web euro: do_op(daspay_debit_account_operation(payment_id, pk, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); // Since price is 100 dasc for 1 web eur and transaction ratio is 2.0%, we took 102 dasc from foo's reserved balance: BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), 98 * DASCOIN_DEFAULT_ASSET_PRECISION ); const auto& limit_order_idx = db.get_index_type<limit_order_index>(); const auto& limit_price_idx = limit_order_idx.indices().get<by_price>(); // One limit order at this point: BOOST_CHECK_EQUAL( limit_price_idx.size(), 1 ); // Enable daspay clearing: do_op(update_daspay_clearing_parameters_operation(get_daspay_administrator_id(), true, 12, {}, {})); // Wait for the next clearing interval: generate_blocks(db.head_block_time() + fc::seconds(18)); // No limit orders because a match has been made: BOOST_CHECK_EQUAL( limit_price_idx.size(), 0 ); issue_webasset("2", foo_id, 100 * DASCOIN_FIAT_ASSET_PRECISION, 0); do_op(limit_order_create_operation(foo_id, asset{10 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Wait for the next clearing interval: generate_blocks(db.head_block_time() + fc::seconds(18)); auto history = get_operation_history(foo_id); BOOST_CHECK( !history.empty() ); fill_order_operation fo = history[0].op.get<fill_order_operation>(); BOOST_CHECK( fo.account_id == foo_id ); BOOST_CHECK( fo.fill_price == price(asset(10 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()), asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()))); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_clearing2_test ) { try { ACTORS((foo)(clearing)(payment)); VAULT_ACTORS((bar)(foobar)); tether_accounts(foo_id, bar_id); tether_accounts(clearing_id, foobar_id); vector<account_id_type> v{clearing_id}; const auto& root_id = db.get_global_properties().authorities.daspay_administrator; public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); do_op(create_payment_service_provider_operation(root_id, payment_id, v)); do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})); issue_dascoin(bar_id, 1000); issue_dascoin(foobar_id, 500); generate_blocks(HARDFORK_FIX_DASPAY_PRICE_TIME); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); db.adjust_balance_limit(foobar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); transfer_dascoin_vault_to_wallet(foobar_id, clearing_id, 500 * DASCOIN_DEFAULT_ASSET_PRECISION); issue_webasset("1", clearing_id, 100 * DASCOIN_FIAT_ASSET_PRECISION, 0); // Set huge dasc collateral so no sells will be made: do_op(update_daspay_clearing_parameters_operation(get_daspay_administrator_id(), {}, {}, 1000 * DASCOIN_DEFAULT_ASSET_PRECISION, {})); do_op(limit_order_create_operation(foo_id, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, asset{10 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); BOOST_CHECK_EQUAL( get_balance(clearing_id, get_dascoin_asset_id()), 500 * DASCOIN_DEFAULT_ASSET_PRECISION ); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); // Return 1 web euro back: do_op(daspay_credit_account_operation(payment_id, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); // 10 dascoins were returned, 490 left: BOOST_CHECK_EQUAL( get_balance(clearing_id, get_dascoin_asset_id()), 490 * DASCOIN_DEFAULT_ASSET_PRECISION ); // Set huge dasc collateral so no sells will be made: do_op(update_daspay_clearing_parameters_operation(get_daspay_administrator_id(), true, {}, {}, {})); // Wait for the next clearing interval: generate_blocks(db.head_block_time() + fc::seconds(12)); const auto& limit_order_idx = db.get_index_type<limit_order_index>(); const auto& limit_price_idx = limit_order_idx.indices().get<by_price>(); // At this point there should be one limit order: BOOST_CHECK_EQUAL( limit_price_idx.size(), 1 ); const auto& loo = *(limit_price_idx.begin()); // Seller is clearing account: BOOST_CHECK( loo.seller == clearing_id ); // Price is 10 cents, so we are selling 51 euros for 510 dascoins (remember, collateral is 1000 dascoins): BOOST_CHECK_EQUAL( loo.sell_price.base.amount.value, 51 * DASCOIN_FIAT_ASSET_PRECISION ); BOOST_CHECK_EQUAL( loo.sell_price.quote.amount.value, 510 * DASCOIN_DEFAULT_ASSET_PRECISION ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_clearing3_test ) { try { ACTORS((foo)(clearing)(payment)(buyer)); VAULT_ACTORS((bar)(foobar)); tether_accounts(foo_id, bar_id); tether_accounts(clearing_id, foobar_id); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); db.adjust_balance_limit(foobar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); issue_dascoin(bar_id, 1000); issue_dascoin(foobar_id, 500); generate_blocks(HARDFORK_FIX_DASPAY_PRICE_TIME); vector<account_id_type> v{clearing_id}; const auto& root_id = db.get_global_properties().authorities.daspay_administrator; public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); do_op(create_payment_service_provider_operation(root_id, payment_id, v)); do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); db.adjust_balance_limit(foobar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 200 * DASCOIN_DEFAULT_ASSET_PRECISION); transfer_dascoin_vault_to_wallet(foobar_id, clearing_id, 200 * DASCOIN_DEFAULT_ASSET_PRECISION); do_op(reserve_asset_on_account_operation(foo_id, asset{ 200 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); // Set debit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 200, 0)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); issue_webasset("1", buyer_id, 1 * DASCOIN_FIAT_ASSET_PRECISION, 0); do_op(limit_order_create_operation(buyer_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Debit one web euro: do_op(daspay_debit_account_operation(payment_id, pk, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); // Since price is 100 dasc for 1 web eur and transaction ratio is 2.0%, we took 102 dasc from foo's reserved balance: BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), 98 * DASCOIN_DEFAULT_ASSET_PRECISION ); const auto& limit_order_idx = db.get_index_type<limit_order_index>(); const auto& limit_price_idx = limit_order_idx.indices().get<by_price>(); // One limit order at this point: BOOST_CHECK_EQUAL( limit_price_idx.size(), 1 ); // Enable daspay clearing: do_op(update_daspay_clearing_parameters_operation(get_daspay_administrator_id(), true, 12, {}, {})); // Wait for the next clearing interval: generate_blocks(db.head_block_time() + fc::seconds(18)); // No limit orders because a match has been made: BOOST_CHECK_EQUAL( limit_price_idx.size(), 0 ); issue_webasset("2", foo_id, 100 * DASCOIN_FIAT_ASSET_PRECISION, 0); do_op(limit_order_create_operation(foo_id, asset{10 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Wait for the next clearing interval: generate_blocks(db.head_block_time() + fc::seconds(18)); auto history = get_operation_history(foo_id); BOOST_CHECK( !history.empty() ); fill_order_operation fo = history[0].op.get<fill_order_operation>(); BOOST_CHECK( fo.account_id == foo_id ); BOOST_CHECK( fo.fill_price == price(asset(10 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()), asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()))); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( update_delayed_operations_resolver_parameters_unit_test ) { try { do_op(update_delayed_operations_resolver_parameters_operation(db.get_global_properties().authorities.root_administrator, {true}, {600})); BOOST_CHECK_EQUAL( db.get_global_properties().delayed_operations_resolver_enabled, true ); BOOST_CHECK_EQUAL( db.get_global_properties().delayed_operations_resolver_interval_time_seconds, 600 ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_use_external_price_debit_test ) { try { ACTORS((foo)(clearing1)(payment1)(clearing2)(payment2)(foobar)); VAULT_ACTOR(bar); tether_accounts(foo_id, bar_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); public_key_type pk1 = public_key_type(generate_private_key("foo").get_public_key()); vector<account_id_type> v1{clearing1_id}; do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), payment1_id, v1)); do_op(register_daspay_authority_operation(foo_id, payment1_id, pk1, {})); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 600 * DASCOIN_DEFAULT_ASSET_PRECISION); do_op(reserve_asset_on_account_operation(foo_id, asset{ 600 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); generate_blocks(HARDFORK_FIX_DASPAY_PRICE_TIME); public_key_type pk2 = public_key_type(generate_private_key("foo2").get_public_key()); // Set debit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 200, 0)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); // make limit order => price is 1we for 100dasc issue_webasset("1", foobar_id, 1 * DASCOIN_FIAT_ASSET_PRECISION, 0); do_op(limit_order_create_operation(foobar_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Debit one web euro: do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing1_id, "", {})); const auto& dgpo = db.get_dynamic_global_properties(); share_type debit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; debit_amount_with_fee += debit_amount_with_fee * db.get_dynamic_global_properties().daspay_debit_transaction_ratio / 10000; const auto& debit_amount = asset{debit_amount_with_fee, db.get_web_asset_id()} * dgpo.last_dascoin_price; // Expect one hundred dasc plus fee BOOST_CHECK_EQUAL( get_dascoin_balance(clearing1_id), debit_amount.amount.value ); // Set external price to 1we for 5dasc auto op = update_external_token_price_operation(); op.issuer = get_webasset_issuer_id(); op.token_id = get_dascoin_asset_id(); price external_price = asset(5 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()); op.eur_amount_per_token = external_price; do_op(op); // Set daspay to use external price for dasc flat_set<asset_id_type> tokens; tokens.insert(get_dascoin_asset_id()); do_op(daspay_set_use_external_token_price_operation(get_daspay_administrator_id(), tokens)); vector<account_id_type> v2{clearing2_id}; do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), payment2_id, v2)); do_op(register_daspay_authority_operation(foo_id, payment2_id, pk2, {})); // Debit one euro do_op(daspay_debit_account_operation(payment2_id, pk2, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing2_id, "", {})); debit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; debit_amount_with_fee += debit_amount_with_fee * db.get_dynamic_global_properties().daspay_debit_transaction_ratio / 10000; const auto& debit_amount2 = asset{debit_amount_with_fee, db.get_web_asset_id()} * external_price; // Expect one dasc plus fee BOOST_CHECK_EQUAL( get_dascoin_balance(clearing2_id), debit_amount2.amount.value ); // Fails: wrong key used (pk2 is registered with payment2_id): GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk2, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_use_external_price_credit_test ) { try { ACTORS((foo)(foo2)(clearing)(payment)(payment2)(foobar)); VAULT_ACTORS((bar)(foobar2)); tether_accounts(clearing_id, bar_id); tether_accounts(foobar_id, foobar2_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); vector<account_id_type> v{clearing_id}; const auto& root_id = db.get_global_properties().authorities.daspay_administrator; public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); do_op(create_payment_service_provider_operation(root_id, payment_id, v)); do_op(create_payment_service_provider_operation(root_id, payment2_id, v)); do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})); do_op(register_daspay_authority_operation(foo2_id, payment_id, pk, {})); transfer_dascoin_vault_to_wallet(bar_id, clearing_id, 200 * DASCOIN_DEFAULT_ASSET_PRECISION); // Set credit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 0, 200)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); issue_dascoin(foobar2_id, 1000); disable_vault_to_wallet_limit(foobar2_id); transfer_dascoin_vault_to_wallet(foobar2_id, foobar_id, 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); generate_blocks(HARDFORK_FIX_DASPAY_PRICE_TIME); do_op(limit_order_create_operation(foobar_id, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Credit one web euro: do_op(daspay_credit_account_operation(payment_id, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); const auto& dgpo = db.get_dynamic_global_properties(); share_type credit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; credit_amount_with_fee += credit_amount_with_fee * db.get_dynamic_global_properties().daspay_credit_transaction_ratio / 10000; const auto& credit_amount = asset{credit_amount_with_fee, db.get_web_asset_id()} * dgpo.last_dascoin_price; BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), credit_amount.amount.value ); // Set external price to 1we for 5dasc auto op = update_external_token_price_operation(); op.issuer = get_webasset_issuer_id(); op.token_id = get_dascoin_asset_id(); price external_price = asset(5 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()); op.eur_amount_per_token = external_price; do_op(op); // Set daspay to use external price for dasc flat_set<asset_id_type> tokens; tokens.insert(get_dascoin_asset_id()); do_op(daspay_set_use_external_token_price_operation(get_daspay_administrator_id(), tokens)); // Credit one web euro: do_op(daspay_credit_account_operation(payment_id, foo2_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); credit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; credit_amount_with_fee += credit_amount_with_fee * db.get_dynamic_global_properties().daspay_credit_transaction_ratio / 10000; const auto& credit_amount2 = asset{credit_amount_with_fee, db.get_web_asset_id()} * external_price; BOOST_CHECK_EQUAL( get_reserved_balance(foo2_id, get_dascoin_asset_id()), credit_amount2.amount.value ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_price_override_debit_test ) { try { ACTORS((foo)(clearing1)(payment1)(clearing2)(payment2)(foobar)); VAULT_ACTOR(bar); tether_accounts(foo_id, bar_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); public_key_type pk1 = public_key_type(generate_private_key("foo").get_public_key()); vector<account_id_type> v1{clearing1_id}; do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), payment1_id, v1)); do_op(register_daspay_authority_operation(foo_id, payment1_id, pk1, {})); transfer_dascoin_vault_to_wallet(bar_id, foo_id, 600 * DASCOIN_DEFAULT_ASSET_PRECISION); do_op(reserve_asset_on_account_operation(foo_id, asset{ 600 * DASCOIN_DEFAULT_ASSET_PRECISION, db.get_dascoin_asset_id() })); generate_blocks(HARDFORK_FIX_DASPAY_PRICE_TIME); public_key_type pk2 = public_key_type(generate_private_key("foo2").get_public_key()); // Set debit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 200, 0)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); // make limit order => price is 1we for 100dasc issue_webasset("1", foobar_id, 1 * DASCOIN_FIAT_ASSET_PRECISION, 0); do_op(limit_order_create_operation(foobar_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Debit one web euro: do_op(daspay_debit_account_operation(payment1_id, pk1, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing1_id, "", {})); const auto& dgpo = db.get_dynamic_global_properties(); share_type debit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; debit_amount_with_fee += debit_amount_with_fee * db.get_dynamic_global_properties().daspay_debit_transaction_ratio / 10000; const auto& debit_amount = asset{debit_amount_with_fee, db.get_web_asset_id()} * dgpo.last_dascoin_price; // Expect one hundred dasc plus fee BOOST_CHECK_EQUAL( get_dascoin_balance(clearing1_id), debit_amount.amount.value ); // Set price override for daspay to 0.2eur for 1dasc price override_price = asset(5 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()); map<asset_id_type, price> price_overrides; price_overrides[get_dascoin_asset_id()] = override_price; update_daspay_clearing_parameters_operation update_op; update_op.authority = get_das33_administrator_id(); update_op.extensions.insert(price_overrides); do_op(update_op); vector<account_id_type> v2{clearing2_id}; do_op(create_payment_service_provider_operation(get_daspay_administrator_id(), payment2_id, v2)); do_op(register_daspay_authority_operation(foo_id, payment2_id, pk2, {})); // Debit one euro do_op(daspay_debit_account_operation(payment2_id, pk2, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing2_id, "", {})); debit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; debit_amount_with_fee += debit_amount_with_fee * db.get_dynamic_global_properties().daspay_debit_transaction_ratio / 10000; const auto& debit_amount2 = asset{debit_amount_with_fee, db.get_web_asset_id()} * override_price; // Expect one dasc plus fee BOOST_CHECK_EQUAL( get_dascoin_balance(clearing2_id), debit_amount2.amount.value ); // Fails: wrong key used (pk2 is registered with payment2_id): GRAPHENE_REQUIRE_THROW( do_op(daspay_debit_account_operation(payment1_id, pk2, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing1_id, "", {})), fc::exception ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( daspay_price_override_credit_test ) { try { ACTORS((foo)(foo2)(clearing)(payment)(payment2)(foobar)); VAULT_ACTORS((bar)(foobar2)); tether_accounts(clearing_id, bar_id); tether_accounts(foobar_id, foobar2_id); auto lic_typ = *(_dal.get_license_type("standard_charter")); do_op(issue_license_operation(get_license_issuer_id(), bar_id, lic_typ.id, 10, 200, db.head_block_time())); toggle_reward_queue(true); generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); db.adjust_balance_limit(bar, get_dascoin_asset_id(), 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); // Generate some coins: adjust_dascoin_reward(500 * DASCOIN_DEFAULT_ASSET_PRECISION); adjust_frequency(200); // Wait for the coins to be distributed: generate_blocks(db.head_block_time() + fc::seconds(get_chain_parameters().reward_interval_time_seconds)); vector<account_id_type> v{clearing_id}; const auto& root_id = db.get_global_properties().authorities.daspay_administrator; public_key_type pk = public_key_type(generate_private_key("foo").get_public_key()); do_op(create_payment_service_provider_operation(root_id, payment_id, v)); do_op(create_payment_service_provider_operation(root_id, payment2_id, v)); do_op(register_daspay_authority_operation(foo_id, payment_id, pk, {})); do_op(register_daspay_authority_operation(foo2_id, payment_id, pk, {})); transfer_dascoin_vault_to_wallet(bar_id, clearing_id, 200 * DASCOIN_DEFAULT_ASSET_PRECISION); // Set credit transaction ratio to 2.0% do_op(set_daspay_transaction_ratio_operation(get_daspay_administrator_id(), 0, 200)); // Set price to 1we -> 100dasc set_last_dascoin_price(asset(100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id())); issue_dascoin(foobar2_id, 1000); disable_vault_to_wallet_limit(foobar2_id); transfer_dascoin_vault_to_wallet(foobar2_id, foobar_id, 1000 * DASCOIN_DEFAULT_ASSET_PRECISION); generate_blocks(HARDFORK_FIX_DASPAY_PRICE_TIME); do_op(limit_order_create_operation(foobar_id, asset{100 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()}, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()}, 0, {}, db.head_block_time() + fc::seconds(600))); // Credit one web euro: do_op(daspay_credit_account_operation(payment_id, foo_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); const auto& dgpo = db.get_dynamic_global_properties(); share_type credit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; credit_amount_with_fee += credit_amount_with_fee * db.get_dynamic_global_properties().daspay_credit_transaction_ratio / 10000; const auto& credit_amount = asset{credit_amount_with_fee, db.get_web_asset_id()} * dgpo.last_dascoin_price; BOOST_CHECK_EQUAL( get_reserved_balance(foo_id, get_dascoin_asset_id()), credit_amount.amount.value ); // Set price override for daspay to 0.2eur for 1dasc price override_price = asset(5 * DASCOIN_DEFAULT_ASSET_PRECISION, get_dascoin_asset_id()) / asset(1 * DASCOIN_FIAT_ASSET_PRECISION, get_web_asset_id()); map<asset_id_type, price> price_overrides; price_overrides[get_dascoin_asset_id()] = override_price; update_daspay_clearing_parameters_operation update_op; update_op.authority = get_das33_administrator_id(); update_op.extensions.insert(price_overrides); do_op(update_op); // Credit one web euro: do_op(daspay_credit_account_operation(payment_id, foo2_id, asset{1 * DASCOIN_FIAT_ASSET_PRECISION, db.get_web_asset_id()}, clearing_id, "", {})); credit_amount_with_fee = 1 * DASCOIN_FIAT_ASSET_PRECISION; credit_amount_with_fee += credit_amount_with_fee * db.get_dynamic_global_properties().daspay_credit_transaction_ratio / 10000; const auto& credit_amount2 = asset{credit_amount_with_fee, db.get_web_asset_id()} * override_price; BOOST_CHECK_EQUAL( get_reserved_balance(foo2_id, get_dascoin_asset_id()), credit_amount2.amount.value ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END() // dascoin_tests::daspay_tests BOOST_AUTO_TEST_SUITE_END() // dascoin_tests
50.734522
228
0.779469
[ "vector" ]
ff0cb32159d387b269446dc254356b8017c7fa8b
4,589
cpp
C++
ocl/getting_started/hello_vadd_ocl/src/host.cpp
martinATtug/SDSoC_Examples
0cfb0a96bdbe07b5a6fb58f859a4a07b37390ffe
[ "BSD-3-Clause" ]
89
2017-05-26T01:52:20.000Z
2022-01-10T06:20:48.000Z
ocl/getting_started/hello_vadd_ocl/src/host.cpp
martinATtug/SDSoC_Examples
0cfb0a96bdbe07b5a6fb58f859a4a07b37390ffe
[ "BSD-3-Clause" ]
4
2018-03-29T12:32:09.000Z
2020-07-16T19:35:42.000Z
ocl/getting_started/hello_vadd_ocl/src/host.cpp
martinATtug/SDSoC_Examples
0cfb0a96bdbe07b5a6fb58f859a4a07b37390ffe
[ "BSD-3-Clause" ]
46
2017-05-18T11:22:13.000Z
2021-03-25T16:56:13.000Z
/********** Copyright (c) 2018, Xilinx, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********/ /******************************************************************************* * Vendor: Xilinx * Associated Filename: vadd.cpp * Purpose: SDAccel vector addition * Revision History: January 28, 2016 *******************************************************************************/ //OpenCL utility layer include #include "xcl2.hpp" #define LENGTH (1024) int main(int argc, char* argv[]) { size_t vector_size_bytes = sizeof(int) * LENGTH; //Source Memories std::vector<unsigned int> source_a(LENGTH); std::vector<unsigned int> source_b(LENGTH); std::vector<unsigned int> result_sim (LENGTH); std::vector<unsigned int> result_krnl(LENGTH); /* Create the test data and golden data locally */ for(int i=0; i < LENGTH; i++){ source_a[i] = i; source_b[i] = 2*i; result_sim[i] = source_a[i] + source_b[i]; } // OPENCL HOST CODE AREA START //Getting Xilinx Platform and its device std::vector<cl::Device> devices = xcl::get_xil_devices(); cl::Device device = devices[0]; std::string device_name = device.getInfo<CL_DEVICE_NAME>(); //Creating Context and Command Queue for selected Device cl::Context context(device); cl::CommandQueue q(context, device); //Loading XCL Bin into char buffer std::string binaryFile = xcl::find_binary_file(device_name,"vadd"); cl::Program::Binaries bins = xcl::import_binary_file(binaryFile); devices.resize(1); cl::Program program(context, devices, bins); //Creating Kernel and Functor of Kernel int err1; cl::Kernel kernel(program, "vadd", &err1); auto krnl_vadd = cl::KernelFunctor<cl::Buffer&, cl::Buffer&, cl::Buffer&, int>(kernel); //Creating Buffers inside Device cl::Buffer buffer_a(context, CL_MEM_READ_ONLY, vector_size_bytes); cl::Buffer buffer_b(context, CL_MEM_READ_ONLY, vector_size_bytes); cl::Buffer buffer_c(context, CL_MEM_WRITE_ONLY, vector_size_bytes); //Copying input data to Device buffer from host memory q.enqueueWriteBuffer(buffer_a, CL_TRUE, 0, vector_size_bytes, source_a.data()); q.enqueueWriteBuffer(buffer_b, CL_TRUE, 0, vector_size_bytes, source_b.data()); //Running Kernel krnl_vadd (cl::EnqueueArgs(q, cl::NDRange(1,1,1), cl::NDRange(1,1,1)), buffer_a, buffer_b, buffer_c, LENGTH); q.finish(); //Copying Device result data to Host memory q.enqueueReadBuffer(buffer_c, CL_TRUE, 0, vector_size_bytes, result_krnl.data()); // OPENCL HOST CODE AREA END /* Compare the results of the kernel to the simulation */ bool krnl_match = true; for(int i = 0; i < LENGTH; i++){ if(result_sim[i] != result_krnl[i]){ std::cout <<"Error: Result mismatch" << std::endl; std::cout <<"i = " << i << " CPU result = " << result_sim[i] << " Krnl Result = " << result_krnl[i] << std::endl; krnl_match = false; break; } } std::cout << "TEST " << (krnl_match ? "PASSED" : "FAILED") << std::endl; return (krnl_match ? EXIT_SUCCESS: EXIT_FAILURE); }
40.973214
125
0.681848
[ "vector" ]
d42f42e10b09dda341d7485f0fc7736516ebf5ef
537
cpp
C++
docs/snippets/MULTI2.cpp
pazamelin/openvino
b7e8ef910d7ed8e52326d14dc6fd53b71d16ed48
[ "Apache-2.0" ]
2,406
2020-04-22T15:47:54.000Z
2022-03-31T10:27:37.000Z
docs/snippets/MULTI2.cpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4,948
2020-04-22T15:12:39.000Z
2022-03-31T18:45:42.000Z
docs/snippets/MULTI2.cpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
991
2020-04-23T18:21:09.000Z
2022-03-31T18:40:57.000Z
#include <ie_core.hpp> int main() { using namespace InferenceEngine; //! [part2] Core ie; auto cnnNetwork = ie.ReadNetwork("sample.xml"); std::string allDevices = "MULTI:"; std::vector<std::string> availableDevices = ie.GetAvailableDevices(); for (auto && device : availableDevices) { allDevices += device; allDevices += ((device == availableDevices[availableDevices.size()-1]) ? "" : ","); } ExecutableNetwork exeNetwork = ie.LoadNetwork(cnnNetwork, allDevices, {}); //! [part2] return 0; }
29.833333
91
0.649907
[ "vector" ]
d43e63e6d80c5488b07b64ea23c5d680cce6f847
2,754
cc
C++
drds/src/model/DescribeDrdsSlowSqlsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
3
2020-01-06T08:23:14.000Z
2022-01-22T04:41:35.000Z
drds/src/model/DescribeDrdsSlowSqlsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
drds/src/model/DescribeDrdsSlowSqlsResult.cc
sdk-team/aliyun-openapi-cpp-sdk
d0e92f6f33126dcdc7e40f60582304faf2c229b7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/drds/model/DescribeDrdsSlowSqlsResult.h> #include <json/json.h> using namespace AlibabaCloud::Drds; using namespace AlibabaCloud::Drds::Model; DescribeDrdsSlowSqlsResult::DescribeDrdsSlowSqlsResult() : ServiceResult() {} DescribeDrdsSlowSqlsResult::DescribeDrdsSlowSqlsResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDrdsSlowSqlsResult::~DescribeDrdsSlowSqlsResult() {} void DescribeDrdsSlowSqlsResult::parse(const std::string &payload) { Json::CharReaderBuilder builder; Json::CharReader *reader = builder.newCharReader(); Json::Value *val; Json::Value value; JSONCPP_STRING *errs; reader->parse(payload.data(), payload.data() + payload.size(), val, errs); value = *val; setRequestId(value["RequestId"].asString()); auto allItems = value["Items"]["Item"]; for (auto value : allItems) { Item itemsObject; if(!value["Schema"].isNull()) itemsObject.schema = value["Schema"].asString(); if(!value["Sql"].isNull()) itemsObject.sql = value["Sql"].asString(); if(!value["SendTime"].isNull()) itemsObject.sendTime = std::stol(value["SendTime"].asString()); if(!value["ResponseTime"].isNull()) itemsObject.responseTime = std::stol(value["ResponseTime"].asString()); if(!value["Host"].isNull()) itemsObject.host = value["Host"].asString(); items_.push_back(itemsObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Total"].isNull()) total_ = std::stoi(value["Total"].asString()); if(!value["PageNumber"].isNull()) pageNumber_ = std::stoi(value["PageNumber"].asString()); if(!value["PageSize"].isNull()) pageSize_ = std::stoi(value["PageSize"].asString()); } int DescribeDrdsSlowSqlsResult::getPageSize()const { return pageSize_; } int DescribeDrdsSlowSqlsResult::getPageNumber()const { return pageNumber_; } int DescribeDrdsSlowSqlsResult::getTotal()const { return total_; } std::vector<DescribeDrdsSlowSqlsResult::Item> DescribeDrdsSlowSqlsResult::getItems()const { return items_; } bool DescribeDrdsSlowSqlsResult::getSuccess()const { return success_; }
28.102041
89
0.729484
[ "vector", "model" ]
d4484c5a11a7c1f0d2104159a07b8a7ca8c1f2f7
3,334
cxx
C++
EMCAL/EMCALTriggerBase/AliEMCALTriggerAlgorithm.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
EMCAL/EMCALTriggerBase/AliEMCALTriggerAlgorithm.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
EMCAL/EMCALTriggerBase/AliEMCALTriggerAlgorithm.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/** * @file AliEMCALTriggerAlgorithm.cxx * @date Oct. 23, 2015 * @author Markus Fasel <markus.fasel@cern.ch>, Lawrence Berkeley National Laboratory */ /************************************************************************** * Copyright(c) 1998-2013, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include "AliEMCALTriggerDataGrid.h" #include "AliEMCALTriggerAlgorithm.h" #include <algorithm> /// \cond CLASSIMP templateClassImp(AliEMCALTriggerAlgorithm) /// \endcond template<typename T> AliEMCALTriggerAlgorithm<T>::AliEMCALTriggerAlgorithm(): TObject(), fRowMin(0), fRowMax(0), fPatchSize(0), fSubregionSize(1), fBitMask(0), fThreshold(0), fOfflineThreshold(0) { } template<typename T> AliEMCALTriggerAlgorithm<T>::AliEMCALTriggerAlgorithm(Int_t rowmin, Int_t rowmax, UInt_t bitmask): TObject(), fRowMin(rowmin), fRowMax(rowmax), fPatchSize(0), fSubregionSize(1), fBitMask(bitmask), fThreshold(0), fOfflineThreshold(0) { } template<typename T> AliEMCALTriggerAlgorithm<T>::~AliEMCALTriggerAlgorithm() { } template<typename T> std::vector<AliEMCALTriggerRawPatch> AliEMCALTriggerAlgorithm<T>::FindPatches(const AliEMCALTriggerDataGrid<T> &adc, const AliEMCALTriggerDataGrid<T> &offlineAdc) const { std::vector<AliEMCALTriggerRawPatch> result; T sumadc(0); T sumofflineAdc(0); int rowStartMax = fRowMax - (fPatchSize-1); int colStartMax = adc.GetNumberOfCols() - fPatchSize; for(int irow = fRowMin; irow <= rowStartMax; irow += fSubregionSize){ for(int icol = 0; icol <= colStartMax; icol += fSubregionSize){ sumadc = 0; sumofflineAdc = 0; for(int jrow = irow; jrow < irow + fPatchSize; jrow++){ for(int jcol = icol; jcol < icol + fPatchSize; jcol++){ try{ sumadc += adc(jcol, jrow); sumofflineAdc += offlineAdc(jcol, jrow); } catch (typename AliEMCALTriggerDataGrid<T>::OutOfBoundsException &e){ } } } if(sumadc > fThreshold || sumofflineAdc > fOfflineThreshold){ AliEMCALTriggerRawPatch recpatch(icol, irow, fPatchSize, sumadc, sumofflineAdc); recpatch.SetBitmask(fBitMask); result.push_back(recpatch); } } } std::sort(result.begin(), result.end()); return result; } template class AliEMCALTriggerAlgorithm<int>; template class AliEMCALTriggerAlgorithm<double>; template class AliEMCALTriggerAlgorithm<float>;
34.729167
170
0.631974
[ "vector" ]
d44dda6255767318dc217f07119126ac3a624e00
8,132
cpp
C++
ocr/src/v20181119/model/PropOwnerCertOCRResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
43
2019-08-14T08:14:12.000Z
2022-03-30T12:35:09.000Z
ocr/src/v20181119/model/PropOwnerCertOCRResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
12
2019-07-15T10:44:59.000Z
2021-11-02T12:35:00.000Z
ocr/src/v20181119/model/PropOwnerCertOCRResponse.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
28
2019-07-12T09:06:22.000Z
2022-03-30T08:04:18.000Z
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/ocr/v20181119/model/PropOwnerCertOCRResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ocr::V20181119::Model; using namespace std; PropOwnerCertOCRResponse::PropOwnerCertOCRResponse() : m_ownerHasBeenSet(false), m_possessionHasBeenSet(false), m_registerTimeHasBeenSet(false), m_purposeHasBeenSet(false), m_natureHasBeenSet(false), m_locationHasBeenSet(false) { } CoreInternalOutcome PropOwnerCertOCRResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("Owner") && !rsp["Owner"].IsNull()) { if (!rsp["Owner"].IsString()) { return CoreInternalOutcome(Core::Error("response `Owner` IsString=false incorrectly").SetRequestId(requestId)); } m_owner = string(rsp["Owner"].GetString()); m_ownerHasBeenSet = true; } if (rsp.HasMember("Possession") && !rsp["Possession"].IsNull()) { if (!rsp["Possession"].IsString()) { return CoreInternalOutcome(Core::Error("response `Possession` IsString=false incorrectly").SetRequestId(requestId)); } m_possession = string(rsp["Possession"].GetString()); m_possessionHasBeenSet = true; } if (rsp.HasMember("RegisterTime") && !rsp["RegisterTime"].IsNull()) { if (!rsp["RegisterTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `RegisterTime` IsString=false incorrectly").SetRequestId(requestId)); } m_registerTime = string(rsp["RegisterTime"].GetString()); m_registerTimeHasBeenSet = true; } if (rsp.HasMember("Purpose") && !rsp["Purpose"].IsNull()) { if (!rsp["Purpose"].IsString()) { return CoreInternalOutcome(Core::Error("response `Purpose` IsString=false incorrectly").SetRequestId(requestId)); } m_purpose = string(rsp["Purpose"].GetString()); m_purposeHasBeenSet = true; } if (rsp.HasMember("Nature") && !rsp["Nature"].IsNull()) { if (!rsp["Nature"].IsString()) { return CoreInternalOutcome(Core::Error("response `Nature` IsString=false incorrectly").SetRequestId(requestId)); } m_nature = string(rsp["Nature"].GetString()); m_natureHasBeenSet = true; } if (rsp.HasMember("Location") && !rsp["Location"].IsNull()) { if (!rsp["Location"].IsString()) { return CoreInternalOutcome(Core::Error("response `Location` IsString=false incorrectly").SetRequestId(requestId)); } m_location = string(rsp["Location"].GetString()); m_locationHasBeenSet = true; } return CoreInternalOutcome(true); } string PropOwnerCertOCRResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_ownerHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Owner"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_owner.c_str(), allocator).Move(), allocator); } if (m_possessionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Possession"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_possession.c_str(), allocator).Move(), allocator); } if (m_registerTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RegisterTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_registerTime.c_str(), allocator).Move(), allocator); } if (m_purposeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Purpose"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_purpose.c_str(), allocator).Move(), allocator); } if (m_natureHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Nature"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_nature.c_str(), allocator).Move(), allocator); } if (m_locationHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Location"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_location.c_str(), allocator).Move(), allocator); } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } string PropOwnerCertOCRResponse::GetOwner() const { return m_owner; } bool PropOwnerCertOCRResponse::OwnerHasBeenSet() const { return m_ownerHasBeenSet; } string PropOwnerCertOCRResponse::GetPossession() const { return m_possession; } bool PropOwnerCertOCRResponse::PossessionHasBeenSet() const { return m_possessionHasBeenSet; } string PropOwnerCertOCRResponse::GetRegisterTime() const { return m_registerTime; } bool PropOwnerCertOCRResponse::RegisterTimeHasBeenSet() const { return m_registerTimeHasBeenSet; } string PropOwnerCertOCRResponse::GetPurpose() const { return m_purpose; } bool PropOwnerCertOCRResponse::PurposeHasBeenSet() const { return m_purposeHasBeenSet; } string PropOwnerCertOCRResponse::GetNature() const { return m_nature; } bool PropOwnerCertOCRResponse::NatureHasBeenSet() const { return m_natureHasBeenSet; } string PropOwnerCertOCRResponse::GetLocation() const { return m_location; } bool PropOwnerCertOCRResponse::LocationHasBeenSet() const { return m_locationHasBeenSet; }
31.157088
130
0.670069
[ "object", "model" ]
d44ecbd2703089fa353f9ace507ec2aefeafbdf9
1,527
hpp
C++
src/RenderSystem.GL4/InputLayoutGL4.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
src/RenderSystem.GL4/InputLayoutGL4.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
src/RenderSystem.GL4/InputLayoutGL4.hpp
ValtoForks/pomdog
73798ae5f4a4c3b9b1e1e96239187c4b842c93b2
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license. #pragma once #include "OpenGLPrerequisites.hpp" #include "TypesafeGL4.hpp" #include "../Utility/Tagged.hpp" #include "Pomdog/Graphics/detail/ForwardDeclarations.hpp" #include <memory> #include <optional> #include <vector> namespace Pomdog { namespace Detail { namespace GL4 { namespace Tags { struct ScalarDataTypeTag {}; struct VertexArrayTag {}; } // namespace Tags using ScalarTypeGL4 = Tagged<GLuint, Tags::ScalarDataTypeTag>; using VertexArrayGL4 = Tagged<GLuint, Tags::VertexArrayTag>; struct InputElementGL4 { GLuint AttributeLocation; // Input element offset. std::uint32_t ByteOffset; std::uint16_t InputSlot; std::uint16_t InstanceStepRate; // Specifies the scalar data type. ScalarTypeGL4 ScalarType; // Must be 1, 2, 3, and 4. std::int8_t Components; bool IsInteger = false; }; struct VertexDeclarationGL4 { GLsizei StrideBytes; }; class InputLayoutGL4 final { public: explicit InputLayoutGL4(const ShaderProgramGL4& shaderProgram); InputLayoutGL4( const ShaderProgramGL4& shaderProgram, const InputLayoutDescription& description); ~InputLayoutGL4(); void Apply(const std::vector<VertexBufferBinding>& vertexBuffers); private: std::vector<InputElementGL4> inputElements; std::vector<VertexDeclarationGL4> vertexDeclarations; std::optional<VertexArrayGL4> inputLayout; }; } // namespace GL4 } // namespace Detail } // namespace Pomdog
21.507042
71
0.734774
[ "vector" ]
d44fe92169be662f153e7ae24268dd93cdcc9455
25,409
cpp
C++
dash_client_lib/source/api/biosmanagement.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
13
2015-08-06T14:55:10.000Z
2021-12-26T04:41:54.000Z
dash_client_lib/source/api/biosmanagement.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
null
null
null
dash_client_lib/source/api/biosmanagement.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
1
2017-06-17T14:15:41.000Z
2017-06-17T14:15:41.000Z
/* * License Agreement * * Copyright (c) 2007, 2008, 2009 Advanced Micro Devices Inc. * * All rights reserved. * * Redistribution and use in any form of this material and any product thereof including * software in source or binary forms, along with any related documentation, with or * without modification ("this material"), is permitted provided that the following * conditions are met: * * + Redistributions of source code of any software must retain the above copyright * notice and all terms of this license as part of the code. * * + Redistributions in binary form of any software must reproduce the above copyright * notice and all terms of this license in any related documentation and/or other * materials. * * + Neither the names nor trademarks of Advanced Micro Devices, Inc. or any copyright * holders or contributors may be used to endorse or promote products derived from * this material without specific prior written permission. * * + Notice about U.S. Government restricted rights: This material is provided with ? * RESTRICTED RIGHTS.? Use, duplication or disclosure by the U.S. Government is subject * to the full extent of restrictions set forth in FAR52.227 and DFARS252.227 et seq., * or any successor or applicable regulations. Use of this material by the U.S. * Government constitutes acknowledgment of the proprietary rights of * Advanced Micro Devices, Inc. and any copyright holders and contributors. * * + In no event shall anyone redistributing or accessing or using this material * commence or participate in any arbitration or legal action relating to this * material against Advanced Micro Devices, Inc. or any copyright holders or contributors. * The foregoing shall survive any expiration or termination of this license or any * agreement or access or use related to this material. * * + ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION * OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL. * * THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY REPRESENTATIONS, GUARANTEE, * OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO SUPPORT, INDEMNITY, ERROR FREE OR * UNINTERRUPTED OPERATION, OR THAT IT IS FREE FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS * ARE HEREBY DISCLAIMED - WHETHER EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT * LIMITED TO, ANY IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT. * IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * OR BASED ON ANY THEORY OF LIABILITY ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED * MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS * (US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS THIS * ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT * HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES, OBLIGATIONS, CLAIMS, OR DEMANDS IN * EXCESS OF TEN DOLLARS (US $10.00). THE FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, * IF ANY OF THESE TERMS ARE CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME * VOID OR DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS * FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL SHALL TERMINATE * IMMEDIATELY. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF THIS * LICENSE OR ANY AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. * * NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL SUCH NOTICE * IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO RESTRICTIONS UNDER THE LAWS AND REGULATIONS * OF THE UNITED STATES OR OTHER COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT * CONTROL LAWS SUCH AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS * DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S. MUNITIONS LIST. THIS * MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED, EXPORTED AND/OR RE-EXPORTED IN ANY * MANNER PROHIBITED UNDER ANY APPLICABLE LAWS, INCLUDING U.S. EXPORT CONTROL LAWS REGARDING * SPECIFICALLY DESIGNATED PERSONS, COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY * CONTROLS. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY LICENSE * OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. * * This license forms the entire agreement regarding the subject matter hereof and supersedes all * proposals and prior discussions and writings between the parties with respect thereto. This * license does not affect any ownership, rights, title, or interest in, or relating to, this * material. No terms of this license can be modified or waived, and no breach of this license * can be excused, unless done so in a writing signed by all affected parties. Each term of this * license is separately enforceable. If any term of this license is determined to be or becomes * unenforceable or illegal, such term shall be reformed to the minimum extent necessary in order * for this license to remain in effect in accordance with its terms as modified by such reformation. * This license shall be governed by and construed in accordance with the laws of the State of * Texas without regard to rules on conflicts of law of any state or jurisdiction or the United * Nations Convention on the International Sale of Goods. All disputes arising out of this license * shall be subject to the jurisdiction of the federal and state courts in Austin, Texas, and all * defenses are hereby waived concerning personal jurisdiction and venue of these courts. */ /** * biosmanagement.h * A class representing a bios management. */ #include <dsdk/oal/CIM_BIOSElement.h> #include <dsdk/oal/CIM_BIOSAttribute.h> #include <dsdk/oal/CIM_BIOSService.h> #include <dsdk/oal/CIM_BIOSEnumeration.h> #include <dsdk/oal/CIM_BIOSInteger.h> #include <dsdk/oal/CIM_BIOSString.h> #include <dsdk/oal/CIM_BIOSPassword.h> #include <dsdk/oal/CIM_SystemBIOS.h> #include <dsdk/oal/CIM_ServiceAffectsElement.h> #include <dsdk/oal/CIM_ConcreteComponent.h> #include <dsdk/oal/CIM_BIOSServiceCapabilities.h> #include <dsdk/biosmanagement.h> #include <dsdk/dsdkexception.h> #include "apiimp.h" #include <dsdk/enumerator.h> using namespace dsdk; /* * Constructor */ CBIOSAttribute::CBIOSAttribute (const CIM_BIOSAttribute& ba) { _ba = new CIM_BIOSAttribute (ba); } /* * Constructor */ CBIOSAttribute::CBIOSAttribute (const CBIOSAttribute& ba) { this->_ba = new CIM_BIOSAttribute (*(ba._ba)); } /* * Destruction */ CBIOSAttribute::~CBIOSAttribute () { if (this->_ba) { delete this->_ba; } } /* * Assignment operator */ const CBIOSAttribute& CBIOSAttribute::operator = (const CBIOSAttribute& rhs) { if (this->_ba) { delete this->_ba; } this->_ba = new CIM_BIOSAttribute (*rhs._ba); return *this; } /* * enumerateBIOSElement */ CBIOSAttribute::iterator CBIOSAttribute::enumBIOSAttributes (IClient* client, bool cached) { vector<string> props = getCachedProps (); CIM_BIOSAttribute::iterator iter = CIM_BIOSAttribute::enumInstances (client, 0, props); if (cached) { return createIterator (iter, props); } else { return createIterator (iter); } } /* * getInstanceID */ string CBIOSAttribute::getInstanceID(void) const { return _ba->getInstanceID (); } /* * getAttributeName */ string CBIOSAttribute::getAttributeName (void) const { return _ba->getAttributeName (); } /* * getCurrentValue */ vector<string> CBIOSAttribute::getCurrentValue (void) const { vector<string> values; values = _ba->getCurrentValue (); return values; } /* * getDefaultValue */ vector<string> CBIOSAttribute::getDefaultValue (void) const { vector<string> values; values = _ba->getDefaultValue (); return values; } /* * getPendingValue */ vector<string> CBIOSAttribute::getPendingValue (void) const { vector<string> values; values = _ba->getPendingValue (); return values; } /* * isReadOnly */ boolean CBIOSAttribute::isReadOnly (void) const { return _ba->getIsReadOnly (); } /* * isOrderedList */ boolean CBIOSAttribute::isOrderedList (void) const { return _ba->getIsOrderedList (); } /* * getPossibleValues */ vector<string> CBIOSAttribute::getPossibleValues (void) const { return ((CIM_BIOSEnumeration*)_ba)->getPossibleValues (); } /* * getPossibleValuesDescription */ vector<string> CBIOSAttribute::getPossibleValuesDescription (void) const { return ((CIM_BIOSEnumeration*)_ba)->getPossibleValuesDescription (); } /* * getLowerBound */ uint64 CBIOSAttribute::getLowerBound (void) const { return ((CIM_BIOSInteger*)_ba)->getLowerBound (); } /* * getUpperBound */ uint64 CBIOSAttribute::getUpperBound (void) const { return ((CIM_BIOSInteger*)_ba)->getUpperBound (); } /* * getProgrammaticUnit */ string CBIOSAttribute::getProgrammaticUnit (void) const { return ((CIM_BIOSInteger*)_ba)->getProgrammaticUnit (); } /* * getScalarIncrement */ uint32 CBIOSAttribute::getScalarIncrement (void) const { return ((CIM_BIOSInteger*)_ba)->getScalarIncrement (); } /* * getMaxLength */ uint64 CBIOSAttribute::getMaxLength (void) const { return ((CIM_BIOSString*)_ba)->getMaxLength (); } /* * getMinLength */ uint64 CBIOSAttribute::getMinLength (void) const { return ((CIM_BIOSString*)_ba)->getMinLength (); } /* * getStringType */ uint32 CBIOSAttribute::getStringType (void) const { return ((CIM_BIOSString*)_ba)->getStringType (); } /* * getStringTypeStr */ string CBIOSAttribute::getStringTypeStr (void) const { return CIM_BIOSString::getValueStr_StringType (((CIM_BIOSString*)_ba)->getStringType ()); } /* * getValueExpression */ string CBIOSAttribute::getValueExpression (void) const { return ((CIM_BIOSString*)_ba)->getValueExpression (); } /* * isPasswordSet */ boolean CBIOSAttribute::isPasswordSet (void) const { return ((CIM_BIOSPassword*)_ba)->getIsSet (); } /* * getPasswordEncoding */ uint32 CBIOSAttribute::getPasswordEncoding (void) const { return ((CIM_BIOSPassword*)_ba)->getPasswordEncoding (); } /* * getPasswordEncodingStr */ string CBIOSAttribute::getPasswordEncodingStr (void) const { return CIM_BIOSPassword::getValueStr_PasswordEncoding (((CIM_BIOSPassword*)_ba)->getPasswordEncoding ()); } /* * setAttribute */ uint32 CBIOSAttribute::setAttribute (const vector<string>& values) { uint32 result; CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); if(capableOfSetBIOSAttribute(bs,be) == false) { throw EFunctionNotSupported ("setBIOSAttribute"); } uint32 status = bs.SetBIOSAttribute (be, this->getAttributeName(), values, "", 2, &result); /* if set attribute is success return 0, else throw EFunctionReturnedWithFailure execption */ if (0 == status) { return status; } else { string retcodestr = bs.getValueStr_SetBIOSAttributeEmbeddedInstance_ReturnCode(status); throw EFunctionReturnedWithFailure ("CIM_BIOSService::SetBIOSAttribute", retcodestr, status); } } bool CBIOSAttribute::capableOfBIOSManagementService(CIM_BIOSService &bs, CIM_BIOSElement &be, CIM_BIOSServiceCapabilities &bsc) const { vector<string> empty_props; CIM_BIOSService::iterator Iterbs = CIM_ServiceAffectsElement <CIM_BIOSAttribute, CIM_BIOSService>::enumerateAffectingElement (this->_ba->getClient(), *(_ba), empty_props); if (Iterbs == CIM_BIOSService::iterator::end ()) return false; /* only one BIOS Service will be associated with a BIOSAttribute through Service AffectsElement */ bs = *Iterbs; /* Enumerate the Find the BIOSElement instance associated with BIOSAttribute */ CCIMObjectPath op = CCIMObjectPath::nullInstance (); CIM_BIOSElement::iterator Iterbe = CIM_ConcreteComponent <CIM_BIOSElement, CIM_BIOSAttribute>::enumerateGroupComponent(this->_ba->getClient(), *(_ba), empty_props); if (Iterbe == CIM_BIOSElement::iterator::end ()) return false; /* only one BIOS Element will be associated with a BIOSAttribute through ConcreteComponent class */ be = *Iterbe; // Enumerate CIM_BIOSServiceCapabilities instance associated with BIOSService through ElementCapabilities instance. CIM_BIOSServiceCapabilities::iterator Iterbsc = CIM_ElementCapabilities< CIM_BIOSService, CIM_BIOSServiceCapabilities>::enumerateCapabilities(this->_ba->getClient(), bs, empty_props); if (Iterbsc == CIM_BIOSServiceCapabilities::iterator::end ()) return false; bsc = *Iterbsc; return true; } bool CBIOSAttribute::capableOfBIOSManagementService() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); return capableOfBIOSManagementService(bs, be, bsc); } bool CBIOSAttribute::capableOfSetBIOSAttributes(CIM_BIOSService &bs, CIM_BIOSElement &be) const { CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); if ( false == capableOfBIOSManagementService(bs, be, bsc) ) return false; vector<uint32> vmethods = bsc.getMethodsSupported(); for ( size_t i=0; i < vmethods.size(); i++) { if (vmethods[i] == CIM_BIOSServiceCapabilities::MethodsSupported_SetBIOSAttributes) return true; } return false; } /** */ bool CBIOSAttribute::capableOfSetBIOSAttributes() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); return capableOfSetBIOSAttribute(bs, be); } bool CBIOSAttribute::capableOfSetBIOSAttributeEmbeddedInstance(CIM_BIOSService &bs, CIM_BIOSElement &be ) const { CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); if ( false == capableOfBIOSManagementService(bs, be, bsc) ) return false; vector<uint32> vmethods = bsc.getMethodsSupported(); for ( size_t i=0; i < vmethods.size(); i++) { if (vmethods[i] == CIM_BIOSServiceCapabilities::MethodsSupported_SetBIOSAttributeEmbeddedInstance) return true; } return false; } bool CBIOSAttribute::capableOfSetBIOSAttributeEmbeddedInstance() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); return capableOfSetBIOSAttributeEmbeddedInstance(bs, be); } bool CBIOSAttribute::capableOfSetBIOSAttribute(CIM_BIOSService &bs, CIM_BIOSElement &be) const { CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); if ( false == capableOfBIOSManagementService(bs, be, bsc) ) return false; vector<uint32> vmethods = bsc.getMethodsSupported(); for ( size_t i=0; i < vmethods.size(); i++) { if (vmethods[i] == CIM_BIOSServiceCapabilities::MethodsSupported_SetBIOSAttribute) return true; } return false; } /** */ bool CBIOSAttribute::capableOfSetBIOSAttribute() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); return capableOfSetBIOSAttribute(bs, be); } bool CBIOSAttribute::getSupportedEncodingsStr(vector<string> &encod_str) const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); if ( false == capableOfBIOSManagementService(bs, be, bsc) ) return false; vector<uint32> encod_val = bsc.getSupportedPasswordEncodings(); if ( encod_val.size() == 0 ) return false; for ( size_t i=0; i < encod_val.size(); i++) { encod_str.push_back(bsc.getValueStr_SupportedPasswordEncodings(encod_val[i])); } return true; } bool CBIOSAttribute::getSupportedPasswordAlgorithms(vector<string> &algo_str) const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); if ( false == capableOfBIOSManagementService(bs, be, bsc) ) return false; algo_str = bsc.getSupportedPasswordAlgorithms(); if ( algo_str.size() == 0 ) return false; return true; } /* * getCachedProps */ vector<string> CBIOSAttribute::getCachedProps (void) { vector<string> props; props.push_back ("InstanceID"); props.push_back ("AttributeName"); props.push_back ("CurrentValue"); props.push_back ("DefaultValue"); props.push_back ("PendingValue"); props.push_back ("IsReadOnly"); props.push_back ("IsOrderedList"); props.push_back ("PossibleValues"); props.push_back ("AttributeName"); props.push_back ("PossibleValuesDescription"); props.push_back ("LowerBound"); props.push_back ("UpperBound"); props.push_back ("ProgrammaticUnit"); props.push_back ("ScalarIncrement"); props.push_back ("MaxLength"); props.push_back ("MinLength"); props.push_back ("StringType"); props.push_back ("ValueExpression"); props.push_back ("IsSet"); props.push_back ("PasswordEncoding"); return props; } /* * BIOSAttribute::Iterator */ DEFINE_API_ITERATOR (CBIOSAttribute); /* * createIterator */ DEFINE_CREATE_API_ITERATOR (CBIOSAttribute, CIM_BIOSAttribute); /* * Constructor */ CBIOSElement::CBIOSElement (const CIM_BIOSElement& be) { _be = new CIM_BIOSElement (be); } /* * Constructor */ CBIOSElement::CBIOSElement (const CBIOSElement& be) { this->_be = new CIM_BIOSElement (*(be._be)); } /* * Destruction */ CBIOSElement::~CBIOSElement () { if (this->_be) { delete this->_be; } } /* * Assignment operator */ const CBIOSElement& CBIOSElement::operator = (const CBIOSElement& rhs) { if (this->_be) { delete this->_be; } this->_be = new CIM_BIOSElement (*rhs._be); return *this; } /* * enumerateBIOSElement */ CBIOSElement::iterator CBIOSElement::enumBIOSElements (IClient* client, bool cached) { vector<string> props = getCachedProps (); CIM_BIOSElement::iterator iter = CIM_BIOSElement::enumInstances (client, 0, props); if (cached) { return createIterator (iter, props); } else { return createIterator (iter); } } /* * getName */ string CBIOSElement::getName (void) const { return _be->getName (); } /* * getManufacture */ string CBIOSElement::getManufacturer (void) const { return _be->getManufacturer(); } /* * getPrimaryBIOS */ boolean CBIOSElement::getPrimaryBIOS (void) const { return _be->getPrimaryBIOS (); } /* * getVersion */ string CBIOSElement::getVersion (void) const { return _be->getVersion (); } /* * getSoftwareElementState */ uint16 CBIOSElement::getSoftwareElementState (void) const { return _be->getSoftwareElementState (); } /* * getSoftwareElementStateStr */ string CBIOSElement::getSoftwareElementStateStr (void) const { return CIM_BIOSElement::getValueStr_SoftwareElementState (_be->getSoftwareElementState ()); } /* * getSoftwareElementID */ string CBIOSElement::getSoftwareElementID (void) const { return _be->getSoftwareElementID (); } /* * getTargetOperatingSystem */ uint16 CBIOSElement::getTargetOperatingSystem (void) const { return _be->getTargetOperatingSystem (); } /* * getTargetOperatingSystemStr */ string CBIOSElement::getTargetOperatingSystemStr (void) const { return CIM_BIOSElement::getValueStr_TargetOperatingSystem (_be->getTargetOperatingSystem ()); } /* * getRegistryURIs */ vector<string> CBIOSElement::getRegistryURIs (void) const { return _be->getRegistryURIs (); } /* * getAttributes */ vector<CBIOSAttribute> CBIOSElement::getAttributes (void) const { vector <CBIOSAttribute> attributes; /* enumerate the attribute associated with this BIOS element */ /* @todo */ //CBIOSAttribute::iterator iter = enumBIOSAttributes (_be->getClient(), *(_be)); CBIOSAttribute::iterator iter = CBIOSAttribute::enumBIOSAttributes (_be->getClient()); for (; iter != CBIOSAttribute::iterator::end (); ++iter) { CBIOSAttribute attribute = *iter; attributes.push_back (attribute); } return attributes; } /* * restoreDefaults */ uint32 CBIOSElement::restoreDefaults (void) { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSElement be(CCIMInstance::nullInstance ()); if(capableOfRestoreDefaults(bs) == false) { throw EFunctionNotSupported ("restoreBIOSDefaults"); } uint32 status = bs.RestoreBIOSDefaults (*(this->getCIMObject()), "", 0); /* if BIOS restored successfully return 0, else throw EFunctionReturnedWithFailure execption */ if (0 == status) { return status; } else { string retcodestr = bs.getValueStr_RestoreBIOSDefaults_ReturnCode(status); throw EFunctionReturnedWithFailure ("CIM_BIOSService::RestoreBIOSDefaults", retcodestr, status); } } // ============================ Below ===================== bool CBIOSElement::capableOfBIOSManagementService(CIM_BIOSService &bs, CIM_BIOSServiceCapabilities &bsc) const { vector<string> empty_props; /* enumerate the Computer System associated with this BIOS Element */ CIM_ComputerSystem::iterator iter = CIM_SystemBIOS <CIM_ComputerSystem, CIM_BIOSElement>::enumerateGroupComponent (_be->getClient(), *(this->getCIMObject ()), empty_props); if (iter == CIM_ComputerSystem::iterator::end ()) return false; /* only one computer system will be associated with a BIOS Element so use the first instance */ CIM_ComputerSystem cs = *iter; /* enumerate the BIOS Service associated with the computer system */ CIM_BIOSService::iterator Iter = CIM_ServiceAffectsElement <CIM_ComputerSystem, CIM_BIOSService>::enumerateAffectingElement (this->_be->getClient(), cs, empty_props); if (Iter == CIM_BIOSService::iterator::end ()) return false; /* only one BIOS Service will be associated with a computer system through Service AffectsElement */ bs = *Iter; /* enumerate the BIOSSErviceCapabilities instance associate with BIOSService through ElementCapbilities */ CIM_BIOSServiceCapabilities::iterator bsciter = CIM_ElementCapabilities < CIM_BIOSService,CIM_BIOSServiceCapabilities>::enumerateCapabilities ( bs.getClient (), bs,empty_props); if (bsciter == CIM_BIOSServiceCapabilities::iterator::end()) { //throw EFunctionNotSupported ("BIOSServiceCapabilities"); return false; } /* Only one BIOS Service capabilities will be supported, so use the first BIOS Service capabilities */ bsc = *bsciter; return true; } bool CBIOSElement::capableOfBIOSManagementService() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); return capableOfBIOSManagementService(bs, bsc); } bool CBIOSElement::isSupportedMethod(CIM_BIOSService &bs, uint32 method ) const { CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); if ( capableOfBIOSManagementService(bs, bsc) == false) return false; vector<uint32> vmethods = bsc.getMethodsSupported(); for ( size_t i=0; i < vmethods.size(); i++) { if (vmethods[i] == method) return true; } return false; } /* */ bool CBIOSElement::capableOfReadRawBIOSData(CIM_BIOSService &bs) const { return isSupportedMethod(bs, CIM_BIOSServiceCapabilities::MethodsSupported_ReadRawBIOSData); } bool CBIOSElement::capableOfReadRawBIOSData() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); return capableOfReadRawBIOSData(bs); } /* */ bool CBIOSElement::capableOfWriteRawBIOSData(CIM_BIOSService &bs) const { return isSupportedMethod(bs, CIM_BIOSServiceCapabilities::MethodsSupported_WriteRawBIOSData); } bool CBIOSElement::capableOfWriteRawBIOSData() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); return capableOfWriteRawBIOSData(bs); } /* */ bool CBIOSElement::capableOfRestoreDefaults(CIM_BIOSService &bs ) const { return isSupportedMethod(bs, CIM_BIOSServiceCapabilities::MethodsSupported_RestoreBIOSDefaults); } bool CBIOSElement::capableOfRestoreDefaults() const { CIM_BIOSService bs(CCIMInstance::nullInstance ()); return capableOfRestoreDefaults(bs); } vector<uint32> CBIOSElement::getSupportedMethods() { CIM_BIOSServiceCapabilities bsc (CCIMInstance::nullInstance ()); CIM_BIOSService bs (CCIMInstance::nullInstance ()); return bsc.getMethodsSupported(); } //================================== Above ============================================= /* * getCachedProps */ vector<string> CBIOSElement::getCachedProps (void) { vector<string> props; props.push_back ("Manufacturer"); props.push_back ("PrimaryBIOS"); props.push_back ("Name"); props.push_back ("Version"); props.push_back ("SoftwareElementState"); props.push_back ("SoftwareElementID"); props.push_back ("TargetOperatingSystem"); props.push_back ("RegistryURIs"); return props; } /* * BIOSElement::Iterator */ DEFINE_API_ITERATOR (CBIOSElement); /* * createIterator */ DEFINE_CREATE_API_ITERATOR (CBIOSElement, CIM_BIOSElement);
27.558568
128
0.745996
[ "vector" ]
d4530f90e2cd28190e444774210a53c532711ff9
3,187
cpp
C++
src/exp/pokec/pokec_size_estimation.cpp
kazuibasou/KDD2020
fc327ffc745c0cedbce85cfbffb606ac46df9a85
[ "MIT" ]
2
2020-11-07T05:50:39.000Z
2022-01-29T14:03:25.000Z
src/exp/pokec/pokec_size_estimation.cpp
kazuibasou/KDD2020
fc327ffc745c0cedbce85cfbffb606ac46df9a85
[ "MIT" ]
null
null
null
src/exp/pokec/pokec_size_estimation.cpp
kazuibasou/KDD2020
fc327ffc745c0cedbce85cfbffb606ac46df9a85
[ "MIT" ]
1
2021-05-12T04:51:52.000Z
2021-05-12T04:51:52.000Z
#include <iostream> #include <vector> #include <string> #include <random> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include "../../main/graph.h" #include "../../main/sampling.h" #include "../../main/estimation.h" #include "../exp.h" /* We estimate the NRMSEs of estimates of the following size estimators for specified sample sizes. estimation0: naive weighting estimation1: proposed weighting */ int several_samplesize_exp(Graph &G,std::string model,const std::vector<double> samplerates,const double ratio_m_r,const int exptime,std::vector<std::vector<double> > &NRMSEs){ int i,j,k,seed,samplesize; double NRMSE; double exact_value = double(G.N); std::vector<SampledData> samplinglist; std::vector<double> estimations; std::vector<std::vector<double> > estimations_results; NRMSEs.clear(); PublicCluster LPC = return_LPC(G); for(i=0;i<int(samplerates.size());++i){ samplesize = round(G.N*samplerates[i]); estimations_results = std::vector<std::vector<double> >(); for(j=0;j<exptime;++j){ seed = select_seed(LPC); samplinglist.clear(); RW(G, model, samplesize, seed, samplinglist); estimations.clear(); Size_estimations(samplinglist,ratio_m_r,estimations); estimations_results.resize(estimations.size()); for(k=0;k<int(estimations_results.size());++k){ estimations_results[k].push_back(estimations[k]); } } NRMSEs.resize(estimations_results.size()); for(k=0;k<int(NRMSEs.size());++k){ NRMSE = calc_NRMSE(estimations_results[k],exact_value); NRMSEs[k].push_back(NRMSE); } } return 0; } int main(int argc,char *argv[]){ if(argc != 2){ printf("Error: Please input following: ./pokec_size_estimation (access model: ideal or hidden)\n"); return -1; } //read graph data. const char graphdata[] = "graphdata.txt"; //name of file contains data (number of nodes, number of edges and so on) of each graph. const char *readgraph = "pokec"; //name of file we read. const char *model = argv[1]; //The model of available neighbor data. We specify "ideal" or "hidden". Graph G; G.readpokec(graphdata,readgraph); //main process srand((unsigned) time(NULL)); Settings settings; std::vector<std::vector<double> > NRMSEs; several_samplesize_exp(G,model,settings.pokec_samplerates,settings.ratio_m_r,settings.numrun,NRMSEs); //write result const char *dir = "../data/exp/"; const std::string expfilepath = std::string(dir) + std::string(readgraph) + "_size_" + model + ".txt"; FILE *ef = fopen(expfilepath.c_str(),"w"); if(ef == NULL) { printf("Could not open file named %s.\n",expfilepath.c_str()); return -1; } fprintf(ef,"The NRMSEs of estimates of each size estimator for specified sample rates.\n"); fprintf(ef,"Sample rates:"); for(double samplerate:settings.pokec_samplerates){ fprintf(ef,"%lf, ",samplerate); } fprintf(ef,"\n"); fprintf(ef,"Ratio of a threshold m to sample size: %lf\n",settings.ratio_m_r); fprintf(ef,"Number of runs: %d\n",settings.numrun); for(int i=0;i<int(NRMSEs.size());++i){ fprintf(ef,"NRMSE of estimation%d:\n",i); for(double NRMSE:NRMSEs[i]){ fprintf(ef,"%lf, ",NRMSE); } fprintf(ef,"\n"); } fclose(ef); return 0; }
31.87
176
0.700031
[ "vector", "model" ]
d45485a3bad1c1fe89b67fc9e76d5d1272c607b6
7,051
cc
C++
lib/imagereader/imdimagereader.cc
tdaede/fluxengine
056055bf0bf8b4091ab9d23b1542d1549aa99e6a
[ "MIT" ]
247
2019-01-07T05:12:52.000Z
2022-03-30T02:30:21.000Z
lib/imagereader/imdimagereader.cc
tdaede/fluxengine
056055bf0bf8b4091ab9d23b1542d1549aa99e6a
[ "MIT" ]
337
2019-02-19T17:56:56.000Z
2022-03-31T22:04:25.000Z
lib/imagereader/imdimagereader.cc
tdaede/fluxengine
056055bf0bf8b4091ab9d23b1542d1549aa99e6a
[ "MIT" ]
57
2019-01-07T05:18:17.000Z
2022-03-05T09:12:28.000Z
#include "globals.h" #include "flags.h" #include "sector.h" #include "imagereader/imagereader.h" #include "image.h" #include "lib/config.pb.h" #include "fmt/format.h" #include <algorithm> #include <iostream> #include <fstream> static unsigned getModulationandSpeed(uint8_t flags, bool *mfm) { switch (flags) { case 0: /* 500 kbps FM */ //clockRateKhz.setDefaultValue(250); *mfm = false; return 500; break; case 1: /* 300 kbps FM */ *mfm = false; return 300; break; case 2: /* 250 kbps FM */ *mfm = false; return 250; break; case 3: /* 500 kbps MFM */ *mfm = true; return 500; break; case 4: /* 300 kbps MFM */ *mfm = true; return 300; break; case 5: /* 250 kbps MFM */ *mfm = true; return 250; break; default: Error() << fmt::format("don't understand IMD disks with this modulation and speed {}", flags); throw 0; } } struct TrackHeader { uint8_t ModeValue; uint8_t track; uint8_t Head; uint8_t numSectors; uint8_t SectorSize; }; static unsigned getSectorSize(uint8_t flags) { switch (flags) { case 0: return 128; case 1: return 256; case 2: return 512; case 3: return 1024; case 4: return 2048; case 5: return 4096; case 6: return 8192; } Error() << "not reachable"; } #define SEC_CYL_MAP_FLAG 0x80 #define SEC_HEAD_MAP_FLAG 0x40 #define HEAD_MASK 0x3F #define END_OF_FILE 0x1A class IMDImageReader : public ImageReader { public: IMDImageReader(const ImageReaderProto& config): ImageReader(config) {} Image readImage() /* IMAGE FILE FORMAT The overall layout of an ImageDisk .IMD image file is: IMD v.vv: dd/mm/yyyy hh:mm:ss Comment (ASCII only - unlimited size) 1A byte - ASCII EOF character - For each track on the disk: 1 byte Mode value see getModulationspeed for definition 1 byte Cylinder 1 byte Head 1 byte number of sectors in track 1 byte sector size see getsectorsize for definition sector numbering map sector cylinder map (optional) definied in high byte of head (since head is 0 or 1) sector head map (optional) definied in high byte of head (since head is 0 or 1) sector data records <End of file> */ { //Read File std::ifstream inputFile(_config.filename(), std::ios::in | std::ios::binary); if (!inputFile.is_open()) Error() << "cannot open input file"; //define some variables bool mfm = false; //define coding just to show in comment for setting the right write parameters inputFile.seekg(0, inputFile.end); int inputFileSize = inputFile.tellg(); // determine filesize inputFile.seekg(0, inputFile.beg); Bytes data; data.writer() += inputFile; ByteReader br(data); Image image; TrackHeader header = {0, 0, 0, 0, 0}; unsigned n = 0; unsigned headerPtr = 0; unsigned Modulation_Speed = 0; unsigned sectorSize = 0; std::string sector_skew; int b; unsigned char comment[8192]; //i choose a fixed value. dont know how to make dynamic arrays in C++. This should be enough // Read comment while ((b = br.read_8()) != EOF && b != 0x1A) { comment[n++] = (unsigned char)b; } headerPtr = n; //set pointer to after comment comment[n] = '\0'; // null-terminate the string //write comment to screen std::cout << "Comment in IMD image:\n" << fmt::format("{}\n", comment); //first read header for (;;) { if (headerPtr >= inputFileSize-1) { break; } header.ModeValue = br.read_8(); headerPtr++; Modulation_Speed = getModulationandSpeed(header.ModeValue, &mfm); header.track = br.read_8(); headerPtr++; header.Head = br.read_8(); headerPtr++; header.numSectors = br.read_8(); headerPtr++; header.SectorSize = br.read_8(); headerPtr++; sectorSize = getSectorSize(header.SectorSize); //Read optional cylinder map To Do //Read optional sector head map To Do //read sector numbering map std::vector<unsigned> sector_map(header.numSectors); bool blnBaseOne = false; sector_skew.clear(); for (b = 0; b < header.numSectors; b++) { sector_map[b] = br.read_8(); sector_skew.push_back(sector_map[b] + '0'); if (b == 0) //first sector see if base is 0 or 1 Fluxengine wants 0 { if (sector_map[b]==1) { blnBaseOne = true; } } if (blnBaseOne==true) { sector_map[b] = (sector_map[b]-1); } headerPtr++; } //read the sectors for (int s = 0; s < header.numSectors; s++) { Bytes sectordata; const auto& sector = image.put(header.track, header.Head, sector_map[s]); //read the status of the sector unsigned int Status_Sector = br.read_8(); headerPtr++; switch (Status_Sector) { case 0: /* Sector data unavailable - could not be read */ break; case 1: /* Normal data: (Sector Size) bytes follow */ sectordata = br.read(sectorSize); headerPtr += sectorSize; sector->data.writer().append(sectordata); break; case 2: /* Compressed: All bytes in sector have same value (xx) */ sectordata = br.read(1); headerPtr++; sector->data.writer().append(sectordata); for (int k = 1; k < sectorSize; k++) { //fill data till sector is full sector->data.writer().append(sectordata); } break; case 3: /* Normal data with "Deleted-Data address mark" */ break; case 4: /* Compressed with "Deleted-Data address mark"*/ break; case 5: /* Normal data read with data error */ break; case 6: /* Compressed read with data error" */ break; case 7: /* Deleted data read with data error" */ break; case 8: /* Compressed, Deleted read with data error" */ break; default: Error() << fmt::format("don't understand IMD disks with sector status {}", Status_Sector); } sector->status = Sector::OK; sector->logicalTrack = sector->physicalCylinder = header.track; sector->logicalSide = sector->physicalHead = header.Head; sector->logicalSector = (sector_map[s]); } } //Write format detected in IMD image to screen to help user set the right write parameters image.setGeometry({ .numTracks = header.track, .numSides = header.Head + 1U, .numSectors = header.numSectors, .sectorSize = sectorSize }); size_t headSize = header.numSectors * sectorSize; size_t trackSize = headSize * (header.Head + 1); std::cout << "reading IMD image\n" << fmt::format("{} tracks, {} heads; {}; {} kbps; {} sectoren; sectorsize {}; sectormap {}; {} kB total \n", header.track, header.Head + 1, mfm ? "MFM" : "FM", Modulation_Speed, header.numSectors, sectorSize, sector_skew, (header.track+1) * trackSize / 1024); return image; } }; std::unique_ptr<ImageReader> ImageReader::createIMDImageReader( const ImageReaderProto& config) { return std::unique_ptr<ImageReader>(new IMDImageReader(config)); }
24.397924
123
0.633811
[ "vector" ]
d45adcbfada5432315ce4a7334174128443b4403
12,662
cpp
C++
src/charls_jpegls_decoder.cpp
genisysram/charls
5cd3ed2839c49f0ff2d2aeb722ae432225d59c4e
[ "BSD-3-Clause" ]
null
null
null
src/charls_jpegls_decoder.cpp
genisysram/charls
5cd3ed2839c49f0ff2d2aeb722ae432225d59c4e
[ "BSD-3-Clause" ]
null
null
null
src/charls_jpegls_decoder.cpp
genisysram/charls
5cd3ed2839c49f0ff2d2aeb722ae432225d59c4e
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) Team CharLS. // SPDX-License-Identifier: BSD-3-Clause #include <charls/charls.h> #include "jpeg_stream_reader.h" #include "util.h" #include <cassert> #include <memory> #include <new> using std::unique_ptr; using namespace charls; using impl::throw_jpegls_error; struct charls_jpegls_decoder final { void source(IN_READS_BYTES_(source_size_bytes) const void* source_buffer, const size_t source_size_bytes) CHARLS_ATTRIBUTE((nonnull)) { if (state_ != state::initial) throw_jpegls_error(jpegls_errc::invalid_operation); source_buffer_ = source_buffer; size_ = source_size_bytes; byte_stream_info source{from_byte_array_const(source_buffer_, size_)}; reader_ = std::make_unique<jpeg_stream_reader>(source); state_ = state::source_set; } bool read_header(OUT_ spiff_header* spiff_header) { if (state_ != state::source_set) throw_jpegls_error(jpegls_errc::invalid_operation); bool spiff_header_found{}; reader_->read_header(spiff_header, &spiff_header_found); state_ = spiff_header_found ? state::spiff_header_read : state::spiff_header_not_found; return spiff_header_found; } void read_header() { if (state_ == state::initial || state_ >= state::header_read) throw_jpegls_error(jpegls_errc::invalid_operation); if (state_ != state::spiff_header_not_found) { reader_->read_header(); } reader_->read_start_of_scan(); state_ = state::header_read; } charls::frame_info frame_info() const { if (state_ < state::header_read) throw_jpegls_error(jpegls_errc::invalid_operation); return reader_->frame_info(); } int32_t near_lossless(int32_t /*component*/ = 0) const { if (state_ < state::header_read) throw_jpegls_error(jpegls_errc::invalid_operation); // Note: The JPEG-LS standard allows to define different NEAR parameter for every scan. return reader_->parameters().near_lossless; } charls::interleave_mode interleave_mode() const { if (state_ < state::header_read) throw_jpegls_error(jpegls_errc::invalid_operation); // Note: The JPEG-LS standard allows to define different interleave modes for every scan. // CharLS doesn't support mixed interleave modes, first scan determines the mode. return reader_->parameters().interleave_mode; } color_transformation transformation() const { if (state_ < state::header_read) throw_jpegls_error(jpegls_errc::invalid_operation); return reader_->parameters().transformation; } const jpegls_pc_parameters& preset_coding_parameters() const { if (state_ < state::header_read) throw_jpegls_error(jpegls_errc::invalid_operation); return reader_->preset_coding_parameters(); } size_t destination_size(const uint32_t stride) const { const charls::frame_info info{frame_info()}; if (stride == 0) { return static_cast<size_t>(info.component_count) * info.height * info.width * bit_to_byte_count(info.bits_per_sample); } switch (interleave_mode()) { case charls::interleave_mode::none: return static_cast<size_t>(info.component_count) * stride * info.height; case charls::interleave_mode::line: case charls::interleave_mode::sample: return static_cast<size_t>(stride) * info.height; } ASSERT(false); return 0; } void decode(OUT_WRITES_BYTES_(destination_size_bytes) void* destination_buffer, const size_t destination_size_bytes, const uint32_t stride) const CHARLS_ATTRIBUTE((nonnull)) { if (state_ != state::header_read) throw_jpegls_error(jpegls_errc::invalid_operation); const byte_stream_info destination = from_byte_array(destination_buffer, destination_size_bytes); reader_->read(destination, stride); } void output_bgr(const bool value) const noexcept { reader_->output_bgr(value); } void region(const JlsRect& rect) const noexcept { reader_->rect(rect); } private: enum class state { initial, source_set, spiff_header_read, spiff_header_not_found, header_read, completed }; state state_{}; unique_ptr<jpeg_stream_reader> reader_; const void* source_buffer_{}; size_t size_{}; }; extern "C" { charls_jpegls_decoder* CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_create() noexcept { MSVC_WARNING_SUPPRESS_NEXT_LINE(26402 26409) // don't use new and delete + scoped object and move return new (std::nothrow) charls_jpegls_decoder; // NOLINT(cppcoreguidelines-owning-memory) } void CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_destroy(IN_OPT_ const charls_jpegls_decoder* decoder) noexcept { MSVC_WARNING_SUPPRESS_NEXT_LINE(26401 26409) // don't use new and delete + non-owner. delete decoder; // NOLINT(cppcoreguidelines-owning-memory) } jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_set_source_buffer(IN_ charls_jpegls_decoder* decoder, IN_READS_BYTES_(source_size_bytes) const void* source_buffer, const size_t source_size_bytes) noexcept try { check_pointer(decoder)->source(check_pointer(source_buffer), source_size_bytes); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } charls_jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_read_spiff_header(IN_ charls_jpegls_decoder* const decoder, OUT_ charls_spiff_header* spiff_header, OUT_ int32_t* header_found) noexcept try { *check_pointer(header_found) = static_cast<int32_t>(check_pointer(decoder)->read_header(check_pointer(spiff_header))); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_read_header(IN_ charls_jpegls_decoder* const decoder) noexcept try { check_pointer(decoder)->read_header(); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_get_frame_info(IN_ const charls_jpegls_decoder* const decoder, OUT_ charls_frame_info* frame_info) noexcept try { *check_pointer(frame_info) = check_pointer(decoder)->frame_info(); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } charls_jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_get_near_lossless(IN_ const charls_jpegls_decoder* decoder, const int32_t component, OUT_ int32_t* near_lossless) noexcept try { *check_pointer(near_lossless) = check_pointer(decoder)->near_lossless(component); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } charls_jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_get_interleave_mode(IN_ const charls_jpegls_decoder* decoder, OUT_ charls_interleave_mode* interleave_mode) noexcept try { *check_pointer(interleave_mode) = check_pointer(decoder)->interleave_mode(); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } charls_jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_get_preset_coding_parameters(IN_ const charls_jpegls_decoder* decoder, const int32_t /*reserved*/, OUT_ charls_jpegls_pc_parameters* preset_coding_parameters) noexcept try { *check_pointer(preset_coding_parameters) = check_pointer(decoder)->preset_coding_parameters(); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_get_destination_size(IN_ const charls_jpegls_decoder* decoder, const uint32_t stride, OUT_ size_t* destination_size_bytes) noexcept try { *check_pointer(destination_size_bytes) = check_pointer(decoder)->destination_size(stride); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } jpegls_errc CHARLS_API_CALLING_CONVENTION charls_jpegls_decoder_decode_to_buffer(IN_ const charls_jpegls_decoder* decoder, OUT_WRITES_BYTES_(destination_size_bytes) void* destination_buffer, const size_t destination_size_bytes, const uint32_t stride) noexcept try { check_pointer(decoder)->decode(check_pointer(destination_buffer), destination_size_bytes, stride); return jpegls_errc::success; } catch (...) { return to_jpegls_errc(); } jpegls_errc CHARLS_API_CALLING_CONVENTION JpegLsReadHeader( IN_READS_BYTES_(source_length) const void* source, const size_t source_length, OUT_ JlsParameters* params, OUT_OPT_ char* error_message) try { charls_jpegls_decoder decoder; decoder.source(check_pointer(source), source_length); decoder.read_header(); *check_pointer(params) = JlsParameters{}; const frame_info info = decoder.frame_info(); params->height = static_cast<int32_t>(info.height); params->width = static_cast<int32_t>(info.width); params->bitsPerSample = info.bits_per_sample; params->components = info.component_count; params->interleaveMode = decoder.interleave_mode(); params->allowedLossyError = decoder.near_lossless(); params->colorTransformation = decoder.transformation(); const int32_t component_count = params->interleaveMode == interleave_mode::none ? 1 : params->components; params->stride = params->width * component_count * static_cast<int32_t>(bit_to_byte_count(params->bitsPerSample)); const auto& preset{decoder.preset_coding_parameters()}; params->custom.MaximumSampleValue = preset.maximum_sample_value; params->custom.Threshold1 = preset.threshold1; params->custom.Threshold2 = preset.threshold2; params->custom.Threshold3 = preset.threshold3; params->custom.ResetValue = preset.reset_value; clear_error_message(error_message); return jpegls_errc::success; } catch (...) { return set_error_message(to_jpegls_errc(), error_message); } jpegls_errc CHARLS_API_CALLING_CONVENTION JpegLsDecode(OUT_WRITES_BYTES_(destination_length) void* destination, const size_t destination_length, IN_READS_BYTES_(source_length) const void* source, const size_t source_length, IN_OPT_ const struct JlsParameters* params, OUT_OPT_ char* error_message) try { charls_jpegls_decoder decoder; decoder.source(check_pointer(source), source_length); decoder.read_header(); int32_t stride{}; if (params) { decoder.output_bgr(params->outputBgr != 0); stride = params->stride; } decoder.decode(check_pointer(destination), destination_length, static_cast<uint32_t>(stride)); clear_error_message(error_message); return jpegls_errc::success; } catch (...) { return set_error_message(to_jpegls_errc(), error_message); } jpegls_errc CHARLS_API_CALLING_CONVENTION JpegLsDecodeRect(OUT_WRITES_BYTES_(destination_length) void* destination, const size_t destination_length, IN_READS_BYTES_(source_length) const void* source, const size_t source_length, const JlsRect roi, IN_OPT_ const JlsParameters* params, OUT_OPT_ char* error_message) try { charls_jpegls_decoder decoder; decoder.source(check_pointer(source), source_length); decoder.read_header(); int32_t stride{}; if (params) { decoder.output_bgr(params->outputBgr != 0); stride = params->stride; } decoder.region(roi); decoder.decode(check_pointer(destination), destination_length, static_cast<uint32_t>(stride)); clear_error_message(error_message); return jpegls_errc::success; } catch (...) { return set_error_message(to_jpegls_errc(), error_message); } }
31.341584
130
0.685595
[ "object" ]
d4611978a2e1cd1c02fe051eaea8cb90d12461d0
319
cpp
C++
openearthsdk/src/main/cpp/earth/geometry/geometry_util.cpp
Darlun1024/OpenEarth
f30f5fd2d4bb91e00d323f8c8a1d17169a3e8fbb
[ "Unlicense" ]
5
2017-12-05T01:32:19.000Z
2019-12-15T17:42:47.000Z
openearthsdk/src/main/cpp/earth/geometry/geometry_util.cpp
Darlun1024/OpenEarth
f30f5fd2d4bb91e00d323f8c8a1d17169a3e8fbb
[ "Unlicense" ]
1
2017-12-08T06:48:41.000Z
2017-12-08T06:48:41.000Z
openearthsdk/src/main/cpp/earth/geometry/geometry_util.cpp
Darlun1024/OpenEarth
f30f5fd2d4bb91e00d323f8c8a1d17169a3e8fbb
[ "Unlicense" ]
4
2017-12-05T01:34:09.000Z
2019-12-15T17:42:53.000Z
// // Created by GXSN-Pro on 2017/12/21. // #include <glm/detail/func_geometric.inl> #include "geometry_util.hpp" using namespace OpenEarth::Geometry; glm::vec3 GeometryUtil::projectToPlane(glm::vec3 vector,glm::vec3 plane){ float a = glm::dot(vector,plane)/glm::length(plane); return vector - plane * a; }
26.583333
74
0.708464
[ "geometry", "vector" ]
d4615bb7b98e6842d1d464541c2f1addbf529a0a
33,517
cpp
C++
lib/dmitigr/pgfe/sql_string.cpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
121
2018-05-23T19:51:00.000Z
2022-03-12T13:05:34.000Z
lib/dmitigr/pgfe/sql_string.cpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
36
2019-11-11T03:25:10.000Z
2022-03-28T21:54:07.000Z
lib/dmitigr/pgfe/sql_string.cpp
dmitigr/pgfe
c5dd21c0f4949cf6ea2e71368e3c6025c3daf69a
[ "Zlib" ]
17
2018-05-24T04:01:28.000Z
2022-01-16T13:22:26.000Z
// -*- C++ -*- // Copyright (C) Dmitry Igrishin // For conditions of distribution and use, see files LICENSE.txt or pgfe.hpp #include "dmitigr/pgfe/data.hpp" #include "dmitigr/pgfe/sql_string.hpp" #include <memory> #include <cstring> #include <stdexcept> namespace dmitigr::pgfe { DMITIGR_PGFE_INLINE Sql_string::Sql_string(const std::string_view text) { auto s = parse_sql_input(text, loc_).first; swap(s); assert(is_invariant_ok()); } DMITIGR_PGFE_INLINE Sql_string::Sql_string(const std::string& text) : Sql_string{std::string_view{text}} {} DMITIGR_PGFE_INLINE Sql_string::Sql_string(const char* const text) : Sql_string{std::string_view{text, std::strlen(text)}} {} DMITIGR_PGFE_INLINE Sql_string::Sql_string(const Sql_string& rhs) : fragments_{rhs.fragments_} , positional_parameters_{rhs.positional_parameters_} , is_extra_data_should_be_extracted_from_comments_{rhs.is_extra_data_should_be_extracted_from_comments_} , extra_{rhs.extra_} { named_parameters_ = named_parameters(); } DMITIGR_PGFE_INLINE Sql_string& Sql_string::operator=(const Sql_string& rhs) { if (this != &rhs) { Sql_string tmp{rhs}; swap(tmp); } return *this; } DMITIGR_PGFE_INLINE Sql_string::Sql_string(Sql_string&& rhs) noexcept : fragments_{std::move(rhs.fragments_)} , positional_parameters_{std::move(rhs.positional_parameters_)} , is_extra_data_should_be_extracted_from_comments_{std::move(rhs.is_extra_data_should_be_extracted_from_comments_)} , extra_{std::move(rhs.extra_)} { named_parameters_ = named_parameters(); } DMITIGR_PGFE_INLINE Sql_string& Sql_string::operator=(Sql_string&& rhs) noexcept { if (this != &rhs) { Sql_string tmp{std::move(rhs)}; swap(tmp); } return *this; } DMITIGR_PGFE_INLINE void Sql_string::swap(Sql_string& rhs) noexcept { fragments_.swap(rhs.fragments_); positional_parameters_.swap(rhs.positional_parameters_); named_parameters_.swap(rhs.named_parameters_); std::swap(is_extra_data_should_be_extracted_from_comments_, rhs.is_extra_data_should_be_extracted_from_comments_); std::swap(extra_, rhs.extra_); } DMITIGR_PGFE_INLINE bool Sql_string::is_query_empty() const noexcept { return all_of(cbegin(fragments_), cend(fragments_), [this](const Fragment& f) { return is_comment(f) || (is_text(f) && is_blank_string(f.str, loc_)); }); } DMITIGR_PGFE_INLINE void Sql_string::append(const Sql_string& appendix) { const bool was_query_empty = is_query_empty(); // Updating fragments auto old_fragments = fragments_; try { fragments_.insert(cend(fragments_), cbegin(appendix.fragments_), cend(appendix.fragments_)); update_cache(appendix); // can throw (strong exception safety guarantee) if (was_query_empty) is_extra_data_should_be_extracted_from_comments_ = true; } catch (...) { fragments_.swap(old_fragments); // rollback throw; } assert(is_invariant_ok()); } DMITIGR_PGFE_INLINE void Sql_string::replace_parameter(const std::string_view name, const Sql_string& replacement) { assert(parameter_index(name) < parameter_count()); assert(this != &replacement); // Updating fragments auto old_fragments = fragments_; try { for (auto fi = begin(fragments_); fi != end(fragments_);) { if (fi->type == Fragment::Type::named_parameter && fi->str == name) { // Firstly, we'll insert the `replacement` just before `fi`. fragments_.insert(fi, cbegin(replacement.fragments_), cend(replacement.fragments_)); // Secondly, we'll erase named parameter pointed by `fi` and got the next iterator. fi = fragments_.erase(fi); } else ++fi; } update_cache(replacement); // can throw (strong exception safety guarantee) } catch (...) { fragments_.swap(old_fragments); throw; } assert(is_invariant_ok()); } DMITIGR_PGFE_INLINE std::string Sql_string::to_string() const { std::string result; result.reserve(512); for (const auto& fragment : fragments_) { switch (fragment.type) { case Fragment::Type::text: result += fragment.str; break; case Fragment::Type::one_line_comment: result += "--"; result += fragment.str; result += '\n'; break; case Fragment::Type::multi_line_comment: result += "/*"; result += fragment.str; result += "*/"; break; case Fragment::Type::named_parameter: result += ':'; result += fragment.str; break; case Fragment::Type::positional_parameter: result += '$'; result += fragment.str; break; } } result.shrink_to_fit(); return result; } DMITIGR_PGFE_INLINE std::string Sql_string::to_query_string() const { std::string result; result.reserve(512); for (const auto& fragment : fragments_) { switch (fragment.type) { case Fragment::Type::text: result += fragment.str; break; case Fragment::Type::one_line_comment: case Fragment::Type::multi_line_comment: break; case Fragment::Type::named_parameter: { const auto idx = named_parameter_index(fragment.str); assert(idx < parameter_count()); result += '$'; result += std::to_string(idx + 1); break; } case Fragment::Type::positional_parameter: result += '$'; result += fragment.str; break; } } return result; } // --------------------------------------------------------------------------- // Extra data // --------------------------------------------------------------------------- /// Represents an API for extraction the extra data from the comments. struct Sql_string::Extra final { public: /// Denotes the key type of the associated data. using Key = std::string; /// Denotes the value type of the associated data. using Value = std::unique_ptr<Data>; /// Denotes the fragment type. using Fragment = Sql_string::Fragment; /// Denotes the fragment list type. using Fragment_list = Sql_string::Fragment_list; /// @returns The vector of associated extra data. static std::vector<std::pair<Key, Value>> extract(const Fragment_list& fragments, const std::locale& loc) { std::vector<std::pair<Key, Value>> result; const auto iters = first_related_comments(fragments, loc); if (iters.first != cend(fragments)) { const auto comments = joined_comments(iters.first, iters.second); for (const auto& comment : comments) { auto associations = extract(comment.first, comment.second, loc); result.reserve(result.capacity() + associations.size()); for (auto& a : associations) result.push_back(std::move(a)); } } return result; } private: /// Represents a comment type. enum class Comment_type { /// Denotes one line comment one_line, /// Denotes multi line comment multi_line }; /** * @brief Extracts the associated data from dollar quoted literals found in comments. * * @returns Extracted data as key/value pairs. * * @param input An input string with comments. * @param comment_type A type of comments in the `input`. */ static std::vector<std::pair<Key, Value>> extract(const std::string_view input, const Comment_type comment_type, const std::locale& loc) { enum { top, dollar, dollar_quote_leading_tag, dollar_quote, dollar_quote_dollar } state = top; std::vector<std::pair<Key, Value>> result; std::string content; std::string dollar_quote_leading_tag_name; std::string dollar_quote_trailing_tag_name; const auto is_valid_tag_char = [&loc](const char c) noexcept { return isalnum(c, loc) || c == '_' || c == '-'; }; for (const auto current_char : input) { switch (state) { case top: if (current_char == '$') state = dollar; continue; case dollar: if (is_valid_tag_char(current_char)) { state = dollar_quote_leading_tag; dollar_quote_leading_tag_name += current_char; } continue; case dollar_quote_leading_tag: if (current_char == '$') { state = dollar_quote; } else if (is_valid_tag_char(current_char)) { dollar_quote_leading_tag_name += current_char; } else throw std::runtime_error{"invalid dollar quote tag"}; continue; case dollar_quote: if (current_char == '$') state = dollar_quote_dollar; else content += current_char; continue; case dollar_quote_dollar: if (current_char == '$') { if (dollar_quote_leading_tag_name == dollar_quote_trailing_tag_name) { /* * Okay, the tag's name and content are successfully extracted. * Now attempt to clean up the content before adding it to the result. */ state = top; result.emplace_back(std::move(dollar_quote_leading_tag_name), Data::make(cleaned_content(std::move(content), comment_type, loc), Data_format::text)); content = {}; dollar_quote_leading_tag_name = {}; } else state = dollar_quote; dollar_quote_trailing_tag_name.clear(); } else dollar_quote_trailing_tag_name += current_char; continue; } } if (state != top) throw std::runtime_error{"invalid comment block:\n" + std::string{input}}; return result; } /** * @brief Scans the extra data content to determine the indent size. * * @returns The number of characters to remove after each '\n'. */ static std::size_t indent_size(const std::string_view content, const Comment_type comment_type, const std::locale& loc) { const auto set_if_less = [](auto& variable, const auto count) { if (!variable) variable.emplace(count); else if (count < variable) variable = count; }; enum { counting, after_asterisk, after_non_asterisk, skiping } state = counting; std::optional<std::size_t> min_indent_to_border{}; std::optional<std::size_t> min_indent_to_content{}; std::size_t count{}; for (const auto current_char : content) { switch (state) { case counting: if (current_char == '\n') count = 0; else if (current_char == '*') state = after_asterisk; else if (isspace(current_char, loc)) ++count; else state = after_non_asterisk; continue; case after_asterisk: if (current_char == ' ') { if (min_indent_to_border) { if (count < *min_indent_to_border) { set_if_less(min_indent_to_content, *min_indent_to_border); min_indent_to_border = count; } else if (count == *min_indent_to_border + 1) set_if_less(min_indent_to_content, count); } else min_indent_to_border.emplace(count); } else set_if_less(min_indent_to_content, count); state = skiping; continue; case after_non_asterisk: set_if_less(min_indent_to_content, count); state = skiping; continue; case skiping: if (current_char == '\n') { count = 0; state = counting; } continue; } } // Calculating the result depending on the comment type. switch (comment_type) { case Comment_type::multi_line: if (min_indent_to_border) { if (min_indent_to_content) { if (min_indent_to_content <= min_indent_to_border) return 0; else if (min_indent_to_content == *min_indent_to_border + 1) return *min_indent_to_content; } return *min_indent_to_border + 1 + 1; } else return 0; case Comment_type::one_line: return min_indent_to_content ? (*min_indent_to_content == 0 ? 0 : 1) : 1; } assert(false); std::terminate(); } /** * @brief Cleans up the extra data content. * * Cleaning up includes: * - removing the indentation characters; * - trimming most leading and/or most trailing newline characters (for multiline comments only). */ static std::string cleaned_content(std::string&& content, const Comment_type comment_type, const std::locale& loc) { std::string result; // Removing the indentation characters (if any). if (const std::size_t isize = indent_size(content, comment_type, loc); isize > 0) { std::size_t count{}; enum { eating, skiping } state = eating; for (const auto current_char : content) { switch (state) { case eating: if (current_char == '\n') { count = isize; state = skiping; } result += current_char; continue; case skiping: if (count > 1) --count; else state = eating; continue; } } std::string{}.swap(content); } else result.swap(content); // Trimming the result string: remove the most leading and the most trailing newline-characters. if (const auto size = result.size(); size > 0) { std::string::size_type start{}; if (result[start] == '\r') ++start; if (start < size && result[start] == '\n') ++start; std::string::size_type end{size}; if (start < end && result[end - 1] == '\n') --end; if (start < end && result[end - 1] == '\r') --end; if (start > 0 || end < size) result = result.substr(start, end - start); } return result; } // ------------------------------------------------------------------------- // Related comments extraction // ------------------------------------------------------------------------- /** * @brief Finds very first relevant comments of the specified fragments. * * @returns The pair of iterators that specifies the range of relevant comments. */ std::pair<Fragment_list::const_iterator, Fragment_list::const_iterator> static first_related_comments(const Fragment_list& fragments, const std::locale& loc) { const auto b = cbegin(fragments); const auto e = cend(fragments); auto result = std::make_pair(e, e); const auto is_nearby_string = [](const std::string_view str, const std::locale& strloc) { std::string::size_type count{}; for (const auto c : str) { if (c == '\n') { ++count; if (count > 1) return false; } else if (!is_space(c, strloc)) break; } return true; }; /* An attempt to find the first commented out text fragment. * Stops lookup when either named parameter or positional parameter are found. * (Only fragments of type `text` can have related comments.) */ auto i = find_if(b, e, [&loc, &is_nearby_string](const Fragment& f) { return (f.type == Fragment::Type::text && is_nearby_string(f.str, loc) && !is_blank_string(f.str, loc)) || f.type == Fragment::Type::named_parameter || f.type == Fragment::Type::positional_parameter; }); if (i != b && i != e && is_text(*i)) { result.second = i; do { --i; assert(is_comment(*i) || (is_text(*i) && is_blank_string(i->str, loc))); if (i->type == Fragment::Type::text) { if (!is_nearby_string(i->str, loc)) break; } result.first = i; } while (i != b); } return result; } /** * @brief Joins first comments of the same type into the result string. * * @returns The pair of: * - the pair of the result string (comment) and its type; * - the iterator that points to the fragment that follows the last comment * appended to the result. */ std::pair<std::pair<std::string, Extra::Comment_type>, Fragment_list::const_iterator> static joined_comments_of_same_type(Fragment_list::const_iterator i, const Fragment_list::const_iterator e) { assert(is_comment(*i)); std::string result; const auto fragment_type = i->type; for (; i->type == fragment_type && i != e; ++i) { result.append(i->str); if (fragment_type == Fragment::Type::one_line_comment) result.append("\n"); } const auto comment_type = [](const Fragment::Type ft) { switch (ft) { case Fragment::Type::one_line_comment: return Extra::Comment_type::one_line; case Fragment::Type::multi_line_comment: return Extra::Comment_type::multi_line; default: assert(false); std::terminate(); } }; return std::make_pair(std::make_pair(result, comment_type(fragment_type)), i); } /** * @brief Joins all comments into the vector of strings. * * @returns The vector of pairs of: * - the joined comments as first element; * - the type of the joined comments as second element. */ std::vector<std::pair<std::string, Extra::Comment_type>> static joined_comments(Fragment_list::const_iterator i, const Fragment_list::const_iterator e) { std::vector<std::pair<std::string, Extra::Comment_type>> result; while (i != e) { if (is_comment(*i)) { auto comments = joined_comments_of_same_type(i, e); result.push_back(std::move(comments.first)); i = comments.second; } else ++i; } return result; } }; const Composite& Sql_string::extra() const { if (!extra_) extra_.emplace(Extra::extract(fragments_, loc_)); else if (is_extra_data_should_be_extracted_from_comments_) extra_->append(Composite{Extra::extract(fragments_, loc_)}); is_extra_data_should_be_extracted_from_comments_ = false; assert(is_invariant_ok()); return *extra_; } // --------------------------------------------------------------------------- // Initializers // --------------------------------------------------------------------------- void Sql_string::push_positional_parameter(const std::string& str) { push_back_fragment(Fragment::Type::positional_parameter, str); using Size = std::vector<bool>::size_type; const int position = stoi(str); if (position < 1 || static_cast<Size>(position) > max_parameter_count()) throw std::runtime_error{"invalid parameter position \"" + str + "\""}; else if (static_cast<Size>(position) > positional_parameters_.size()) positional_parameters_.resize(static_cast<Size>(position), false); positional_parameters_[static_cast<Size>(position) - 1] = true; // set parameter presence flag assert(is_invariant_ok()); } void Sql_string::push_named_parameter(const std::string& str) { if (parameter_count() < max_parameter_count()) { push_back_fragment(Fragment::Type::named_parameter, str); if (none_of(cbegin(named_parameters_), cend(named_parameters_), [&str](const auto& i) { return (i->str == str); })) { auto e = cend(fragments_); --e; named_parameters_.push_back(e); } } else throw std::runtime_error{"maximum parameters count (" + std::to_string(max_parameter_count()) + ") exceeded"}; assert(is_invariant_ok()); } // --------------------------------------------------------------------------- // Updaters // --------------------------------------------------------------------------- // Exception safety guarantee: strong. void Sql_string::update_cache(const Sql_string& rhs) { // Preparing for merge positional parameters. const auto old_pos_params_size = positional_parameters_.size(); const auto rhs_pos_params_size = rhs.positional_parameters_.size(); if (old_pos_params_size < rhs_pos_params_size) positional_parameters_.resize(rhs_pos_params_size); // can throw try { const auto new_pos_params_size = positional_parameters_.size(); assert(new_pos_params_size >= rhs_pos_params_size); // Creating the cache for named parameters. decltype (named_parameters_) new_named_parameters = named_parameters(); // can throw // Check the new parameter count. const auto new_parameter_count = new_pos_params_size + new_named_parameters.size(); if (new_parameter_count > max_parameter_count()) throw std::runtime_error{"parameter count (" + std::to_string(new_parameter_count) + ") " "exceeds the maximum (" + std::to_string(max_parameter_count()) + ")"}; // Merging positional parameters (cannot throw). for (std::size_t i = 0; i < rhs_pos_params_size; ++i) { if (!positional_parameters_[i] && rhs.positional_parameters_[i]) positional_parameters_[i] = true; } named_parameters_.swap(new_named_parameters); // commit (cannot throw) } catch (...) { positional_parameters_.resize(old_pos_params_size); // rollback throw; } assert(is_invariant_ok()); } // --------------------------------------------------------------------------- // Generators // --------------------------------------------------------------------------- auto Sql_string::unique_fragments(const Fragment::Type type) const -> std::vector<Fragment_list::const_iterator> { std::vector<Fragment_list::const_iterator> result; result.reserve(8); const auto e = cend(fragments_); for (auto i = cbegin(fragments_); i != e; ++i) { if (i->type == type) { if (none_of(cbegin(result), cend(result), [&i](const auto& result_i) { return (i->str == result_i->str); })) result.push_back(i); } } return result; } std::size_t Sql_string::unique_fragment_index( const std::vector<Fragment_list::const_iterator>& unique_fragments, const std::string_view str) const noexcept { const auto b = cbegin(unique_fragments); const auto e = cend(unique_fragments); const auto i = find_if(b, e, [&str](const auto& pi) { return (pi->str == str); }); return static_cast<std::size_t>(i - b); } // ----------------------------------------------------------------------------- // Very basic SQL input parser // ----------------------------------------------------------------------------- /* * SQL SYNTAX BASICS (from PostgreSQL documentation): * http://www.postgresql.org/docs/10/static/sql-syntax-lexical.html * * COMMANDS * * A command is composed of a sequence of tokens, terminated by a (";"). * A token can be a key word, an identifier, a quoted identifier, * a literal (or constant), or a special character symbol. Tokens are normally * separated by whitespace (space, tab, newline), but need not be if there is no * ambiguity. * * IDENTIFIERS (UNQUOTED) * * SQL identifiers and key words must begin with a letter (a-z, but also * letters with diacritical marks and non-Latin letters) or an ("_"). * Subsequent characters in an identifier or key word can be letters, * underscores, digits (0-9), or dollar signs ($). * * QUOTED IDENTIFIERS * * The delimited identifier or quoted identifier is formed by enclosing an * arbitrary sequence of characters in double-quotes ("). Quoted identifiers can * contain any character, except the character with code zero. (To include a * double quote, two double quotes should be written.) * * CONSTANTS * * STRING CONSTANTS (QUOTED LITERALS) * * A string constant in SQL is an arbitrary sequence of characters bounded * by single quotes ('), for example 'This is a string'. To include a * single-quote character within a string constant, write two adjacent * single quotes, e.g., 'Dianne''s horse'. * * DOLLAR QUOTED STRING CONSTANTS * * A dollar-quoted string constant consists of a dollar sign ($), an * optional "tag" of zero or more characters, another dollar sign, an * arbitrary sequence of characters that makes up the string content, a * dollar sign, the same tag that began this dollar quote, and a dollar * sign. * The tag, if any, of a dollar-quoted string follows the same rules * as an unquoted identifier, except that it cannot contain a dollar sign. * A dollar-quoted string that follows a keyword or identifier must be * separated from it by whitespace; otherwise the dollar quoting delimiter * would be taken as part of the preceding identifier. * * SPECIAL CHARACTERS * * - A dollar sign ("$") followed by digits is used to represent a positional * parameter in the body of a function definition or a prepared statement. * In other contexts the dollar sign can be part of an identifier or a * dollar-quoted string constant. * * - The colon (":") is used to select "slices" from arrays. In certain SQL * dialects (such as Embedded SQL), the colon is used to prefix variable * names. * [In Pgfe we will use ":" to prefix named parameters and placeholders.] * * - Brackets ([]) are used to select the elements of an array. */ namespace { /// @returns `true` if `c` is a valid character of unquoted SQL identifier. inline bool is_ident_char(const char c, const std::locale& loc) noexcept { return isalnum(c, loc) || c == '_' || c == '$'; } } // namespace /** * @returns Preparsed SQL string in pair with the pointer to a character * that follows returned SQL string. */ DMITIGR_PGFE_INLINE std::pair<Sql_string, std::string_view::size_type> Sql_string::parse_sql_input(const std::string_view text, const std::locale& loc) { enum { top, bracket, colon, named_parameter, dollar, positional_parameter, dollar_quote_leading_tag, dollar_quote, dollar_quote_dollar, quote, quote_quote, dash, one_line_comment, slash, multi_line_comment, multi_line_comment_star } state = top; Sql_string result; int depth{}; char current_char{}; char previous_char{}; char quote_char{}; std::string fragment; std::string dollar_quote_leading_tag_name; std::string dollar_quote_trailing_tag_name; const auto b = cbegin(text); auto i = b; for (const auto e = cend(text); i != e; previous_char = current_char, ++i) { current_char = *i; switch (state) { case top: switch (current_char) { case '\'': state = quote; quote_char = current_char; fragment += current_char; continue; case '"': state = quote; quote_char = current_char; fragment += current_char; continue; case '[': state = bracket; depth = 1; fragment += current_char; continue; case '$': if (!is_ident_char(previous_char, loc)) state = dollar; else fragment += current_char; continue; case ':': if (previous_char != ':') state = colon; else fragment += current_char; continue; case '-': state = dash; continue; case '/': state = slash; continue; case ';': goto finish; default: fragment += current_char; continue; } // switch (current_char) case bracket: if (current_char == ']') --depth; else if (current_char == '[') ++depth; if (depth == 0) { assert(current_char == ']'); state = top; } fragment += current_char; continue; case dollar: assert(previous_char == '$'); if (isdigit(current_char, loc)) { state = positional_parameter; result.push_text(fragment); fragment.clear(); // The first digit of positional parameter (current_char) will be stored below. } else if (is_ident_char(current_char, loc)) { if (current_char == '$') { state = dollar_quote; } else { state = dollar_quote_leading_tag; dollar_quote_leading_tag_name += current_char; } fragment += previous_char; } else { state = top; fragment += previous_char; } fragment += current_char; continue; case positional_parameter: assert(isdigit(previous_char, loc)); if (!isdigit(current_char, loc)) { state = top; result.push_positional_parameter(fragment); fragment.clear(); } if (current_char != ';') { fragment += current_char; continue; } else goto finish; case dollar_quote_leading_tag: assert(previous_char != '$' && is_ident_char(previous_char, loc)); if (current_char == '$') { fragment += current_char; state = dollar_quote; } else if (is_ident_char(current_char, loc)) { dollar_quote_leading_tag_name += current_char; fragment += current_char; } else throw std::runtime_error{"invalid dollar quote tag"}; continue; case dollar_quote: if (current_char == '$') state = dollar_quote_dollar; fragment += current_char; continue; case dollar_quote_dollar: if (current_char == '$') { if (dollar_quote_leading_tag_name == dollar_quote_trailing_tag_name) { state = top; dollar_quote_leading_tag_name.clear(); } else state = dollar_quote; dollar_quote_trailing_tag_name.clear(); } else dollar_quote_trailing_tag_name += current_char; fragment += current_char; continue; case colon: assert(previous_char == ':'); if (is_ident_char(current_char, loc)) { state = named_parameter; result.push_text(fragment); fragment.clear(); // The first character of the named parameter (current_char) will be stored below. } else { state = top; fragment += previous_char; } if (current_char != ';') { fragment += current_char; continue; } else goto finish; case named_parameter: assert(is_ident_char(previous_char, loc)); if (!is_ident_char(current_char, loc)) { state = top; result.push_named_parameter(fragment); fragment.clear(); } if (current_char != ';') { fragment += current_char; continue; } else goto finish; case quote: if (current_char == quote_char) state = quote_quote; else fragment += current_char; continue; case quote_quote: assert(previous_char == quote_char); if (current_char == quote_char) { state = quote; // Skip previous quote. } else { state = top; fragment += previous_char; // store previous quote } if (current_char != ';') { fragment += current_char; continue; } else goto finish; case dash: assert(previous_char == '-'); if (current_char == '-') { state = one_line_comment; result.push_text(fragment); fragment.clear(); // The comment marker ("--") will not be included in the next fragment. } else { state = top; fragment += previous_char; if (current_char != ';') { fragment += current_char; continue; } else goto finish; } continue; case one_line_comment: if (current_char == '\n') { state = top; if (!fragment.empty() && fragment.back() == '\r') fragment.pop_back(); result.push_one_line_comment(fragment); fragment.clear(); } else fragment += current_char; continue; case slash: assert(previous_char == '/'); if (current_char == '*') { state = multi_line_comment; if (depth > 0) { fragment += previous_char; fragment += current_char; } else { result.push_text(fragment); fragment.clear(); // The comment marker ("/*") will not be included in the next fragment. } ++depth; } else { state = (depth == 0) ? top : multi_line_comment; fragment += previous_char; fragment += current_char; } continue; case multi_line_comment: if (current_char == '/') { state = slash; } else if (current_char == '*') { state = multi_line_comment_star; } else fragment += current_char; continue; case multi_line_comment_star: assert(previous_char == '*'); if (current_char == '/') { --depth; if (depth == 0) { state = top; result.push_multi_line_comment(fragment); // without trailing "*/" fragment.clear(); } else { state = multi_line_comment; fragment += previous_char; // '*' fragment += current_char; // '/' } } else { state = multi_line_comment; fragment += previous_char; fragment += current_char; } continue; } // switch (state) } // for finish: switch (state) { case top: if (current_char == ';') ++i; if (!fragment.empty()) result.push_text(fragment); break; case quote_quote: fragment += previous_char; result.push_text(fragment); break; case one_line_comment: result.push_one_line_comment(fragment); break; case positional_parameter: result.push_positional_parameter(fragment); break; case named_parameter: result.push_named_parameter(fragment); break; default: { std::string message{"invalid SQL input"}; if (!result.fragments_.empty()) message.append(" follows after: ").append(result.fragments_.back().str); throw std::runtime_error{message}; } } return std::make_pair(result, i - b); } } // namespace dmitigr::pgfe
30.087074
117
0.615151
[ "vector" ]
d46215ea673466d81d35c7d10a4a2e608f6a9dbe
1,257
cpp
C++
openbmc_modules/ipmi-blob-tool/test/crc_unittest.cpp
Eyerunmyden/HWMgmt-MegaRAC-OpenEdition
72b03e9fc6e2a13184f1c57b8045b616db9b0a6d
[ "Apache-2.0", "MIT" ]
14
2021-11-04T07:47:37.000Z
2022-03-21T10:10:30.000Z
openbmc_modules/ipmi-blob-tool/test/crc_unittest.cpp
Eyerunmyden/HWMgmt-MegaRAC-OpenEdition
72b03e9fc6e2a13184f1c57b8045b616db9b0a6d
[ "Apache-2.0", "MIT" ]
null
null
null
openbmc_modules/ipmi-blob-tool/test/crc_unittest.cpp
Eyerunmyden/HWMgmt-MegaRAC-OpenEdition
72b03e9fc6e2a13184f1c57b8045b616db9b0a6d
[ "Apache-2.0", "MIT" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
#include <ipmiblob/crc.hpp> #include <cstdint> #include <string> #include <vector> #include <gtest/gtest.h> namespace ipmiblob { TEST(Crc16Test, VerifyCrcValue) { // Verify the crc16 is producing the value we expect. // Origin: security/crypta/ipmi/portable/ipmi_utils_test.cc struct CrcTestVector { std::string input; uint16_t output; }; std::string longString = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAA"; std::vector<CrcTestVector> vectors({{"", 0x1D0F}, {"A", 0x9479}, {"123456789", 0xE5CC}, {longString, 0xE938}}); for (const CrcTestVector& testVector : vectors) { std::vector<std::uint8_t> input; input.insert(input.begin(), testVector.input.begin(), testVector.input.end()); EXPECT_EQ(generateCrc(input), testVector.output); } } } // namespace ipmiblob
28.568182
70
0.626094
[ "vector" ]
d469228314bf7e08cb2120a7334de72b590967e5
1,075
cpp
C++
solutions/1138.alphabet-board-path.328653183.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/1138.alphabet-board-path.328653183.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/1138.alphabet-board-path.328653183.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: string alphabetBoardPath(string target) { vector<pair<int, int>> positions; for (int i = 0; i < 26; i++) positions.emplace_back(i / 5, i % 5); string ans; char start = 'a'; for (char c : target) { ans += path(start, c, positions); ans += '!'; start = c; } return ans; } string path(char from, char to, vector<pair<int, int>> &positions) { if (from == to) return ""; int x1 = positions[from - 'a'].first; int y1 = positions[from - 'a'].second; int x2 = positions[to - 'a'].first; int y2 = positions[to - 'a'].second; string result = ""; if (x1 == 5) { result += 'U'; x1--; } else if (x2 == 5) { while (y1) { result += 'L'; y1--; } } while (x1 < x2) { result += 'D'; x1++; } while (x1 > x2) { result += 'U'; x1--; } while (y1 < y2) { result += 'R'; y1++; } while (y1 > y2) { result += 'L'; y1--; } return result; } };
17.916667
70
0.447442
[ "vector" ]
d46d22141476573d0324455d38e7499d96a9b911
658
cpp
C++
src/amazebot.cpp
Robotcraft19/amazebot-ros-driver
b3fa0b967cc3bd56c85118e78de55ff07af5b79d
[ "MIT" ]
1
2020-04-15T12:08:13.000Z
2020-04-15T12:08:13.000Z
src/amazebot.cpp
Robotcraft19/amazebot-ros-driver
b3fa0b967cc3bd56c85118e78de55ff07af5b79d
[ "MIT" ]
null
null
null
src/amazebot.cpp
Robotcraft19/amazebot-ros-driver
b3fa0b967cc3bd56c85118e78de55ff07af5b79d
[ "MIT" ]
null
null
null
/** * @file amazebot.cpp * @author Nicolas Filliol <nicolas.filliol@icloud.com>, Erwin Lejeune <erwin.lejeune15@gmail.com>, * Oleksandr Koreiba<alex@koreiba.com>, Jan Tiepelt, * Giovanni Alexander Bergamaschi * @brief Amazebot Controller Class * @version 0.1 * @date 2019-08-11 * * @copyright Copyright (c) 2019 * */ #include "amazebot_controller.h" int main(int argc, char **argv) { // Initialize ROS ros::init(argc, argv, "amazebot_controller"); // Create our controller object and run it auto controller = AmazebotController(); controller.run(); // And make good on our promise return 0; }
21.933333
100
0.662614
[ "object" ]
d46feccd469e525123532cf38ae6a6e6b9c4335c
16,207
hxx
C++
qi/detail/trackable.hxx
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
qi/detail/trackable.hxx
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
qi/detail/trackable.hxx
yumilceh/libqi
f094bcad506bcfd5a8dcfa7688cbcce864b0765b
[ "BSD-3-Clause" ]
null
null
null
#pragma once /* * Copyright (c) 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifndef _QI_DETAIL_TRACKABLE_HXX_ #define _QI_DETAIL_TRACKABLE_HXX_ #include <type_traits> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/weak_ptr.hpp> #include <boost/function_types/result_type.hpp> namespace qi { class Actor; template<typename T> inline Trackable<T>::Trackable() : _wasDestroyed(false) { T* thisAsT = static_cast<T*>(this); _ptr = boost::shared_ptr<T>(thisAsT, boost::bind(&Trackable::_destroyed, _1)); } template<typename T> inline Trackable<T>::Trackable(T* ptr) : _wasDestroyed(false) { _ptr = boost::shared_ptr<T>(ptr, boost::bind(&Trackable::_destroyed, _1)); } template<typename T> inline void Trackable<T>::destroy() { _ptr.reset(); wait(); } template<typename T> inline void Trackable<T>::wait() { boost::mutex::scoped_lock lock(_mutex); while (!_wasDestroyed) { _cond.wait(lock); } } template<typename T> inline void Trackable<T>::_destroyed() { // unblock boost::mutex::scoped_lock lock(_mutex); _wasDestroyed = true; _cond.notify_all(); } template<typename T> inline Trackable<T>::~Trackable() { // We expect destroy() to have been called from parent destructor, so from // this thread. if (!_wasDestroyed) { qiLogError("qi.Trackable") << "Trackable destroyed without calling destroy()"; // do it to mitigate the effect, but it's too late destroy(); } } template<typename T> inline boost::weak_ptr<T> Trackable<T>::weakPtr() { return boost::weak_ptr<T>(_ptr); } namespace detail { template <typename T> T defaultConstruct() { return T{}; // Default constructor might be explicit, so we are forced to call it explicitly. } template <> inline void defaultConstruct<void>() { } // Functor that locks a weak ptr and make a call if successful // Generalize on shared_ptr and weak_ptr types in case we ever have // other types with their semantics template <typename WT, typename F> class LockAndCall { WT _wptr; F _f; boost::function<void()> _onFail; public: LockAndCall(WT arg, F func, boost::function<void()> onFail) : _wptr(std::move(arg)) , _f(std::move(func)) , _onFail(std::move(onFail)) {} template <typename... Args> // decltype(this->_f(std::forward<Args>(args)...)) does not work on vs2013 \o/ auto operator()(Args&&... args) -> decltype(std::declval<F>()(std::forward<Args>(args)...)) { auto s = _wptr.lock(); if (s) return _f(std::forward<Args>(args)...); else { if (_onFail) _onFail(); // hehe, you can't write return {}; because of void here... -_- return defaultConstruct<decltype(this->_f(std::forward<Args>(args)...))>(); } } }; template <typename T, bool IsActor> struct ObjectWrap; template <typename T> struct ObjectWrap<T, false> { template <typename F> using wrap_type = typename std::decay<F>::type; template <typename F> static wrap_type<F> wrap(const T& arg, F&& func, boost::function<void()> onFail) { return std::forward<F>(func); } }; template <typename T> struct ObjectWrap<T, true> { static const bool is_async = true; template <typename F> using wrap_type = decltype( std::declval<T>()->strandedUnwrapped(std::declval<typename std::decay<F>::type>())); template <typename F> static wrap_type<F> wrap(const T& arg, F&& func, boost::function<void()> onFail) { return arg->strandedUnwrapped(std::forward<F>(func), std::move(onFail)); } }; struct IsAsyncBindImpl { struct ArbitraryBigBuf { char arbitrary_buf[128]; }; template <typename T> static decltype(T::is_async) f(int); template <typename T> static ArbitraryBigBuf f(void*); }; // can't use a "using" here because visual gets the SFINAE wrong in the conditional (lol.) template <typename T> struct IsAsyncBind : std::conditional<sizeof(decltype(IsAsyncBindImpl::template f<T>(0))) != sizeof(IsAsyncBindImpl::ArbitraryBigBuf), std::true_type, std::false_type>::type { }; template <typename T, bool IsTrackable> struct BindTransformImpl { static T transform(T arg) { return arg; } template <typename F> using wrap_type = typename std::decay<F>::type; template <typename F> static wrap_type<F> wrap(T arg, F&& func, boost::function<void()> onFail) { return std::forward<F>(func); } }; template <typename T> struct BindTransformImpl<T*, false> { using ObjectWrapType = ObjectWrap<T*, std::is_base_of<Actor, T>::value>; template <typename F> using wrap_type = typename ObjectWrapType::template wrap_type<F>; static T* transform(T* arg) { return arg; } template <typename F> static wrap_type<F> wrap(T* arg, F&& func, boost::function<void()> onFail) { return ObjectWrapType::wrap(arg, std::forward<F>(func), onFail); } }; template <typename T> struct BindTransformImpl<T*, true> { template <typename F> using wrap_type = LockAndCall<boost::weak_ptr<T>, typename std::decay<F>::type>; static T* transform(T* arg) { // Note that we assume that lock if successful always return the same pointer return arg; } template <typename F> static wrap_type<F> wrap(T* arg, F&& func, boost::function<void()> onFail) { return LockAndCall<boost::weak_ptr<T>, typename std::decay<F>::type>( arg->weakPtr(), std::forward<F>(func), onFail); } }; template <typename T> struct BindTransformImpl<boost::weak_ptr<T>, false> { template <typename F> using wrap_type = LockAndCall<boost::weak_ptr<T>, typename std::decay<F>::type>; static T* transform(const boost::weak_ptr<T>& arg) { // Note that we assume that lock if successful always return the same pointer // And that if lock fails once, it will fail forever from that point return arg.lock().get(); } template <typename F> static wrap_type<F> wrap(const boost::weak_ptr<T>& arg, F&& func, boost::function<void()> onFail) { return LockAndCall<boost::weak_ptr<T>, typename std::decay<F>::type>( arg, std::forward<F>(func), onFail); } }; template <typename T> struct BindTransformImpl<boost::shared_ptr<T>, false> { using ObjectWrapType = ObjectWrap<boost::shared_ptr<T>, std::is_base_of<Actor, T>::value>; template <typename F> using wrap_type = typename ObjectWrapType::template wrap_type<F>; static boost::shared_ptr<T> transform(boost::shared_ptr<T> arg) { return std::move(arg); } template <typename F> static wrap_type<F> wrap(const boost::shared_ptr<T>& arg, F&& func, boost::function<void()> onFail) { return ObjectWrapType::wrap(arg, std::forward<F>(func), onFail); } }; template <typename T> using BindTransform = BindTransformImpl<typename std::decay<T>::type, std::is_base_of<TrackableBase, typename std::remove_pointer<typename std::decay<T>::type>::type>::value>; inline void throwPointerLockException() { throw PointerLockException(); } } template <typename RF, typename AF, typename Arg0, typename... Args> QI_API_DEPRECATED_MSG(Use 'bindWithFallback' without explicit template method signature) typename std::enable_if<std::is_function<RF>::value, boost::function<RF>>::type bindWithFallback(boost::function<void()> onFail, AF&& fun, Arg0&& arg0, Args&&... args) { using Transform = detail::BindTransform<Arg0>; auto transformed = Transform::transform(arg0); boost::function<RF> f = boost::bind(std::forward<AF>(fun), std::move(transformed), std::forward<Args>(args)...); return Transform::wrap(arg0, std::move(f), std::move(onFail)); } template <typename RF, typename AF, typename Arg0, typename... Args> QI_API_DEPRECATED_MSG(Use 'bindSilent' without explicit template method signature) typename std::enable_if<std::is_function<RF>::value, boost::function<RF>>::type bindSilent(AF&& fun, Arg0&& arg0, Args&&... args) { return bindWithFallback<RF, AF>({}, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...); } template <typename RF, typename AF, typename Arg0, typename... Args> QI_API_DEPRECATED_MSG(Use 'bind' without explicit template method signature) typename std::enable_if<std::is_function<RF>::value, boost::function<RF>>::type bind(AF&& fun, Arg0&& arg0, Args&&... args) { return bindWithFallback<RF, AF>(detail::throwPointerLockException, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...); } namespace detail { template<typename AF, typename Arg0, typename... Args> struct WorkaroundVS2015 // TODO: Remove once we upgrade from VS2015 { using type = decltype(boost::bind( std::declval<AF>(), detail::BindTransform<Arg0>::transform(std::declval<Arg0>()), std::declval<Args>()...)); }; } template <typename AF, typename Arg0, typename... Args> auto bindWithFallback(boost::function<void()> onFail, AF&& fun, Arg0&& arg0, Args&&... args) -> typename detail::BindTransform<Arg0>::template wrap_type< typename detail::WorkaroundVS2015<AF, Arg0, Args...>::type > { using Transform = detail::BindTransform<Arg0>; auto transformed = Transform::transform(arg0); return Transform::wrap(arg0, boost::bind(std::forward<AF>(fun), std::move(transformed), std::forward<Args>(args)...), std::move(onFail)); } template <typename AF, typename Arg0, typename... Args> auto bindSilent(AF&& fun, Arg0&& arg0, Args&&... args) -> decltype(bindWithFallback({}, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...)) { return bindWithFallback({}, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...); } template <typename AF, typename Arg0, typename... Args> auto bind(AF&& fun, Arg0&& arg0, Args&&... args) -> decltype(bindWithFallback(detail::throwPointerLockException, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...)) { return bindWithFallback(detail::throwPointerLockException, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...); } template <typename R, typename T, typename Instance, typename... Args0, typename... Args1> auto bind(R(T::*fun)(Args0...), Instance&& instance, Args1&&... args1) -> decltype(bindWithFallback(detail::throwPointerLockException, fun, std::forward<Instance>(instance), std::forward<Args1>(args1)...)) { return bindWithFallback(detail::throwPointerLockException, fun, std::forward<Instance>(instance), std::forward<Args1>(args1)...); } // with support for R template <typename R, typename AF, typename Arg0, typename... Args> auto bindWithFallback(boost::function<void()> onFail, AF&& fun, Arg0&& arg0, Args&&... args) -> typename std::enable_if<!std::is_function<R>::value, typename detail::BindTransform<Arg0>::template wrap_type< decltype(boost::bind<R>(std::forward<AF>(fun), detail::BindTransform<Arg0>::transform(arg0), std::forward<Args>(args)...))>>::type { using Transform = detail::BindTransform<Arg0>; auto transformed = Transform::transform(arg0); return Transform::wrap(arg0, boost::bind<R>(std::forward<AF>(fun), std::move(transformed), std::forward<Args>(args)...), std::move(onFail)); } template <typename R, typename AF, typename Arg0, typename... Args> auto bindSilent(AF&& fun, Arg0&& arg0, Args&&... args) -> typename std::enable_if<!std::is_function<R>::value, decltype(bindWithFallback<R>({}, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...))>::type { return bindWithFallback<R>({}, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...); } template <typename R, typename AF, typename Arg0, typename... Args> auto bind(AF&& fun, Arg0&& arg0, Args&&... args) -> typename std::enable_if<!std::is_function<R>::value, decltype(bindWithFallback<R>(detail::throwPointerLockException, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...))>::type { return bindWithFallback<R>(detail::throwPointerLockException, std::forward<AF>(fun), std::forward<Arg0>(arg0), std::forward<Args>(args)...); } template <typename F, typename T> auto trackWithFallback(boost::function<void()> onFail, F&& f, T&& toTrack) -> decltype(detail::BindTransform<T>::wrap(std::forward<T>(toTrack), std::forward<F>(f), std::move(onFail))) { return detail::BindTransform<T>::wrap(std::forward<T>(toTrack), std::forward<F>(f), std::move(onFail)); } template <typename F, typename T> auto track(F&& f, T&& toTrack) -> decltype(trackWithFallback(detail::throwPointerLockException, std::forward<F>(f), std::forward<T>(toTrack))) { return trackWithFallback(detail::throwPointerLockException, std::forward<F>(f), std::forward<T>(toTrack)); } template <typename F, typename T> auto trackSilent(F&& f, T&& toTrack) -> decltype(trackWithFallback({}, std::forward<F>(f), std::forward<T>(toTrack))) { return trackWithFallback({}, std::forward<F>(f), std::forward<T>(toTrack)); } template<typename F, typename T> boost::function<F> trackWithFallback( boost::function<void()> onFail, boost::function<F> f, const T& toTrack) { return detail::BindTransform<T>::wrap(toTrack, std::move(f), std::move(onFail)); } template<typename F, typename T> boost::function<F> trackSilent(boost::function<F> f, const T& toTrack) { return trackWithFallback<F, T>({}, std::move(f), toTrack); } template<typename F, typename T> boost::function<F> track(boost::function<F> f, const T& toTrack) { return trackWithFallback<F, T>(detail::throwPointerLockException, std::move(f), toTrack); } } #endif // _QI_DETAIL_TRACKABLE_HXX_
35.856195
159
0.581169
[ "transform" ]
d472dab459899e9c6cc23b512543e7991bf0e2eb
5,558
cc
C++
src/libmess/extra/harmonic.cc
dsjense/MESS
b54c161327e2e35a40bb3b71555bdc2eef7cd7f9
[ "Apache-2.0" ]
9
2020-03-03T07:34:35.000Z
2021-12-08T13:12:16.000Z
src/libmess/extra/harmonic.cc
dsjense/MESS
b54c161327e2e35a40bb3b71555bdc2eef7cd7f9
[ "Apache-2.0" ]
1
2022-03-23T10:57:25.000Z
2022-03-31T12:30:44.000Z
src/libmess/extra/harmonic.cc
dsjense/MESS
b54c161327e2e35a40bb3b71555bdc2eef7cd7f9
[ "Apache-2.0" ]
9
2019-12-18T19:59:13.000Z
2022-01-31T01:49:43.000Z
#include "harmonic.hh" #include "io.hh" /******************************************************************************************* ****************** HARMONIC EXPANSION OF THE ANGULAR PART OF THE POTENTIAL ***************** *******************************************************************************************/ std::ostream& operator<< (std::ostream& to, const HarmonicExpansion& hex) { to << hex._expansion.size() << "\n"; for(int x = 0; x < hex._expansion.size(); ++x) { for(std::map<int, double>::const_iterator it = hex._expansion[x].begin(); it != hex._expansion[x].end(); ++it) to << it->first << " " << it->second << " "; to << "\n"; } return to; } HarmonicExpansion::HarmonicExpansion (std::istream& from, int rdim, int qdim) throw(Error::General) : _rmonom(rdim, 3), _qmonom(2 * qdim, 4) { const char funame [] = "HarmonicExpansion::HarmonicExpansion: "; int itemp; double dtemp; std::string stemp; from >> itemp; std::getline(from, stemp); _expansion.resize(itemp); for(int x = 0; x < _expansion.size(); ++x) { IO::LineInput lin(from); while(lin >> itemp >> dtemp) _expansion[x][itemp] = dtemp; } if(!from) { std::cerr << funame << "corrupted\n"; throw Error::Input(); } } HarmonicExpansion::HarmonicExpansion (const Configuration::DoubleSpaceGroup& symm_group, int rdim, int qdim) throw(Error::General) : _rmonom(rdim, 3), _qmonom(2 * qdim, 4) { const char funame [] = "HarmonicExpansion::HarmonicExpansion: "; static const double tolerance = 1.e-10; IO::Marker funame_marker(funame); int itemp; double dtemp; const int xsize = _rmonom.linear_size() * _qmonom.linear_size(); IO::log << IO::log_offset << "(" << rdim << ", " << qdim << ")-expansion dimension = " << xsize << std::endl; Lapack::Matrix project(xsize); project = 0.; Lapack::SymmetricMatrix product(xsize); product = 0.; Lapack::Matrix a(xsize); for(int g = 0; g < symm_group.size(); ++g) { IO::log << IO::log_offset << std::setw(3) << g + 1 << " out of " << symm_group.size() << " symmetry elements" << std::endl; Lapack::Matrix rmatrix = _rmonom(symm_group.rmatrix(g)); Lapack::Matrix qmatrix = _qmonom(symm_group.qmatrix(g)); #pragma omp parallel for default(shared) private(dtemp) schedule(dynamic) for(int i = 0; i < xsize; ++i) for(int j = 0; j < xsize; ++j) { dtemp = rmatrix(i / _qmonom.linear_size(), j / _qmonom.linear_size()) * qmatrix(i % _qmonom.linear_size(), j % _qmonom.linear_size()); a(i, j) = dtemp; project(i, j) += dtemp; } #pragma omp parallel for default(shared) schedule(dynamic) for(int i = 0; i < xsize; ++i) for(int j = i; j < xsize; ++j) product(i, j) += vdot(a.row(i), a.row(j)); } product /= (double)symm_group.size(); project /= (double)symm_group.size(); project = project * product; IO::log << IO::log_offset << "diagonalizing symmetry group projector ... "; Lapack::Matrix evec; Lapack::Vector eval = Lapack::diagonalize(Lapack::SymmetricMatrix(project), product, &evec); IO::log << "done" << std::endl; // checking eigenvalues for(int i = 0; i < xsize; ++i) { dtemp = eval[i]; if(dtemp > - tolerance && dtemp < tolerance) continue; dtemp -= 1.; if(dtemp > - tolerance && dtemp < tolerance) continue; std::cerr << funame << "not projector\n"; throw Error::Range(); } itemp = -1; for(int i = 0; i < xsize; ++i) { if(itemp < 0 && eval[i] > 1. - tolerance) { itemp = 0; _expansion.resize(xsize - i); } if(itemp >= 0) { for(int j = 0; j < xsize; ++j) { dtemp = evec(j, i); if(dtemp < -tolerance || dtemp > tolerance) _expansion[itemp][j] = dtemp; } ++itemp; } } itemp = 0; for(int x = 0; x < _expansion.size(); ++x) itemp += _expansion[x].size(); IO::log << IO::log_offset << "symmetric monomials number = " << _expansion.size() << "; total number of non-zero terms = " << itemp << std::endl; } double HarmonicExpansion::operator() (int term, const Configuration::State& state) const throw(Error::General) { const char funame [] = "HarmonicExpansion::operator(): "; double dtemp; //check layout if(state.size() != 7) { std::cerr << funame << "wrong layout\n"; throw Error::Logic(); } if(term < 0 || term >= size()) { std::cerr << funame << "out of range\n"; throw Error::Range(); } Lapack::Matrix rfactor(_rmonom.rank(), 3); for(int i = 0; i < 3; ++i) { dtemp = state.radius_vector()[i]; for(int j = 0; j < _rmonom.rank(); ++j, dtemp *= state.radius_vector()[i]) rfactor(j, i) = dtemp; } Lapack::Matrix qfactor(_qmonom.rank(), 4); for(int i = 0; i < 4; ++i) { dtemp = state.orientation()[i]; for(int j = 0; j < _qmonom.rank(); ++j, dtemp *= state.orientation()[i]) qfactor(j, i) = dtemp; } double res = 0.; //#pragma omp parallel for default(shared) private(dtemp) reduction(+: res) schedule(static) for(std::map<int, double>::const_iterator it = _expansion[term].begin(); it != _expansion[term].end(); ++it) { dtemp = it->second; std::vector<int> multi = _rmonom(it->first / _qmonom.linear_size()); for(int i = 0; i < 3; ++i) if(multi[i]) dtemp *= rfactor(multi[i] - 1, i); multi = _qmonom(it->first % _qmonom.linear_size()); for(int i = 0; i < 4; ++i) if(multi[i]) dtemp *= qfactor(multi[i] - 1, i); res += dtemp; } return res; }
27.929648
115
0.564052
[ "vector" ]
d47928692cb958edf00ade4fd242ada3e3460422
12,545
cpp
C++
CPPProjects/SubtreeSize.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
39
2018-08-26T05:53:19.000Z
2021-12-11T07:47:24.000Z
CPPProjects/SubtreeSize.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
1
2018-06-21T00:40:41.000Z
2018-06-21T00:40:46.000Z
CPPProjects/SubtreeSize.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
8
2018-08-27T00:34:23.000Z
2020-09-27T12:51:22.000Z
//#define SUBMIT #ifdef SUBMIT #define LOGLEVEL 0 #define NDEBUG #else #define LOGLEVEL 1 #endif #include <cstdio> #include <algorithm> #include <cstring> #include <cassert> #include <iostream> #include <vector> #include <map> #include <set> #include <cmath> #include <cstdlib> #include <array> #include <type_traits> #include <queue> #include <stack> #include <functional> using namespace std; #define LOG(l, x) if (l <= LOGLEVEL) cout << x << endl #define int64 long long #define repeat(x) for (auto repeat_var = 0; repeat_var < x; ++repeat_var) #define for_inc(i, x) for (auto i = 0; i < x; ++i) #define for_dec(i, x) for (auto i = x - 1; i >= 0; --i) #define for_inc_range(i, x, y) for (auto i = x; i <= y; ++i) #define for_dec_range(i, x, y) for (auto i = x; i >= y; --i) #define fill0(x) memset(x, 0, sizeof(x)) #define INT_INF ((int)2E9L) #define INT64_INF ((int64)1E18L) #define MOD 1000000007 int MODP(int64 x) { int r = x % MOD; if (r < 0) r += MOD; return r; } template <class T, class Q> using TreeMergeFunction = function<Q(const Q &, const Q &)>; template <class T, class Q> using TreeUpdateLeafFunction = function<Q(const Q &, const T &, const T &, int, int)>; template <class T, class Q> using TreeSplitFunction = function<void(Q &, Q &, Q &, T, int, int, int)>; template <class T, class Q> using TreeInitFunction = function<Q(const T&, int, int)>; template <class T, class Q> struct SegmentTree { struct TreeNode { bool leaf = true; // All elements in the leaf node's segment are the same T value; Q query; int leftChild = -1, rightChild = -1; // index of the left and right children, -1 for no child }; vector<TreeNode> node; TreeMergeFunction<T, Q> merge; TreeUpdateLeafFunction<T, Q> updateLeaf; TreeSplitFunction<T, Q> split; TreeInitFunction<T, Q> init; const T defaultValue; int addNode(int l, int r) { TreeNode newNode; newNode.value = defaultValue; node.push_back(newNode); return (int)node.size() - 1; } void splitNode(int p, int l, int r) { assert(node[p].leaf); int m = (l + r) / 2; node[p].leaf = false; if (node[p].leftChild == -1) { int c = addNode(l, m); node[p].leftChild = c; c = addNode(m + 1, r); node[p].rightChild = c; } int lc = node[p].leftChild; int rc = node[p].rightChild; node[lc].leaf = true; node[rc].leaf = true; node[lc].value = node[p].value; node[rc].value = node[p].value; split(node[p].query, node[lc].query, node[rc].query, node[p].value, l, m, r); } void update(int p, int l, int r, int i, int j, const T &v) { if (j < l || i > r) return; int m = (l + r) / 2; if (i <= l && r <= j) { // [i,j] covers [l,r] if (node[p].leaf) { node[p].query = updateLeaf(node[p].query, node[p].value, v, l, r); node[p].value = v; return; } else { node[p].leaf = true; node[p].value = v; } } else if (node[p].leaf) { // [i,j] intersects [l, r] splitNode(p, l, r); } update(node[p].leftChild, l, m, i, j, v); update(node[p].rightChild, m + 1, r, i, j, v); node[p].query = merge(node[node[p].leftChild].query, node[node[p].rightChild].query); } Q query(int p, int l, int r, int i, int j) { if (i <= l && r <= j) { // [i,j] contains [l,r] return node[p].query; } if (node[p].leaf) { // [i,j] intersects [l, r] splitNode(p, l, r); } int m = (l + r) / 2; Q ret; if (j <= m) { ret = query(node[p].leftChild, l, m, i, j); } else if (i >= m + 1) { ret = query(node[p].rightChild, m + 1, r, i, j); } else { ret = merge(query(node[p].leftChild, l, m, i, j), query(node[p].rightChild, m + 1, r, i, j)); } node[p].query = merge(node[node[p].leftChild].query, node[node[p].rightChild].query); return ret; } int minIndex, maxIndex; int root; public: // First way to specify a segment tree, usually use when lazy propagation is needed. // Q merge(Q, Q) that merges the query from left and right children // Q updateLeaf(Q cur, T oldV, T curV, int l, int r) return the updated // query in a leaf node if its old value is oldV and new value is curV // split(Q& cur, Q &lChild, Q &rChild, int curV, int l, int m, int r) // modify the query in the current node and it's left and right children when // a split action happens. SegmentTree(int minIndex, int maxIndex, T defaultValue, const TreeMergeFunction<T, Q> &merge, const TreeUpdateLeafFunction<T, Q> &updateLeaf, const TreeSplitFunction<T, Q> &split) : merge(merge), updateLeaf(updateLeaf), split(split), defaultValue(defaultValue), minIndex(minIndex), maxIndex(maxIndex) { root = addNode(minIndex, maxIndex); } // The second way to specify a segment tree: // a merge function // an init function (v, l, r) that initilize the query based on // the value of the node and the node interval SegmentTree(int minIndex, int maxIndex, T defaultValue, const TreeMergeFunction<T, Q> &merge, const function<Q(T, int, int)> &init) : merge(merge), defaultValue(defaultValue), minIndex(minIndex), maxIndex(maxIndex), init(init) { updateLeaf = [&] (const Q &cur, T oldV, T curV, int l, int r) { return this->init(curV, l, r); }; split = [&](Q &cur, Q &lQ, Q &rQ, T v, int l, int m, int r) { lQ = this->init(v, l, m); rQ = this->init(v, m + 1, r); }; root = addNode(minIndex, maxIndex); } // Set all elements in [i, j] to be v void update(int i, int j, T v) { update(root, minIndex, maxIndex, i, j, v); } // Query augmented data in [i, j] Q query(int i, int j) { return query(root, minIndex, maxIndex, i, j); } // Query augmented data in the whole range Q query() { return query(root, minIndex, maxIndex, minIndex, maxIndex); } }; // Weighted undirected tree template <class T> class WeightedTree { vector<vector<pair<int, T>>> adj; // p [u] = parent of u and weight p[u] -> u vector<pair<int, T>> p; vector<int> depth; int n; int root; public: const vector<pair<int, T>> &getAdjacent(int u) const { return adj[u]; } void reset(int size) { this->n = size; adj.resize(n + 1); for_inc_range(i, 1, n) adj[i].clear(); p.resize(n + 1); depth.resize(n + 1); for_inc_range(i, 1, n) { p[i] = make_pair(-1, -1); depth[i] = 0; } } WeightedTree() {} WeightedTree(int n) { reset(n); } void dfs(int u) { stack<int> node; node.push(u); while (!node.empty()) { u = node.top(); node.pop(); for (auto &e : adj[u]) { int v = e.first; int c = e.second; if (p[v].first == -1) { p[v] = make_pair(u, c); depth[v] = depth[u] + 1; node.push(v); } } } } int getParent(int u) const { return p[u].first; } T getWeight(int u) const { return p[u].second; } void setWeight(int u, T w) { p[u].second = w; } int getDepth(int u) const { return depth[u]; } size_t getSize() const { return n; } int getRoot() const { return root; } void setRoot(int u) { for_inc_range(v, 1, n) { p[v].first = -1; } root = u; p[root].first = -2; dfs(root); } void addEdge(int u, int v, int c) { adj[u].push_back(make_pair(v, c)); adj[v].push_back(make_pair(u, c)); } }; template<class T> class SubtreeSize { const WeightedTree<T> &tree; vector<int> subtreeSize; vector<bool> visit; void dfs(int u) { stack<int> node; node.push(u); while (!node.empty()) { u = node.top(); if (visit[u]) { node.pop(); subtreeSize[u] = 1; } for (auto &v: tree.getAdjacent(u)) { if (v.first != tree.getParent(u)) { if (!visit[u]) { node.push(v.first); } else { subtreeSize[u] += subtreeSize[v.first]; } } } visit[u] = true; } } public: SubtreeSize(const WeightedTree<T> &tree): tree(tree) { subtreeSize.resize(tree.getSize() + 1); visit.resize(tree.getSize() + 1); dfs(tree.getRoot()); } const int operator[](int u) const { assert(1 <= u && u <= tree.getSize()); return subtreeSize[u]; } }; template<class T> class HeavyLightDecomposition { const WeightedTree<T> &tree; int timeStamp; vector<int> start; vector<int> head; vector<int> node; int n; void dfs(int u, const SubtreeSize<T> &subtreeSize) { stack<int> s; s.push(u); while (!s.empty()) { u = s.top(); s.pop(); timeStamp++; node[timeStamp] = u; start[u] = timeStamp; int heavyCutoff = subtreeSize[u] / 2; int nextNode = -1; for (auto &v: tree.getAdjacent(u)) { if (v.first != tree.getParent(u)) { if (subtreeSize[v.first] > heavyCutoff) { nextNode = v.first; break; } } } for (auto &v: tree.getAdjacent(u)) { if (v.first != tree.getParent(u) && v.first != nextNode) { head[v.first] = v.first; s.push(v.first); } } if (nextNode != -1) { head[nextNode] = head[u]; // Tricky: in non-recursive DFS, if you want to visit nextNode first, // you have to push it last into the stack s.push(nextNode); } } } public: HeavyLightDecomposition(const WeightedTree<T> &tree): tree(tree) { n = (int) tree.getSize(); timeStamp = 0; SubtreeSize<int> subtreeSize(tree); start.resize(n + 1); head.resize(n + 1); node.resize(n + 1); head[tree.getRoot()] = tree.getRoot(); dfs(tree.getRoot(), subtreeSize); } // is the path parent[u] to u light? bool isLight(int u) const { assert(u != tree.getRoot()); assert(1 <= u && u <= n); return head[u] == u; } bool isHeavy(int u) const { return !isLight(u); } int getHead(int u) const { assert(1 <= u && u <= n); return head[u]; } int getStartTime(int u) const { assert(1 <= u && u <= n); return start[u]; } int getNodeAtTime(int timeStamp) const { return node[timeStamp]; } int getHeadTime(int u) const { assert(1 <= u && u <= n); return start[head[u]]; } bool inSameHeavyPath(int u, int v) const { assert(1 <= u && u <= n); return head[u] == head[v]; } }; void testGen() { freopen("biginput1.txt", "w", stdout); fclose(stdout); } int queryUp(int u, int v, const vector<int> &color, const WeightedTree<int> &tree, const HeavyLightDecomposition<int> &hld, SegmentTree<int, int> &seg) { // v is ancestor of u int res = INT_INF; while (1) { if (color[u] == 1) { res = u; } if (u == v) { break; } if (hld.isLight(u)) { u = tree.getParent(u); } else { if (hld.inSameHeavyPath(u, v)) { int t = seg.query(hld.getStartTime(v), hld.getStartTime(u)); if (t != INT_INF) { res = hld.getNodeAtTime(t); } return res; } else { int t = seg.query(hld.getHeadTime(u), hld.getStartTime(u)); if (t != INT_INF) { res = hld.getNodeAtTime(t); } u = hld.getHead(u); } } } return res; } // Sample: SPOJ - QTREE3 int main() { ios::sync_with_stdio(false); #ifndef SUBMIT freopen("biginput1.txt", "r", stdin); freopen("biginput1.out", "w", stdout); #endif int n, q; scanf("%d%d", &n, &q); WeightedTree<int> tree; tree.reset(n); vector<pair<int, int>> edge; repeat(n - 1) { int u, v; scanf("%d%d", &u, &v); tree.addEdge(u, v, 1); edge.push_back(make_pair(u, v)); } tree.setRoot(1); HeavyLightDecomposition<int> hld(tree); SegmentTree<int, int> seg(1, n, 0, [](int l, int r) {return min(l, r);}, [](int v, int l, int r) {return (v == 1) ? l : INT_INF;}); seg.update(1, n, 0); vector<int> color(n + 1); repeat(q) { int t; scanf("%d", &t); if (t == 0) { int u; scanf("%d", &u); color[u] = 1 - color[u]; int s = hld.getStartTime(u); seg.update(s, s, color[u]); } else if (t == 1) { int u; scanf("%d", &u); int res = queryUp(u, 1, color, tree, hld, seg); if (res == INT_INF) res = -1; printf("%d\n", res); } } return 0; }
25.497967
154
0.554404
[ "vector" ]
d47ad955b8edfb22226e27a00da37d5c2854ef6d
3,310
cpp
C++
src/invocation.cpp
brainshave/v8cl
014a939568db9983d9f10b20f63f6e815fe6dd58
[ "MIT" ]
1
2015-10-07T12:56:48.000Z
2015-10-07T12:56:48.000Z
src/invocation.cpp
brainshave/v8cl
014a939568db9983d9f10b20f63f6e815fe6dd58
[ "MIT" ]
null
null
null
src/invocation.cpp
brainshave/v8cl
014a939568db9983d9f10b20f63f6e815fe6dd58
[ "MIT" ]
null
null
null
#include "v8cl.h" #define V8CL_ERROR_WRAPPER_MISSING "Wrapper missing." #define V8CL_ERROR_FUNCTION_NOT_IMPLEMENTED "Function not implemented." #define V8CL_ERROR_NEED_MORE_ARGUMENTS "Need more arguments, in total:" #define V8CL_ERROR_UNKNOWN_OPENCL_ERROR "Unknown WebCL error code:" #define V8CL_INVOCATION_ARGS (Wrapper*& wrapper, \ const Arguments& args, \ vector<void*>& natives, \ vector<void*>& result, \ Handle<Value>& jsResult, \ int32_t& errorNumber) namespace v8cl { map<int, const char*> errorCodes = GetErrorCodes(); void DeleteAllItems(vector<void*>& data) { for(vector<void*>::iterator it = data.begin(), end = data.end(); it < end; ++it) { if (*it) free(*it); } } const char* CheckWrapper V8CL_INVOCATION_ARGS { if (!wrapper) { return V8CL_ERROR_WRAPPER_MISSING; } if (!wrapper->f || !wrapper->action) { return V8CL_ERROR_FUNCTION_NOT_IMPLEMENTED; } return NULL; } const char* ConvertArguments V8CL_INVOCATION_ARGS { int length = args.Length(); if (length < wrapper->minArgc) { errorNumber = wrapper->minArgc; return V8CL_ERROR_NEED_MORE_ARGUMENTS; } // Invoke converters for given arguments Converter *converter = wrapper->converters; for (int i = 0; *converter && (i < length) && (i < V8CL_MAX_CONVERTERS); ++i, ++converter) { (*converter)(wrapper, args[i], natives); } return NULL; } const char* InvokeAction V8CL_INVOCATION_ARGS { int32_t error = wrapper->action(wrapper, natives, result); if (error) { // Show name of error instead of number if it's of known name if (errorCodes.count(error)) { return errorCodes[error]; } else { errorNumber = error; return V8CL_ERROR_UNKNOWN_OPENCL_ERROR; } } return NULL; } const char* ConvertResult V8CL_INVOCATION_ARGS { if (wrapper->returner) { jsResult = wrapper->returner(wrapper, natives, result); } return NULL; } typedef const char* (*InvocationStep) V8CL_INVOCATION_ARGS; InvocationStep invocationSteps[] = { CheckWrapper, ConvertArguments, InvokeAction, ConvertResult, NULL }; Handle<Value> InvokeWrapper (const Arguments& args) { HandleScope scope; Handle<Value> jsResult = Undefined(); vector<void*> natives; vector<void*> result; const char* error; int32_t errorNumber = 0; Wrapper *wrapper = (Wrapper*) External::Unwrap(args.Data()); for (InvocationStep *step = invocationSteps; *step; ++step) { error = (*step)(wrapper, args, natives, result, jsResult, errorNumber); if (error) { Handle<String> message = String::New(error); if (errorNumber) { message = String::Concat( message, String::Concat(String::New(" "), Integer::New(errorNumber)->ToString())); } jsResult = ThrowException(Exception::Error(message)); break; } } DeleteAllItems(natives); DeleteAllItems(result); return scope.Close(jsResult); } }
28.534483
77
0.604834
[ "vector" ]
d47ba9794d29a0e776ed2d4095ebbb3ebe1c7510
9,659
cpp
C++
XCPLib/XCPMaster.cpp
zhuhaijun753/XCP
f510dc96fbfad07170733eb96780c6af51882e37
[ "Unlicense" ]
62
2017-11-22T14:02:27.000Z
2022-03-17T07:52:41.000Z
XCPLib/XCPMaster.cpp
SushMJ/XCP_OverCAN
299f3d9c7672b5111a2c23ffff2e650395618a4d
[ "Unlicense" ]
5
2018-02-23T12:36:22.000Z
2022-01-24T04:02:45.000Z
XCPLib/XCPMaster.cpp
SushMJ/XCP_OverCAN
299f3d9c7672b5111a2c23ffff2e650395618a4d
[ "Unlicense" ]
17
2018-02-22T17:24:19.000Z
2022-03-17T07:52:34.000Z
#include "XCPMaster.h" #include "TCPMessageFactory.h" #include "CANMessageFactory.h" #include "IncomingMessageHandler.h" //#include <vld.h> const XCPMaster::SlaveProperties& XCPMaster::GetSlaveProperties() const { return m_SlaveProperties; } void XCPMaster::SetSlaveProperties(const SlaveProperties& properties) { m_SlaveProperties = properties; } XCPMaster::XCPMaster(TransportLayer transportlayer) { switch (transportlayer) { case TransportLayer::ETHERNET: m_MessageFactory = new TCPMessageFactory(); break; case TransportLayer::CAN: m_MessageFactory = new CANMessageFactory(); break; default: m_MessageFactory = nullptr; break; } m_PacketFactory = new PacketFactory(*this); m_MessageHandler = new IncomingMessageHandler(*this); m_ExternalHandler = nullptr; } XCPMaster::~XCPMaster() { delete m_MessageFactory; delete m_PacketFactory; delete m_MessageHandler; } std::unique_ptr<IXCPMessage> XCPMaster::CreateConnectMessage(ConnectPacket::ConnectMode mode) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateConnectPacket(mode))); } std::unique_ptr<IXCPMessage> XCPMaster::CreateDisconnectMessage() { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateDisconnectPacket())); } std::unique_ptr<IXCPMessage> XCPMaster::CreateGetStatusMessage() { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateGetStatusPacket())); } std::unique_ptr<IXCPMessage> XCPMaster::CreateSynchMessage() { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateSynchPacket())); } std::unique_ptr<IXCPMessage> XCPMaster::CreateSetMTAMessage(uint32_t address, uint8_t extension) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateSetMTAPacket(address, extension, m_SlaveProperties.ByteOrder == 0))); } std::unique_ptr<IXCPMessage> XCPMaster::DeserializeMessage(std::vector<uint8_t>& data) { CommandPacket* LastCommand = nullptr; if (m_SentCommandQueue.size() > 0) { LastCommand = m_SentCommandQueue.front(); } IXCPPacket* Packet = m_PacketFactory->DeserializeIncomingFromSlave(data, m_MessageFactory->GetHeaderSize(), m_MessageFactory->GetTailSize(), LastCommand); if (Packet) { std::vector<uint8_t>(data.begin() + m_MessageFactory->GetHeaderSize() + Packet->GetPacketSize() + m_MessageFactory->GetTailSize(), data.end()).swap(data); //Clear packet data from the buffer. Leaves the not-yet-deserialized data intact. IXCPMessage* MessageFrame = m_MessageFactory->CreateMessage(Packet); //Pass decoded packets to the internal and external handlers. if (m_MessageHandler) { Packet->Dispatch(*m_MessageHandler); } if (m_ExternalHandler) { Packet->Dispatch(*m_ExternalHandler); } std::cout << "---------------------------------------------\n"; if (m_SentCommandQueue.size() > 0 && Packet->GetPid() > 0xFB) //do not pop if this was a DAQ packet { m_SentCommandQueue.pop(); } return std::unique_ptr<IXCPMessage>(MessageFrame); } std::cout << "couldnt deserialise the message\n"; std::cout << "---------------------------------------------\n"; if (m_SentCommandQueue.size() > 0) //TODO: delete this after all packet types are handled correctly... { m_SentCommandQueue.pop(); } data.clear(); return nullptr; } std::unique_ptr<IXCPMessage> XCPMaster::CreateUploadMessage(uint8_t NumberOfElements) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateUploadPacket(NumberOfElements))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateShortUploadMessage(uint8_t NumberOfElements, uint32_t Address, uint8_t AddressExtension) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateShortUploadPacket(NumberOfElements, Address, AddressExtension, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateFreeDaqMessage() { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateFreeDaqPacket())); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateAllocDaqMessage(uint16_t DaqCount) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateAllocDaqPacket(DaqCount, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateAllocOdtMessage(uint16_t DaqListNumber, uint8_t OdtCount) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateAllocOdtPacket(DaqListNumber, OdtCount, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateAllocOdtEntryMessage(uint16_t DaqListNumber, uint8_t OdtNumber, uint8_t OdtEntryCount) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateAllocOdtEntryPacket(DaqListNumber, OdtNumber, OdtEntryCount, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateSetDaqPtrMessage(uint16_t DaqListNumber, uint8_t OdtNumber, uint8_t OdtEntryNumber) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateSetDaqPtrPacket(DaqListNumber, OdtNumber, OdtEntryNumber, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateWriteDaqMessage(uint8_t BitOffset, uint8_t ElementSize, uint8_t AddressExtension, uint32_t Address) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateWriteDaqPacket(BitOffset, ElementSize, AddressExtension, Address, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateSetDaqListModeMessage(uint8_t Mode, uint16_t DaqListNumber, uint16_t EventChannel, uint8_t Prescaler, uint8_t Priority) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateSetDaqListModePacket(Mode, DaqListNumber, EventChannel, Prescaler, Priority, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateStartStopDaqListMessage(StartStopDaqListPacket::Mode Mode, uint16_t DaqListNumber) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateStartStopDaqListPacket(Mode, DaqListNumber, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateStartStopSynchMessage(StartStopSynchPacket::Mode Mode) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateStartStopSyncPacket(Mode))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateGetSeedMessage(GetSeedPacket::Mode Mode, GetSeedPacket::Resource Resource) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateGetSeedPacket(Mode, Resource))); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateGetDaqProcessorInfoMessage() { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateGetDaqProcessorInfoPacket())); } XCP_API std::unique_ptr<IXCPMessage> XCPMaster::CreateClearDaqListMessage(uint16_t DaqListNumber) { if (!m_MessageFactory) { return nullptr; } return std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(m_PacketFactory->CreateClearDaqListPacket(DaqListNumber, m_SlaveProperties.ByteOrder == 0))); } XCP_API std::vector<std::unique_ptr<IXCPMessage>> XCPMaster::CreateUnlockMessages() { std::vector<std::unique_ptr<IXCPMessage>> ret; const std::vector<IXCPPacket*>& packets = m_PacketFactory->CreateUnlockPackets(m_MessageHandler->GetUnlockKey()); for (const auto& a : packets) { ret.push_back(std::move(std::unique_ptr<IXCPMessage>(m_MessageFactory->CreateMessage(a)))); } return ret; } void XCPMaster::AddSentMessage(IXCPMessage * Packet) { if (CommandPacket* ToAdd = dynamic_cast<CommandPacket*>(Packet->GetPacket())) { m_SentCommandQueue.push(ToAdd); } else { std::cout << "XCPMaster::AddSentMessage: This is not a CMD packet."; } } XCP_API void XCPMaster::SetSeedAndKeyFunctionPointers(XCP_GetAvailablePrivilegesPtr_t GetAvailablePrivilegesPtr, XCP_ComputeKeyFromSeedPtr_t ComputeKeyPtr) { m_GetAvailablePrivileges = GetAvailablePrivilegesPtr; m_ComputeKeyFromSeed = ComputeKeyPtr; } XCP_API DAQLayout& XCPMaster::GetDaqLayout() { return m_DAQLayout; } XCP_API void XCPMaster::SetDaqLayout(DAQLayout layout) { m_DAQLayout = layout; } XCP_API void XCPMaster::SetExternalMessageHandler(IIncomingMessageHandler * Handler) { m_ExternalHandler = Handler; } XCP_ComputeKeyFromSeedPtr_t XCPMaster::GetComputeKeyPtr() { return m_ComputeKeyFromSeed; } XCP_GetAvailablePrivilegesPtr_t XCPMaster::GetAvailablePrivilegesPtr() { return m_GetAvailablePrivileges; }
29.811728
238
0.78124
[ "vector" ]
d47ec6653ace12be215cd6472445ad5c0472b161
14,802
cc
C++
src/terrain_render.cc
aeonstasis/opengl-ocean-world
196ac5d7170fc57cdfd3a8e25245bb48fe80384d
[ "MIT" ]
3
2019-12-13T09:01:28.000Z
2021-10-02T23:25:07.000Z
src/terrain_render.cc
aaron-zou/opengl-ocean-world
196ac5d7170fc57cdfd3a8e25245bb48fe80384d
[ "MIT" ]
null
null
null
src/terrain_render.cc
aaron-zou/opengl-ocean-world
196ac5d7170fc57cdfd3a8e25245bb48fe80384d
[ "MIT" ]
1
2021-10-02T23:25:10.000Z
2021-10-02T23:25:10.000Z
#include "terrain_render.h" #include "perlin.hpp" #include <GL/glew.h> #include <algorithm> #include <cmath> #include <glm/gtx/rotate_vector.hpp> #include <iostream> #include <random> const char *terrain_vertex_shader = #include "shaders/terrain.vert" ; const char *terrain_geometry_shader = #include "shaders/terrain.geom" ; const char *terrain_fragment_shader = #include "shaders/terrain.frag" ; const char *ocean_vertex_shader = #include "shaders/ocean.vert" ; const char *ocean_geometry_shader = #include "shaders/ocean.geom" ; const char *ocean_fragment_shader = #include "shaders/ocean.frag" ; const char *ocean_tcs_shader = #include "shaders/ocean.tcs" ; const char *ocean_tes_shader = #include "shaders/ocean.tes" ; using std::array; using std::vector; constexpr float BLOCK_SIZE = 1.0f; constexpr int UPDATE_STEP = 5; constexpr double kPi = 3.141592653589793; constexpr double kG = 9.8000001; // Defines a basic unit cube in 3-space const array<glm::vec4, 4> cube_vertices = { {{0.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 0.0f, BLOCK_SIZE, 1.0f}, {BLOCK_SIZE, 0.0f, 0.0f, 1.0f}, {BLOCK_SIZE, 0.0f, BLOCK_SIZE, 1.0f}}}; const array<glm::uvec3, 2> cube_faces = {{{2, 0, 1}, {1, 3, 2}}}; // Wave simulation parameters constexpr int kNumWaves = 10; float gMedianWave = 30.0f; /* wavelengths sampled based on this average wave */ float gMedianAmp = 0.10f; /* amplitudes sampled based on this average amp */ float gSteepness = 0.3f; /* tunable *sharpness* of wave in [0, 1] */ glm::vec3 gMedianDir = {0.5f, 0.1f, 0.5f}; /* sample directions relative */ float kAngleRange = kPi / 3; /* sample directions within range */ array<float, kNumWaves> gAmp{}; array<float, kNumWaves> gFreq{}; array<float, kNumWaves> gPhi{}; array<glm::vec3, kNumWaves> gDir{}; TerrainRender::TerrainRender(size_t rows, size_t cols, std::vector<ShaderUniform> uniforms) : ticks_(0), rows_(rows), cols_(cols), cached_x_(0), cached_z_(0), instanceOffsets_(rows * cols), sortedOffsets_(rows * cols), heightVec_(rows * cols), norm0_(rows * cols), norm1_(rows * cols), norm2_(rows * cols), norm3_(rows * cols) { // WAVES // Binders auto param_binder = [](int loc, const void *data) { glUniform1fv(loc, kNumWaves, (const GLfloat *)data); }; auto dir_binder = [](int loc, const void *data) { glUniform3fv(loc, kNumWaves, (const GLfloat *)data); }; auto int_binder = [](int loc, const void *data) { glUniform1iv(loc, 1, (const GLint *)data); }; auto float_binder = [](int loc, const void *data) { glUniform1fv(loc, 1, (const GLfloat *)data); }; // Data auto amp_data = []() -> const void * { return gAmp.data(); }; auto freq_data = []() -> const void * { return gFreq.data(); }; auto phi_data = []() -> const void * { return gPhi.data(); }; auto dir_data = []() -> const void * { return gDir.data(); }; auto steepness_data = []() -> const void * { return &gSteepness; }; auto num_waves_data = []() -> const void * { return &kNumWaves; }; // Uniforms uniforms.push_back({"amp", param_binder, amp_data}); uniforms.push_back({"freq", param_binder, freq_data}); uniforms.push_back({"phi", param_binder, phi_data}); uniforms.push_back({"dir", dir_binder, dir_data}); uniforms.push_back({"steepness", float_binder, steepness_data}); uniforms.push_back({"num_waves", int_binder, num_waves_data}); auto terrain_pass_input = RenderDataInput{}; terrain_pass_input.assign(0, "vertex_position", cube_vertices.data(), cube_vertices.size(), 4, GL_FLOAT); // Set up offsets for each instanced cube updateInstanceOffsets(0, 0); terrain_pass_input.assign(1, "offset", instanceOffsets_.data(), instanceOffsets_.size(), 3, GL_FLOAT, true); terrain_pass_input.assign(2, "heightVec", heightVec_.data(), heightVec_.size(), 4, GL_FLOAT, true); terrain_pass_input.assign(3, "norm0", norm0_.data(), norm0_.size(), 3, GL_FLOAT, true); terrain_pass_input.assign(4, "norm1", norm1_.data(), norm1_.size(), 3, GL_FLOAT, true); terrain_pass_input.assign(5, "norm2", norm2_.data(), norm2_.size(), 3, GL_FLOAT, true); terrain_pass_input.assign(6, "norm3", norm3_.data(), norm3_.size(), 3, GL_FLOAT, true); terrain_pass_input.assignIndex(cube_faces.data(), cube_faces.size(), 3); // Shader-related construct arguments for RenderPass auto terrain_shaders = vector<const char *>{{terrain_vertex_shader, terrain_geometry_shader, terrain_fragment_shader}}; auto output = vector<const char *>{{"fragment_color"}}; this->terrain_pass_ = std::make_unique<RenderPass>( -1, terrain_pass_input, terrain_shaders, uniforms, output); // WATER auto ocean_pass_input = RenderDataInput{}; ocean_pass_input.assign(0, "vertex_position", cube_vertices.data(), cube_vertices.size(), 4, GL_FLOAT); ocean_pass_input.assign(1, "offset", sortedOffsets_.data(), sortedOffsets_.size(), 3, GL_FLOAT, true); ocean_pass_input.assignIndex(cube_faces.data(), cube_faces.size(), 3); auto ocean_shaders = vector<const char *>{ {ocean_vertex_shader, ocean_geometry_shader, ocean_fragment_shader, ocean_tcs_shader, ocean_tes_shader}}; this->ocean_pass_ = std::make_unique<RenderPass>( -1, ocean_pass_input, ocean_shaders, uniforms, output); // Initialize wave parameters updateWaveParams(); } void TerrainRender::renderVisible(glm::vec3 eye) { int x_coord = std::floor(eye.x / BLOCK_SIZE); int z_coord = std::floor(eye.z / BLOCK_SIZE); // Update wave parameters every ~3sec ticks_++; if (ticks_ % 180 == 0) { // updateWaveParams(); } // Only update instanceOffsets_ if eye changes if (x_coord / UPDATE_STEP != cached_x_ / UPDATE_STEP || z_coord / UPDATE_STEP != cached_z_ / UPDATE_STEP) { updateInstanceOffsets(x_coord, z_coord); terrain_pass_->updateVBO(1, instanceOffsets_.data(), instanceOffsets_.size()); terrain_pass_->updateVBO(2, heightVec_.data(), heightVec_.size()); terrain_pass_->updateVBO(3, norm0_.data(), norm0_.size()); terrain_pass_->updateVBO(4, norm1_.data(), norm1_.size()); terrain_pass_->updateVBO(5, norm2_.data(), norm2_.size()); terrain_pass_->updateVBO(6, norm3_.data(), norm3_.size()); ocean_pass_->updateVBO(1, sortedOffsets_.data(), sortedOffsets_.size()); } // Draw each cube, instanced terrain_pass_->setup(); glDrawElementsInstanced(GL_TRIANGLES, cube_faces.size() * 3, GL_UNSIGNED_INT, 0, instanceOffsets_.size()); ocean_pass_->setup(); glDrawElementsInstanced(GL_PATCHES, cube_faces.size() * 3, GL_UNSIGNED_INT, 0, sortedOffsets_.size()); } /** * Vary the ocean parameters with time to achieve a dynamic wave simulation. * This also allows us to achieve "stormy" weather vs. "sunny" weather. */ void TerrainRender::updateWaveParams() { static std::mt19937 engine(std::random_device{}()); double now = getTime(); // TODO: Update median wave and amplitude // Resample wavelengths to generate new frequencies auto lengths = array<float, kNumWaves>{}; auto freq_dist = std::uniform_real_distribution<float>(gMedianWave / 2.0, gMedianWave * 2.0); std::generate(lengths.begin(), lengths.end(), [&freq_dist]() { return freq_dist(engine); }); std::transform(lengths.begin(), lengths.end(), gFreq.begin(), [](const auto &wavelength) { return std::sqrt(kG * 2 * kPi / wavelength); }); // Derive amplitudes based on wavelengths (constant ratio) auto amp_dist = std::uniform_real_distribution<float>(gMedianAmp / 2.0, gMedianAmp * 2.0); std::generate(gAmp.begin(), gAmp.end(), [&amp_dist]() { return amp_dist(engine); }); /* std::transform(lengths.begin(), lengths.end(), gAmp.begin(), [](const auto &wavelength) { return // return gMedianAmp / gMedianWave * wavelength; });*/ // Resample direction vectors auto dir_dist = std::uniform_real_distribution<float>(-kAngleRange / 2, kAngleRange / 2); std::generate(gDir.begin(), gDir.end(), [&dir_dist]() { return glm::rotateY(gMedianDir, dir_dist(engine)); }); // Update phase values auto phase_dist = std::uniform_real_distribution<float>(-kPi, kPi); std::generate(gPhi.begin(), gPhi.end(), [&phase_dist]() { return phase_dist(engine); }); } void TerrainRender::updateInstanceOffsets(int x, int z) { int index = 0; instanceOffsets_.resize(rows_ * cols_); for (size_t i = 0; i < rows_; i++) { for (size_t j = 0; j < cols_; j++) { float newX = ((float)i - (float)(rows_ / 2) + (float)x) * BLOCK_SIZE; float newZ = ((float)j - (float)(cols_ / 2) + (float)z) * BLOCK_SIZE; float perlin = perlin::getHeight(newX, newZ); instanceOffsets_[index++] = {newX, perlin, newZ}; } } index = 0; heightVec_.resize(rows_ * cols_); std::vector<glm::vec3> normals(rows_ * cols_); for (size_t i = 0; i < rows_; i++) { for (size_t j = 0; j < cols_; j++) { float botLeft = instanceOffsets_[index].y; glm::vec4 localHeights = glm::vec4{botLeft}; if (i < rows_ - 1) { // Up localHeights[1] = instanceOffsets_[index + cols_].y; } if (j < cols_ - 1) { // Right localHeights[2] = instanceOffsets_[index + 1].y; } if (i < rows_ - 1 && j < cols_ - 1) { // Diag localHeights[3] = instanceOffsets_[index + cols_ + 1].y; } normals[index] = -glm::normalize( glm::cross(glm::vec3{1.0f, localHeights[1] - botLeft, 0.0f}, glm::vec3{0.0f, localHeights[2] - botLeft, 1.0f})); heightVec_[index] = localHeights; index++; } } index = 0; for (size_t i = 0; i < rows_; i++) { for (size_t j = 0; j < cols_; j++) { norm0_[index] = normals[index]; norm1_[index] = (i < rows_ - 1) ? normals[index + cols_] : normals[index]; norm2_[index] = (j < cols_ - 1) ? normals[index + 1] : normals[index]; norm3_[index] = (i < rows_ - 1 && j < cols_ - 1) ? normals[index + cols_ + 1] : normals[index]; index++; } } sortedOffsets_ = instanceOffsets_; glm::vec2 center_pos = {x, z}; std::sort(sortedOffsets_.begin(), sortedOffsets_.end(), [&center_pos](const glm::vec3 &a, const glm::vec3 &b) { return glm::distance(center_pos, glm::vec2{a.x, a.z}) < glm::distance(center_pos, glm::vec2{b.x, b.z}); }); cached_x_ = x; cached_z_ = z; } bool TerrainRender::isPositionLegal(const glm::vec3 &loc) { // Check that player (if treated as a line) lies above terrain int i = int(int(floor(loc.x)) - cached_x_ + rows_ / 2); int j = int(int(floor(loc.z)) - cached_z_ + cols_ / 2); float currentBlockHeight = instanceOffsets_[i * cols_ + j].y; if (currentBlockHeight >= 0.0f && loc.y < currentBlockHeight) { return false; } // Check for collisions with left, right, front, back float x_center = std::floor(loc.x); float z_center = std::floor(loc.z); auto loc_left = glm::vec3{x_center - 1.0f, 0, z_center}; auto loc_right = glm::vec3{x_center + 1.0f, 0, z_center}; auto loc_front = glm::vec3{x_center, 0, z_center + 1.0f}; auto loc_back = glm::vec3{x_center, 0, z_center - 1.0f}; auto loc_left_front = glm::vec3{x_center - 1.0f, 0, z_center + 1.0f}; auto loc_right_front = glm::vec3{x_center + 1.0f, 0, z_center + 1.0f}; auto loc_left_back = glm::vec3{x_center - 1.0f, 0, z_center - 1.0f}; auto loc_right_back = glm::vec3{x_center + 1.0f, 0, z_center - 1.0f}; auto neighbors = vector<glm::vec3>{ loc_left, loc_right, loc_front, loc_back, loc_left_front, loc_right_front, loc_left_back, loc_right_back}; for (const auto &neighbor : neighbors) { // Check circle-rectangle intersection (xz-plane) auto closest = glm::vec2{glm::clamp(loc.x, neighbor.x, neighbor.x + 1.0f), glm::clamp(loc.z, neighbor.z, neighbor.z + 1.0f)}; float distance = glm::distance(closest, {loc.x, loc.z}); if (distance < 0.25f) { // Check heights (y) int i = int(floor(neighbor.x)) - cached_x_ + rows_ / 2; int j = int(floor(neighbor.z)) - cached_z_ + cols_ / 2; auto block_height = instanceOffsets_[i * cols_ + j].y; if (block_height >= 0.0f && loc.y < block_height) { return false; } } } return true; } float TerrainRender::getWaveHeight(const glm::vec3 &loc) { // Calculate wave height at a given location float waveHeight = 0.0f; // Naive sum of sines /*for (size_t i = 0; i < gAmp.size(); i++) { if (gAmp.at(i) == 0.0f) { break; } waveHeight += gAmp.at(i) * glm::sin(glm::dot(glm::vec2(gDir.at(i).x, gDir.at(i).z), glm::vec2(loc.x, loc.z)) * gFreq.at(i) + getTime() * gPhi.at(i)); }*/ glm::vec2 loc_xz = {loc.x, loc.z}; for (size_t i = 0; i < kNumWaves; i++) { glm::vec2 dir_xz = {gDir.at(i).x, gDir.at(i).z}; waveHeight += gAmp.at(i) * glm::sin(glm::dot(gFreq.at(i) * dir_xz, loc_xz) + gPhi.at(i) * getTime()); } return waveHeight + 0.1875f; } glm::vec3 TerrainRender::getWaveNormal(const glm::vec3 &loc) { glm::vec3 pos = loc; pos.y = getWaveHeight(loc); glm::vec3 norm = {0.0f, 1.0f, 0.0f}; for (size_t i = 0; i < kNumWaves; i++) { float q = gSteepness / (gFreq.at(i) * gAmp.at(i) * kNumWaves); float WA = gFreq.at(i) * gAmp.at(i); float S = glm::sin(glm::dot(gFreq.at(i) * gDir.at(i), pos) + gPhi.at(i) * getTime()); float C = glm::cos(glm::dot(gFreq.at(i) * gDir.at(i), pos) + gPhi.at(i) * getTime()); glm::vec3 temp{0.0f}; temp.x = -(gDir.at(i).x * WA * C); temp.z = -(gDir.at(i).z * WA * C); temp.y = -(q * WA * S); norm += temp; } return glm::normalize(norm); } void TerrainRender::toggle_storm(bool is_raining) { if (is_raining) { kAngleRange = kPi / 2; gMedianWave = 150.0f; gMedianAmp = 0.5f; gSteepness = 0.2f; updateWaveParams(); } else { kAngleRange = kPi / 3; gMedianWave = 30.0f; gMedianAmp = 0.10f; gSteepness = 0.3f; updateWaveParams(); } }
37.284635
80
0.611607
[ "vector", "transform" ]
d47f808abe108b9e32ef548e3fa0761d75e70c84
5,296
cpp
C++
dali/internal/render/common/render-item.cpp
vcebollada/dali-core
1f880695d4f6cb871db7f946538721e882ba1633
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali/internal/render/common/render-item.cpp
vcebollada/dali-core
1f880695d4f6cb871db7f946538721e882ba1633
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-03-22T10:19:17.000Z
2020-03-22T10:19:17.000Z
dali/internal/render/common/render-item.cpp
fayhot/dali-core
a69ea317f30961164520664a645ac36c387055ef
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/render/common/render-item.h> // INTERNAL INCLUDES #include <dali/internal/common/memory-pool-object-allocator.h> #include <dali/internal/render/renderers/render-renderer.h> #include <dali/internal/common/math.h> namespace { //Memory pool used to allocate new RenderItems. Memory used by this pool will be released when shutting down DALi Dali::Internal::MemoryPoolObjectAllocator<Dali::Internal::SceneGraph::RenderItem> gRenderItemPool; } namespace Dali { namespace Internal { namespace SceneGraph { RenderItem* RenderItem::New() { return new ( gRenderItemPool.AllocateRaw() ) RenderItem(); } RenderItem::RenderItem() : mModelMatrix( false ), mModelViewMatrix( false ), mSize(), mRenderer( NULL ), mNode( NULL ), mTextureSet( NULL ), mDepthIndex( 0 ), mIsOpaque( true ) { } RenderItem::~RenderItem() { } ClippingBox RenderItem::CalculateViewportSpaceAABB( const int viewportWidth, const int viewportHeight ) const { // Calculate extent vector of the AABB: const float halfActorX = mSize.x * 0.5f; const float halfActorY = mSize.y * 0.5f; // To transform the actor bounds to screen-space, We do a fast, 2D version of a matrix multiply optimized for 2D quads. // This reduces float multiplications from 64 (16 * 4) to 12 (4 * 3). // We create an array of 4 corners and directly initialize the first 3 with the matrix multiplication result of the respective corner. // This causes the construction of the vector arrays contents in-place for optimization. // We place the coords into the array in clockwise order, so we know opposite corners are always i + 2 from corner i. // We skip the 4th corner here as we can calculate that from the other 3, bypassing matrix multiplication. // Note: The below transform methods use a fast (2D) matrix multiply (only 4 multiplications are done). Vector2 corners[4]{ Transform2D( mModelViewMatrix, -halfActorX, -halfActorY ), Transform2D( mModelViewMatrix, halfActorX, -halfActorY ), Transform2D( mModelViewMatrix, halfActorX, halfActorY ) }; // As we are dealing with a rectangle, we can do a fast calculation to get the 4th corner from knowing the other 3 (even if rotated). corners[3] = Vector2( corners[0] + ( corners[2] - corners[1] ) ); // Calculate the AABB: // We use knowledge that opposite corners will be the max/min of each other. Doing this reduces the normal 12 branching comparisons to 3. // The standard equivalent min/max code of the below would be: // Vector2 AABBmax( std::max( corners[0].x, std::max( corners[1].x, std::max( corners[3].x, corners[2].x ) ) ), // std::max( corners[0].y, std::max( corners[1].y, std::max( corners[3].y, corners[2].y ) ) ) ); // Vector2 AABBmin( std::min( corners[0].x, std::min( corners[1].x, std::min( corners[3].x, corners[2].x ) ) ), // std::min( corners[0].y, std::min( corners[1].y, std::min( corners[3].y, corners[2].y ) ) ) ); unsigned int smallestX = 0u; // Loop 3 times to find the index of the smallest X value. // Note: We deliberately do NOT unroll the code here as this hampers the compilers output. for( unsigned int i = 1u; i < 4u; ++i ) { if( corners[i].x < corners[smallestX].x ) { smallestX = i; } } // As we are dealing with a rectangle, we can assume opposite corners are the largest. // So without doing min/max branching, we can fetch the min/max values of all the remaining X/Y coords from this one index. Vector4 aabb( corners[smallestX].x, corners[( smallestX + 3u ) % 4].y, corners[( smallestX + 2u ) % 4].x, corners[( smallestX + 1u ) % 4].y ); // Return the AABB in screen-space pixels (x, y, width, height). // Note: This is a algebraic simplification of: ( viewport.x - aabb.width ) / 2 - ( ( aabb.width / 2 ) + aabb.x ) per axis. Vector4 aabbInScreen( static_cast<float>( viewportWidth ) * 0.5f - aabb.z, static_cast<float>( viewportHeight ) * 0.5f - aabb.w, static_cast<float>( viewportWidth ) * 0.5f - aabb.x, static_cast<float>( viewportHeight ) * 0.5f - aabb.y ); int x = static_cast< int >( roundf( aabbInScreen.x ) ); int y = static_cast< int >( roundf( aabbInScreen.y ) ); int z = static_cast< int >( roundf( aabbInScreen.z ) ); int w = static_cast< int >( roundf( aabbInScreen.w ) ); return ClippingBox( x, y, z - x, w - y ); } void RenderItem::operator delete( void* ptr ) { gRenderItemPool.Free( static_cast<RenderItem*>( ptr ) ); } } // namespace SceneGraph } // namespace Internal } // namespace Dali
40.738462
144
0.679758
[ "render", "object", "vector", "transform" ]
d4800f2e58199dded92863eacba7b2de928169b3
10,573
cpp
C++
src/io/read_obj.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
71
2021-09-08T13:16:43.000Z
2022-03-27T10:23:33.000Z
src/io/read_obj.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
4
2021-09-08T00:16:20.000Z
2022-01-05T17:44:08.000Z
src/io/read_obj.cpp
ipc-sim/rigid-ipc
d839af457236e7363b14c2e482a01d8160fa447e
[ "MIT" ]
2
2021-09-18T15:15:38.000Z
2021-09-21T15:15:38.000Z
// Modified version of read_obj from libigl to include reading polyline elements // as edges. // // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "read_obj.hpp" #include <cstdio> #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <igl/edges.h> #include <igl/list_to_matrix.h> #include <logger.hpp> namespace ipc::rigid { std::string remove_newline(std::string s) { s.erase(std::remove(s.begin(), s.end(), '\n'), s.end()); return s; } bool read_obj( const std::string obj_file_name, std::vector<std::vector<double>>& V, std::vector<std::vector<double>>& TC, std::vector<std::vector<double>>& N, std::vector<std::vector<int>>& F, std::vector<std::vector<int>>& FTC, std::vector<std::vector<int>>& FN, std::vector<std::vector<int>>& L) { // Open file, and check for error FILE* obj_file = fopen(obj_file_name.c_str(), "r"); if (obj_file == NULL) { spdlog::error("read_obj: {:s} could not be opened!", obj_file_name); return false; } return read_obj(obj_file, V, TC, N, F, FTC, FN, L); } bool read_obj( FILE* obj_file, std::vector<std::vector<double>>& V, std::vector<std::vector<double>>& TC, std::vector<std::vector<double>>& N, std::vector<std::vector<int>>& F, std::vector<std::vector<int>>& FTC, std::vector<std::vector<int>>& FN, std::vector<std::vector<int>>& L) { // File open was successful so clear outputs V.clear(); TC.clear(); N.clear(); F.clear(); FTC.clear(); FN.clear(); L.clear(); // variables and constants to assist parsing the .obj file // Constant strings to compare against std::string v("v"); std::string vn("vn"); std::string vt("vt"); std::string f("f"); std::string l("l"); std::string tic_tac_toe("#"); const int LINE_MAX_LEN = 2048; char line[LINE_MAX_LEN]; int line_no = 1; while (fgets(line, LINE_MAX_LEN, obj_file) != NULL) { char type[LINE_MAX_LEN]; // Read first word containing type if (sscanf(line, "%s", type) == 1) { // Get pointer to rest of line right after type char* rest_of_line = &line[strlen(type)]; if (type == v) { std::istringstream ls(&line[1]); std::vector<double> vertex { std::istream_iterator<double>(ls), std::istream_iterator<double>() }; // if (vertex.size() < 3) { // spdlog::error( // "read_obj: vertex on line {:d} should have at " // "least 3 coordinates", // line_no); // fclose(obj_file); // return false; // } V.push_back(vertex); } else if (type == vn) { double x[3]; int count = sscanf(rest_of_line, "%lf %lf %lf\n", &x[0], &x[1], &x[2]); if (count != 3) { spdlog::error( "read_obj: normal on line {:d} should have 3 " "coordinates", line_no); fclose(obj_file); return false; } std::vector<double> normal(count); for (int i = 0; i < count; i++) { normal[i] = x[i]; } N.push_back(normal); } else if (type == vt) { double x[3]; int count = sscanf(rest_of_line, "%lf %lf %lf\n", &x[0], &x[1], &x[2]); if (count != 2 && count != 3) { spdlog::error( "read_obj: texture coords on line {:d} should have " "2 or 3 coordinates (has {:d})", line_no, count); fclose(obj_file); return false; } std::vector<double> tex(count); for (int i = 0; i < count; i++) { tex[i] = x[i]; } TC.push_back(tex); } else if (type == f) { const auto& shift = [&V](const int i) -> int { return i < 0 ? i + V.size() : i - 1; }; const auto& shift_t = [&TC](const int i) -> int { return i < 0 ? i + TC.size() : i - 1; }; const auto& shift_n = [&N](const int i) -> int { return i < 0 ? i + N.size() : i - 1; }; std::vector<int> f; std::vector<int> ftc; std::vector<int> fn; // Read each "word" after type char word[LINE_MAX_LEN]; int offset; while (sscanf(rest_of_line, "%s%n", word, &offset) == 1) { // adjust offset rest_of_line += offset; // Process word long int i, it, in; if (sscanf(word, "%ld/%ld/%ld", &i, &it, &in) == 3) { f.push_back(shift(i)); ftc.push_back(shift_t(it)); fn.push_back(shift_n(in)); } else if (sscanf(word, "%ld/%ld", &i, &it) == 2) { f.push_back(shift(i)); ftc.push_back(shift_t(it)); } else if (sscanf(word, "%ld//%ld", &i, &in) == 2) { f.push_back(shift(i)); fn.push_back(shift_n(in)); } else if (sscanf(word, "%ld", &i) == 1) { f.push_back(shift(i)); } else { spdlog::error( "read_obj: face on line {:d} has invalid " "element format", line_no); fclose(obj_file); return false; } } if ((f.size() > 0 && fn.size() == 0 && ftc.size() == 0) || (f.size() > 0 && fn.size() == f.size() && ftc.size() == 0) || (f.size() > 0 && fn.size() == 0 && ftc.size() == f.size()) || (f.size() > 0 && fn.size() == f.size() && ftc.size() == f.size())) { // No matter what add each type to lists so that lists // are the correct lengths F.push_back(f); FTC.push_back(ftc); FN.push_back(fn); } else { spdlog::error( "read_obj: face on line {:d} has invalid format", line_no); fclose(obj_file); return false; } } else if (type == l) { std::istringstream ls(&line[1]); std::vector<int> polyline { std::istream_iterator<int>(ls), std::istream_iterator<int>() }; if (polyline.size() < 2) { spdlog::error( "read_obj: line element on line {:d} should have " "at least 2 vertices", line_no); fclose(obj_file); return false; } for (int i = 0; i < polyline.size(); i++) { polyline[i] = polyline[i] < 0 ? polyline[i] + V.size() : polyline[i] - 1; } L.push_back(polyline); } else if ( strlen(type) >= 1 && (type[0] == '#' || type[0] == 'g' || type[0] == 's' || strcmp("usemtl", type) == 0 || strcmp("mtllib", type) == 0)) { // ignore comments or other stuff } else { // ignore any other lines std::string line_no_newline = remove_newline(line); spdlog::warn( "read_obj: ignored non-comment line {:d}: {:s}", line_no, line_no_newline); } } else { // ignore empty line } line_no++; } fclose(obj_file); assert(F.size() == FN.size()); assert(F.size() == FTC.size()); return true; } bool read_obj( const std::string obj_file_name, std::vector<std::vector<double>>& V, std::vector<std::vector<int>>& F, std::vector<std::vector<int>>& L) { std::vector<std::vector<double>> TC, N; std::vector<std::vector<int>> FTC, FN; return read_obj(obj_file_name, V, TC, N, F, FTC, FN, L); } bool read_obj( const std::string str, Eigen::MatrixXd& V, Eigen::MatrixXi& E, Eigen::MatrixXi& F) { std::vector<std::vector<double>> vV, vTC, vN; std::vector<std::vector<int>> vF, vFTC, vFN, vL; bool success = read_obj(str, vV, vTC, vN, vF, vFTC, vFN, vL); if (!success) { // read_obj(str,vV,vTC,vN,vF,vFTC,vFN) should have already printed // an error message return false; } bool V_rect = igl::list_to_matrix(vV, V); if (!V_rect) { // igl::list_to_matrix(vV,V) already printed error message return false; } bool F_rect = igl::list_to_matrix(vF, F); if (!F_rect) { // igl::list_to_matrix(vF,F) already printed error message return false; } std::vector<std::vector<int>> vE; for (const std::vector<int>& polyline : vL) { for (int i = 1; i < polyline.size(); i++) { vE.push_back({ { polyline[i - 1], polyline[i] } }); } } bool E_rect = igl::list_to_matrix(vE, E); if (!E_rect) { spdlog::error("read_obj: edges not rectangular matrix!"); return false; } if (F.size()) { Eigen::MatrixXi faceE; igl::edges(F, faceE); E.conservativeResize(E.rows() + faceE.rows(), 2); E.bottomRows(faceE.rows()) = faceE; } return true; } } // namespace ipc::rigid
35.009934
80
0.445663
[ "vector" ]
d481ef831c529fc1906fa4d4ab37f7347b300884
4,778
cpp
C++
LeetCode/C++/22. Generate Parentheses.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/22. Generate Parentheses.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/22. Generate Parentheses.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
//backtrack //Runtime: 4 ms, faster than 89.87% of C++ online submissions for Generate Parentheses. //Memory Usage: 7 MB, less than 100.00% of C++ online submissions for Generate Parentheses. class Solution { public: vector<char> pars = {'(', ')'}; void backtrack(int& n, string& comb, vector<string>& combs){ int open = count(comb.begin(), comb.end(), '('); int close = comb.size() - open; //short for open == n && close == n if(close == n){ combs.push_back(comb); } for(int i = 0; i < pars.size(); i++){ //only when open par's count < n, we can append open par //only when close par's count < open par's count, we can append close par if((i == 0 && open < n) || (i == 1 && open > close)){ comb += pars[i]; backtrack(n, comb, combs); comb.pop_back(); } } }; vector<string> generateParenthesis(int n) { string comb; vector<string> combs; backtrack(n, comb, combs); return combs; } }; //Approach 1: Brute Force, recursion //Runtime: 20 ms, faster than 11.14% of C++ online submissions for Generate Parentheses. //Memory Usage: 6.9 MB, less than 100.00% of C++ online submissions for Generate Parentheses. //time: O(2^(2n)*n), space: O(2^(2n)*n) class Solution { public: bool valid(string& comb){ int balance = 0; for(char c : comb){ if(c == '(') balance++; else balance--; if(balance < 0) return false; } return (balance == 0); } void generateAll(string& comb, vector<string>& combs, int n){ if(comb.size() == 2*n){ // cout << comb << endl; if(valid(comb))combs.push_back(comb); return; } for(char c : {'(', ')'}){ comb.push_back(c); generateAll(comb, combs, n); comb.pop_back(); } } vector<string> generateParenthesis(int n) { string comb; vector<string> combs; generateAll(comb, combs, n); return combs; } }; //Approach 1: Brute Force, recursion //Runtime: 16 ms, faster than 15.92% of C++ online submissions for Generate Parentheses. //Memory Usage: 12.4 MB, less than 92.56% of C++ online submissions for Generate Parentheses. /* time: O(2^(2n)*n), space: O(2^(2n)*n) we may choose either ( or ) for a comb of size 2*n, so there are total 2^(2n) possibilities. And for each possibility, we need to spend O(n) time to check for its validity. */ class Solution { public: vector<string> generateParenthesis(int n) { if(n == 0) return {""}; vector<string> ans; for(int c = 0; c < n; c++){ vector<string> lefts = generateParenthesis(c); vector<string> rights = generateParenthesis(n-1-c); for(string& left : lefts){ for(string& right : rights){ ans.push_back("(" + left + ")" + right); } } } return ans; } }; //backtrack //Runtime: 4 ms, faster than 89.84% of C++ online submissions for Generate Parentheses. //Memory Usage: 11.6 MB, less than 92.56% of C++ online submissions for Generate Parentheses. //time: O(4^n/sqrt(n)), space: O(4^n/sqrt(n)) class Solution { public: void backtrack(string& comb, vector<string>& combs, int open, int close, int n){ if(comb.size() == n*2){ combs.push_back(comb); return; } if(open < n){ comb += '('; backtrack(comb, combs, open+1, close, n); comb.pop_back(); } if(close < open){ comb += ')'; backtrack(comb, combs, open, close+1, n); comb.pop_back(); } } vector<string> generateParenthesis(int n) { string comb = ""; vector<string> combs; backtrack(comb, combs, 0, 0, n); return combs; } }; //Approach 3: Closure Number //Runtime: 20 ms, faster than 11.14% of C++ online submissions for Generate Parentheses. //Memory Usage: 13.3 MB, less than 90.08% of C++ online submissions for Generate Parentheses. //time: O(4^n/sqrt(n)) class Solution { public: vector<string> generateParenthesis(int n) { if(n == 0) return {""}; vector<string> ans; for(int c = 0; c < n; c++){ for(string left : generateParenthesis(c)){ for(string right : generateParenthesis(n-1-c)){ ans.push_back("(" + left + ")" + right); } } } return ans; } };
30.433121
93
0.528464
[ "vector" ]
d48c8597f1f399ee1155246935258ea386177f11
715
cpp
C++
leetcode/0009_palindrome_number.cpp
jacquerie/leetcode
a05e6b832eb0e0740aaff7b2eb3109038ad404bf
[ "MIT" ]
3
2018-05-10T09:56:49.000Z
2020-11-07T18:09:42.000Z
leetcode/0009_palindrome_number.cpp
jacquerie/leetcode
a05e6b832eb0e0740aaff7b2eb3109038ad404bf
[ "MIT" ]
null
null
null
leetcode/0009_palindrome_number.cpp
jacquerie/leetcode
a05e6b832eb0e0740aaff7b2eb3109038ad404bf
[ "MIT" ]
null
null
null
// Copyright (c) 2018 Jacopo Notarstefano #include <cassert> #include <vector> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } vector<int> digits; while (x) { digits.push_back(x % 10); x /= 10; } int n = digits.size(); for (int i = 0; i < n / 2; i++) { if (digits[i] != digits[n - i - 1]) { return false; } } return true; } }; int main() { auto solution = Solution(); assert(solution.isPalindrome(121)); assert(!solution.isPalindrome(-121)); assert(!solution.isPalindrome(10)); }
18.333333
49
0.48951
[ "vector" ]
d494e3bbe416ec8dd37667e44bc31b2e37d21c12
5,912
cpp
C++
src/sobolev/constraints/barycenter_components.cpp
Conrekatsu/repulsive-surfaces
74d6a16e6ca55c8296fa5a49757c2318bea62a84
[ "MIT" ]
35
2021-12-13T09:58:08.000Z
2022-03-30T11:03:01.000Z
src/sobolev/constraints/barycenter_components.cpp
Conrekatsu/repulsive-surfaces
74d6a16e6ca55c8296fa5a49757c2318bea62a84
[ "MIT" ]
null
null
null
src/sobolev/constraints/barycenter_components.cpp
Conrekatsu/repulsive-surfaces
74d6a16e6ca55c8296fa5a49757c2318bea62a84
[ "MIT" ]
3
2022-02-25T06:46:34.000Z
2022-03-16T05:46:53.000Z
#include "sobolev/constraints/barycenter_components.h" #include "helpers.h" #include <deque> namespace rsurfaces { namespace Constraints { void fillComponents(const MeshPtr mesh, const GeomPtr geom, std::vector<std::vector<GCVertex>> &components) { surface::VertexData<bool> grouped(*mesh, false); VertexIndices componentIndices(*mesh); std::deque<GCVertex> frontier; size_t componentID = 0; // Run Dijkstra's from each successive ungrouped point for (GCVertex vert : mesh->vertices()) { if (grouped[vert]) { continue; } std::cout << "Found a new connected component (assigned label " << componentID << ")" << std::endl; // Create data for a new connected component components.push_back(std::vector<GCVertex>()); frontier.clear(); frontier.push_back(vert); // Process next and enqueue neighbors while (!frontier.empty()) { GCVertex next = frontier.front(); frontier.pop_front(); if (grouped[next]) { continue; } // Mark this as having been assigned to a connected component grouped[next] = true; components[componentID].push_back(next); for (GCVertex neighbor : next.adjacentVertices()) { if (!grouped[neighbor]) { frontier.push_back(neighbor); } } } componentID++; } } void addSingleComponentTriplets(std::vector<Triplet> &triplets, const MeshPtr &mesh, const GeomPtr &geom, std::vector<GCVertex> &comp, int baseRow) { // Just want to place normalized dual weights in the entry for each vertex geom->requireVertexDualAreas(); VertexIndices indices = mesh->getVertexIndices(); double sumArea = 0; for (GCVertex v : comp) { sumArea += geom->vertexDualAreas[v]; } for (GCVertex v : comp) { double wt = geom->vertexDualAreas[v] / sumArea; triplets.push_back(Triplet(baseRow, indices[v], wt)); } } BarycenterComponentsConstraint::BarycenterComponentsConstraint(const MeshPtr &mesh, const GeomPtr &geom) { fillComponents(mesh, geom, components); ResetFunction(mesh, geom); } void BarycenterComponentsConstraint::ResetFunction(const MeshPtr &mesh, const GeomPtr &geom) { componentValues.clear(); for (std::vector<GCVertex> &comp : components) { Vector3 center = barycenterOfPoints(geom, mesh, comp); componentValues.push_back(center); } } void BarycenterComponentsConstraint::addTriplets(std::vector<Triplet> &triplets, const MeshPtr &mesh, const GeomPtr &geom, int baseRow) { // Take the same weights from the non-3X version of this constraint, // and duplicate them 3 times on each 3x3 diagonal block. std::vector<Triplet> singleTriplets; for (size_t i = 0; i < components.size(); i++) { addSingleComponentTriplets(singleTriplets, mesh, geom, components[i], i); } for (Triplet t : singleTriplets) { triplets.push_back(Triplet(baseRow + 3 * t.row(), 3 * t.col(), t.value())); triplets.push_back(Triplet(baseRow + 3 * t.row() + 1, 3 * t.col() + 1, t.value())); triplets.push_back(Triplet(baseRow + 3 * t.row() + 2, 3 * t.col() + 2, t.value())); } } void BarycenterComponentsConstraint::addEntries(Eigen::MatrixXd &M, const MeshPtr &mesh, const GeomPtr &geom, int baseRow) { std::vector<Triplet> singleTriplets; for (size_t i = 0; i < components.size(); i++) { addSingleComponentTriplets(singleTriplets, mesh, geom, components[i], i); } for (Triplet t : singleTriplets) { M(baseRow + 3 * t.row(), 3 * t.col()) = t.value(); M(baseRow + 3 * t.row() + 1, 3 * t.col() + 1) = t.value(); M(baseRow + 3 * t.row() + 2, 3 * t.col() + 2) = t.value(); } } void BarycenterComponentsConstraint::addErrorValues(Eigen::VectorXd &V, const MeshPtr &mesh, const GeomPtr &geom, int baseRow) { std::vector<Triplet> singleTriplets; for (size_t i = 0; i < components.size(); i++) { Vector3 current = barycenterOfPoints(geom, mesh, components[i]); V(baseRow + 3 * i) = current.x - componentValues[i].x; V(baseRow + 3 * i + 1) = current.y - componentValues[i].y; V(baseRow + 3 * i + 2) = current.z - componentValues[i].z; } } size_t BarycenterComponentsConstraint::nRows() { return 3 * components.size(); } void BarycenterComponentsConstraint::ProjectConstraint(MeshPtr &mesh, GeomPtr &geom) { for (size_t i = 0; i < components.size(); i++) { Vector3 center = barycenterOfPoints(geom, mesh, components[i]); translatePoints(geom, mesh, componentValues[i] - center, components[i]); } } } // namespace Constraints } // namespace rsurfaces
36.720497
155
0.516407
[ "mesh", "vector" ]
d4956338a5ccabc58b3b06f81ddd44993cf559ad
366
cc
C++
cpp/hackranker/h20.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h20.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
cpp/hackranker/h20.cc
staugust/leetcode
0ddd0b0941e596d3c6a21b6717d0dd193025f580
[ "Apache-2.0" ]
null
null
null
/* * */ #include <iostream> #include <vector> #include <string> #include <algorithm> #include <iomanip> #include <cstdlib> #include <cstdio> #include <map> #include <set> #include <deque> #include <queue> // Complete the strangeCounter function below. long strangeCounter(long t) { int it = 3; while (t > it) { t = t - it; it *= 2; } return it + 1 - t; }
15.25
47
0.639344
[ "vector" ]
d4a11176f3e41630e937b82b3c1c539fa324bd85
9,183
hpp
C++
quantumvk/vulkan/graphics/render_pass.hpp
timith/QuantumVk
1d6dcfd8a12336763ec815b19b6514db8b2ea9e8
[ "MIT" ]
null
null
null
quantumvk/vulkan/graphics/render_pass.hpp
timith/QuantumVk
1d6dcfd8a12336763ec815b19b6514db8b2ea9e8
[ "MIT" ]
null
null
null
quantumvk/vulkan/graphics/render_pass.hpp
timith/QuantumVk
1d6dcfd8a12336763ec815b19b6514db8b2ea9e8
[ "MIT" ]
null
null
null
#pragma once #include "quantumvk/utils/hash.hpp" #include "quantumvk/utils/intrusive.hpp" #include "quantumvk/utils/object_pool.hpp" #include "quantumvk/utils/temporary_hashmap.hpp" #include "quantumvk/vulkan/images/image.hpp" #include "quantumvk/vulkan/misc/cookie.hpp" #include "quantumvk/vulkan/misc/limits.hpp" #include "quantumvk/vulkan/vulkan_headers.hpp" namespace Vulkan { enum RenderPassOp { RENDER_PASS_OP_CLEAR_DEPTH_STENCIL_BIT = 1 << 0, RENDER_PASS_OP_LOAD_DEPTH_STENCIL_BIT = 1 << 1, RENDER_PASS_OP_STORE_DEPTH_STENCIL_BIT = 1 << 2, RENDER_PASS_OP_ENABLE_TRANSIENT_STORE_BIT = 1 << 3, RENDER_PASS_OP_ENABLE_TRANSIENT_LOAD_BIT = 1 << 4 }; using RenderPassOpFlags = uint32_t; class ImageView; struct RenderPassInfo { struct ColorAttachment { // Pointer to ImageView of attachment ImageView* view = nullptr; // Layout that the attachment will be in at the start of the renderpass. VK_IMAGE_LAYOUT_UNDEFINED meanslayout doesn't matter, and the contents of the image can be destructively transitioned away from. // This is ignored if the view is a swapchain image. Initial_layout must not be UNDEFINED if this attachment is set to be loaded at the start of the pass. VkImageLayout initial_layout; // Layout that the attachment will be transitioned to at end of renderpass. VK_IMAGE_LAYOUT_UNDEFINED means it will use the layout from the last subpass. // This is ignored if the view is a swapchain image VkImageLayout final_layout; // Color the attachment will be cleared to at start of renderpass if this attachment's index bit is set in uint32_t clear_attachment. VkClearColorValue clear_color; }; struct DepthStencilAttachment { // Pointer to ImageView of attachment ImageView* view = nullptr; // Layout that the attachment will be in at the start of the renderpass. VK_IMAGE_LAYOUT_UNDEFINED means it doesn't matter, and the contents of the image can be destructively transitioned away from. // Initial_layout must not be UNDEFINED if this attachment is set to be loaded at the start of the pass. VkImageLayout initial_layout; // Layout that the attachment will be transitioned to at end of renderpass. VK_IMAGE_LAYOUT_UNDEFINED means it will use the layout from the last subpass. VkImageLayout final_layout; // DepthStencilClearValue the attachment will be cleared to at start of renderpass if the RENDER_PASS_OP_CLEAR_DEPTH_STENCIL_BIT bit is set in op_flags VkClearDepthStencilValue clear_value = { 1.0f, 0 }; }; uint32_t num_color_attachments = 0; ColorAttachment color_attachments[VULKAN_NUM_ATTACHMENTS]; uint32_t clear_attachments = 0; uint32_t load_attachments = 0; uint32_t store_attachments = 0; DepthStencilAttachment depth_stencil; RenderPassOpFlags op_flags = 0; uint32_t multiview_mask = 0; // Render area will be clipped to the actual framebuffer. VkRect2D render_area = { { 0, 0 }, { UINT32_MAX, UINT32_MAX } }; enum class DepthStencil { None, ReadOnly, ReadWrite }; struct Subpass { uint32_t num_color_attachments = 0; uint32_t color_attachments[VULKAN_NUM_ATTACHMENTS]; uint32_t num_input_attachments = 0; uint32_t input_attachments[VULKAN_NUM_ATTACHMENTS]; uint32_t num_resolve_attachments = 0; uint32_t resolve_attachments[VULKAN_NUM_ATTACHMENTS]; DepthStencil depth_stencil_mode = DepthStencil::ReadWrite; }; // If 0/nullptr, assume a default subpass. uint32_t num_subpasses = 0; const Subpass* subpasses = nullptr; }; class RenderPass : public HashedObject<RenderPass>, public NoCopyNoMove { public: struct SubpassInfo { VkAttachmentReference color_attachments[VULKAN_NUM_ATTACHMENTS]; unsigned num_color_attachments; VkAttachmentReference input_attachments[VULKAN_NUM_ATTACHMENTS]; unsigned num_input_attachments; VkAttachmentReference depth_stencil_attachment; unsigned samples; }; RenderPass(Util::Hash hash, Device* device, const RenderPassInfo& info); RenderPass(Util::Hash hash, Device* device, const VkRenderPassCreateInfo& create_info); ~RenderPass(); unsigned GetNumSubpasses() const { return unsigned(subpasses_info.size()); } VkRenderPass GetRenderPass() const { return render_pass; } uint32_t GetSampleCount(unsigned subpass) const { VK_ASSERT(subpass < subpasses_info.size()); return subpasses_info[subpass].samples; } unsigned GetNumColorAttachments(unsigned subpass) const { VK_ASSERT(subpass < subpasses_info.size()); return subpasses_info[subpass].num_color_attachments; } unsigned GetNumInputAttachments(unsigned subpass) const { VK_ASSERT(subpass < subpasses_info.size()); return subpasses_info[subpass].num_input_attachments; } const VkAttachmentReference& GetColorAttachment(unsigned subpass, unsigned index) const { VK_ASSERT(subpass < subpasses_info.size()); VK_ASSERT(index < subpasses_info[subpass].num_color_attachments); return subpasses_info[subpass].color_attachments[index]; } const VkAttachmentReference& GetInputAttachment(unsigned subpass, unsigned index) const { VK_ASSERT(subpass < subpasses_info.size()); VK_ASSERT(index < subpasses_info[subpass].num_input_attachments); return subpasses_info[subpass].input_attachments[index]; } bool HasDepth(unsigned subpass) const { VK_ASSERT(subpass < subpasses_info.size()); return subpasses_info[subpass].depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED && FormatHasDepthAspect(depth_stencil); } bool HasStencil(unsigned subpass) const { VK_ASSERT(subpass < subpasses_info.size()); return subpasses_info[subpass].depth_stencil_attachment.attachment != VK_ATTACHMENT_UNUSED && FormatHasStencilAspect(depth_stencil); } private: Device* device; VkRenderPass render_pass = VK_NULL_HANDLE; VkFormat color_attachments[VULKAN_NUM_ATTACHMENTS] = {}; VkFormat depth_stencil = VK_FORMAT_UNDEFINED; std::vector<SubpassInfo> subpasses_info; void SetupSubpasses(const VkRenderPassCreateInfo& create_info); void FixupRenderPassWorkaround(VkRenderPassCreateInfo& create_info, VkAttachmentDescription* attachments); void FixupWsiBarrier(VkRenderPassCreateInfo& create_info, VkAttachmentDescription* attachments); }; class Framebuffer : public Cookie, public NoCopyNoMove, public InternalSyncEnabled { public: Framebuffer(Device* device, const RenderPass& rp, const RenderPassInfo& info); ~Framebuffer(); VkFramebuffer GetFramebuffer() const { return framebuffer; } static unsigned SetupRawViews(VkImageView* views, const RenderPassInfo& info); static void ComputeDimensions(const RenderPassInfo& info, uint32_t& width, uint32_t& height); static void ComputeAttachmentDimensions(const RenderPassInfo& info, unsigned index, uint32_t& width, uint32_t& height); uint32_t GetWidth() const { return width; } uint32_t GetHeight() const { return height; } const RenderPass& GetCompatibleRenderPass() const { return render_pass; } private: Device* device; VkFramebuffer framebuffer = VK_NULL_HANDLE; const RenderPass& render_pass; RenderPassInfo info; uint32_t width = 0; uint32_t height = 0; }; static const unsigned VULKAN_FRAMEBUFFER_RING_SIZE = 8; class FramebufferAllocator { public: explicit FramebufferAllocator(Device* device); Framebuffer& RequestFramebuffer(const RenderPassInfo& info); void BeginFrame(); void Clear(); private: struct FramebufferNode : Util::TemporaryHashmapEnabled<FramebufferNode>, Util::IntrusiveListEnabled<FramebufferNode>, Framebuffer { FramebufferNode(Device* device_, const RenderPass& rp, const RenderPassInfo& info_) : Framebuffer(device_, rp, info_) { SetInternalSyncObject(); } }; Device* device; Util::TemporaryHashmap<FramebufferNode, VULKAN_FRAMEBUFFER_RING_SIZE, false> framebuffers; #ifdef QM_VULKAN_MT std::mutex lock; #endif }; class AttachmentAllocator { public: AttachmentAllocator(Device* device_, bool transient_) : device(device_), transient(transient_) { } ImageView& RequestAttachment(uint32_t width, uint32_t height, VkFormat format, uint32_t index = 0, VkSampleCountFlagBits samples = VK_SAMPLE_COUNT_1_BIT, uint32_t layers = 1); void BeginFrame(); void Clear(); private: struct TransientNode : Util::TemporaryHashmapEnabled<TransientNode>, Util::IntrusiveListEnabled<TransientNode> { explicit TransientNode(ImageHandle image_, ImageViewHandle view_) : image(std::move(image_)), view(std::move(view_)) { } ImageHandle image; ImageViewHandle view; }; Device* device; Util::TemporaryHashmap<TransientNode, VULKAN_FRAMEBUFFER_RING_SIZE, false> attachments; #ifdef QM_VULKAN_MT std::mutex lock; #endif bool transient; }; class TransientAttachmentAllocator : public AttachmentAllocator { public: explicit TransientAttachmentAllocator(Device* device_) : AttachmentAllocator(device_, true) { } }; class PhysicalAttachmentAllocator : public AttachmentAllocator { public: explicit PhysicalAttachmentAllocator(Device* device_) : AttachmentAllocator(device_, false) { } }; }
30.009804
204
0.768594
[ "render", "vector" ]
d4a68fc928a94a3786a9d306d48a330c133345c3
3,171
cpp
C++
old/NeuralNetworkMT.cpp
mrnul/Neural-nets
c28c61ab6123298d3a0b1b0f6c0fe0ab9d7f3edf
[ "MIT" ]
2
2019-11-14T01:20:36.000Z
2020-06-18T17:13:27.000Z
old/NeuralNetworkMT.cpp
mrnul/Neural-nets
c28c61ab6123298d3a0b1b0f6c0fe0ab9d7f3edf
[ "MIT" ]
null
null
null
old/NeuralNetworkMT.cpp
mrnul/Neural-nets
c28c61ab6123298d3a0b1b0f6c0fe0ab9d7f3edf
[ "MIT" ]
1
2020-03-07T09:36:26.000Z
2020-03-07T09:36:26.000Z
#include <MyHeaders\NeuralNetworkMT.h> NeuralNetworkMT::NeuralNetworkMT() { //hmmm... } NeuralNetworkMT::NeuralNetworkMT(const vector<unsigned int> topology, const int threads) { Initialize(topology, threads); } void NeuralNetworkMT::Initialize(const vector<unsigned int> topology, const int threads) { Topology = topology; Master.Initialize(topology); BeginThreads(threads); } void NeuralNetworkMT::BeginThreads(const int threads) { auto workingThreads = [&](ThreadData & Data) { while (true) { if (!Data.wakeUp.Wait()) break; if (Data.mustQuit) break; Data.NN.SwapGradPrevGrad(); Data.NN.ZeroGrad(); //calculate the Gradient Data.NN.FeedAndBackProp(*Inputs, *Targets, Master.GetMatrices(), Master.GetIndexVector(), Data.Start, Data.End, Master.Params.DropOutRate); //add regularization terms + momentum NNAddL1L2(Master.Params.L1, Master.Params.L2, Master.GetMatrices(), Data.NN.GetGrad()); NNAddMomentum(Master.Params.Momentum, Data.NN.GetGrad(), Data.NN.GetPrevGrad()); //notify main thread Data.wakeUp.Reset(); Data.jobDone.Signal(); } }; Data.resize(threads); Threads.resize(threads); for (int i = 0; i < threads; i++) { //each thread will use master's weights Data[i].NN.InitializeNoWeights(Topology); Threads[i] = thread(workingThreads, std::ref(Data[i])); } } void NeuralNetworkMT::StopThreads() { const auto threads = Threads.size(); for (int i = 0; i < threads; i++) { Data[i].mustQuit = true; Data[i].wakeUp.Signal(); Threads[i].join(); } Data = vector<ThreadData>(); Threads = vector<thread>(); } void NeuralNetworkMT::Train(const vector<vector<float>> & inputs, const vector<vector<float>> & targets) { Inputs = &inputs; Targets = &targets; const int inputSize = (int)inputs.size(); //resize if needed if (Master.GetIndexVector().size() != inputSize) Master.ResizeIndexVector(inputSize); //shuffle index vector if needed if (Master.Params.BatchSize != inputSize) Master.ShuffleIndexVector(); const auto threadsCount = Threads.size(); const int howManyPerThread = (int)(Master.Params.BatchSize / threadsCount); int end = 0; while (end < inputSize) { const int start = end; end = std::min(end + Master.Params.BatchSize, inputSize); for (int t = 0; t < threadsCount; t++) { Data[t].Start = start + t * howManyPerThread; Data[t].End = std::min(Data[t].Start + howManyPerThread, inputSize); Data[t].wakeUp.Signal(); } Master.SwapGradPrevGrad(); Master.ZeroGrad(); vector<MatrixXf> & Grad = Master.GetGrad(); const auto L = Grad.size(); //wait for threads to finish and update the weights of Master for (int t = 0; t < threadsCount; t++) { Data[t].jobDone.Wait(); Data[t].jobDone.Reset(); //now Grad is the Gradient + regularization terms + momentum for (int i = 0; i < L; i++) Grad[i] += Data[t].NN.GetGrad()[i]; } Master.NormalizeGrad(); Master.UpdateWeights(Master.Params.LearningRate); } } NeuralNetworkMT::~NeuralNetworkMT() { StopThreads(); }
24.392308
143
0.65626
[ "vector" ]
d4a87765313f3a68d4028e1f23a9d09f606bf9c2
20,679
cc
C++
demo_drivers/heat_transfer_and_melting/two_d_unsteady_heat_melt/solid_contact.cc
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
null
null
null
demo_drivers/heat_transfer_and_melting/two_d_unsteady_heat_melt/solid_contact.cc
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
1
2022-03-23T16:16:41.000Z
2022-03-23T16:16:41.000Z
demo_drivers/heat_transfer_and_melting/two_d_unsteady_heat_melt/solid_contact.cc
PuneetMatharu/oomph-lib
edd590cbb4f3ef9940b9738f18275ea2fb828c55
[ "RSA-MD" ]
null
null
null
//LIC// ==================================================================== //LIC// This file forms part of oomph-lib, the object-oriented, //LIC// multi-physics finite-element library, available //LIC// at http://www.oomph-lib.org. //LIC// //LIC// Copyright (C) 2006-2022 Matthias Heil and Andrew Hazel //LIC// //LIC// This library is free software; you can redistribute it and/or //LIC// modify it under the terms of the GNU Lesser General Public //LIC// License as published by the Free Software Foundation; either //LIC// version 2.1 of the License, or (at your option) any later version. //LIC// //LIC// This library is distributed in the hope that it will be useful, //LIC// but WITHOUT ANY WARRANTY; without even the implied warranty of //LIC// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //LIC// Lesser General Public License for more details. //LIC// //LIC// You should have received a copy of the GNU Lesser General Public //LIC// License along with this library; if not, write to the Free Software //LIC// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA //LIC// 02110-1301 USA. //LIC// //LIC// The authors may be contacted at oomph-lib@maths.man.ac.uk. //LIC// //LIC//==================================================================== // Driver for 2D contact problem -- displacement controlled penetrator //=========================================================== // Jonathan to do: // - doc projection of contact pressure (and do by default) // - explore --resolve_after_adapt //=========================================================== #include <fenv.h> //Generic routines #include "generic.h" // The solid elements #include "solid.h" // Mesh #include "meshes/triangle_mesh.h" // Contact stuff #include "contact_elements.h" using namespace std; using namespace oomph; using namespace MathematicalConstants; /// //////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////// /// //////////////////////////////////////////////////////////////////// //======start_of_ProblemParameters===================== /// Namespace for problem parameters //===================================================== namespace ProblemParameters { /// Non-dim density for solid double Lambda_sq=0.0; /// Poisson's ratio for solid double Nu=0.3; /// Pointer to constitutive law ConstitutiveLaw* Constitutive_law_pt=0; /// Radius of penetrator double Radius=0.1; /// Initial/max y-position double Y_c_max=0.0; /// Position of centre of penetrator Vector<double> Centre; /// Penetrator Penetrator* Penetrator_pt=0; /// Initial/max element area double El_area=0.002; } // end of ProblemParameters /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //=====start_of_problem_class========================================= /// Problem class //==================================================================== template<class ELEMENT> class ContactProblem : public Problem { public: /// Constructor ContactProblem(); /// Destructor (empty) ~ContactProblem(){} /// Update the problem specs after solve (empty) void actions_after_newton_solve() {} /// Update the problem specs before solve (empty) void actions_before_newton_solve() {} /// Actions before next timestep void actions_before_implicit_timestep() { // Amplitude of oscillation double amplitude=0.1; // Update position of centre -- amplitude of oscillation increases // by 5% per period... double time=time_pt()->time(); ProblemParameters::Centre[1]=ProblemParameters::Y_c_max-amplitude* (1.0+0.05*time)*0.5*(1.0-cos(2.0*MathematicalConstants::Pi*time)); oomph_info << "Solving for y_c = " << ProblemParameters::Centre[1] << " for time: " << time << std::endl; } /// Actions before adapt: wipe contact elements void actions_before_adapt() { // Make backup of surface mesh Backed_up_surface_contact_mesh_pt= new BackupMeshForProjection<TElement<1,3> >( Surface_contact_mesh_pt,Contact_boundary_id); // // Output contact elements // ofstream some_file; // char filename[100]; // sprintf(filename,"contact_before.dat"); // some_file.open(filename); // unsigned nel=Surface_contact_mesh_pt->nelement(); // for (unsigned e=0;e<nel;e++) // { // dynamic_cast<NonlinearSurfaceContactElement<ELEMENT>* >( // Surface_contact_mesh_pt->element_pt(e))->output(some_file); // } // some_file.close(); // // Kill the elements and wipe surface mesh delete_contact_elements(); // Rebuild the Problem's global mesh from its various sub-meshes rebuild_global_mesh(); } /// Actions after adapt: /// Setup the problem again -- remember that the mesh has been /// completely rebuilt and its element's don't have any /// pointers to source fcts etc. yet void actions_after_adapt() { // Create contact elements create_contact_elements(); // Rebuild the Problem's global mesh from its various sub-meshes rebuild_global_mesh(); // Rebuild elements complete_problem_setup(); // Now project from backup of original contact mesh to new one oomph_info << "Projecting contact pressure.\n"; Backed_up_surface_contact_mesh_pt->project_onto_new_mesh( Surface_contact_mesh_pt); // Kill backed up mesh delete Backed_up_surface_contact_mesh_pt; Backed_up_surface_contact_mesh_pt=0; // // Output contact elements // ofstream some_file; // char filename[100]; // sprintf(filename,"contact_after.dat"); // some_file.open(filename); // unsigned nel=Surface_contact_mesh_pt->nelement(); // for (unsigned e=0;e<nel;e++) // { // dynamic_cast<NonlinearSurfaceContactElement<ELEMENT>* >( // Surface_contact_mesh_pt->element_pt(e))->output(some_file); // } // some_file.close(); // //pause("done"); } /// Doc the solution void doc_solution(); /// Dummy global error norm for adaptive time-stepping double global_temporal_error_norm(){return 0.0;} private: /// Create contact elements void create_contact_elements() { // How many bulk elements are adjacent to boundary b? unsigned b=Contact_boundary_id; unsigned n_element = Bulk_mesh_pt->nboundary_element(b); // Loop over the bulk elements adjacent to boundary b? for(unsigned e=0;e<n_element;e++) { // Get pointer to the bulk element that is adjacent to boundary b ELEMENT* bulk_elem_pt = dynamic_cast<ELEMENT*>( Bulk_mesh_pt->boundary_element_pt(b,e)); //What is the face index of element e along boundary b int face_index = Bulk_mesh_pt->face_index_at_boundary(b,e); // Build the corresponding contact element NonlinearSurfaceContactElement<ELEMENT>* contact_element_pt = new NonlinearSurfaceContactElement<ELEMENT>(bulk_elem_pt,face_index); //Add the contact element to the surface mesh Surface_contact_mesh_pt->add_element_pt(contact_element_pt); } //end of loop over bulk elements adjacent to boundary b } /// Delete contact elements void delete_contact_elements() { // How many surface elements are in the surface mesh unsigned n_element = Surface_contact_mesh_pt->nelement(); // Loop over the surface elements for(unsigned e=0;e<n_element;e++) { // Kill surface element delete Surface_contact_mesh_pt->element_pt(e); } // Wipe the mesh Surface_contact_mesh_pt->flush_element_and_node_storage(); } /// Helper function to (re-)set boundary condition /// and complete the build of all elements void complete_problem_setup() { // Set (pseudo-)solid mechanics properties for all elements //--------------------------------------------------------- unsigned n_element = Bulk_mesh_pt->nelement(); for(unsigned e=0;e<n_element;e++) { //Cast to a solid element ELEMENT *el_pt = dynamic_cast<ELEMENT*>(Bulk_mesh_pt->element_pt(e)); // Set the constitutive law el_pt->constitutive_law_pt() = ProblemParameters::Constitutive_law_pt; // Set density to zero el_pt->lambda_sq_pt()=&ProblemParameters::Lambda_sq; // Disable inertia el_pt->disable_inertia(); } // Apply boundary conditions for solid //------------------------------------ // Bottom: completely pinned unsigned b=Bottom_boundary_id; unsigned nnod=Bulk_mesh_pt->nboundary_node(b); for (unsigned j=0;j<nnod;j++) { SolidNode* nod_pt=Bulk_mesh_pt->boundary_node_pt(b,j); nod_pt->pin_position(0); nod_pt->pin_position(1); } // Sides: Symmetry bcs b=Left_boundary_id; nnod=Bulk_mesh_pt->nboundary_node(b); for (unsigned j=0;j<nnod;j++) { SolidNode* nod_pt=Bulk_mesh_pt->boundary_node_pt(b,j); nod_pt->pin_position(0); } b=Right_boundary_id; nnod=Bulk_mesh_pt->nboundary_node(b); for (unsigned j=0;j<nnod;j++) { SolidNode* nod_pt=Bulk_mesh_pt->boundary_node_pt(b,j); nod_pt->pin_position(0); } // hierher // if (!CommandLineArgs::command_line_flag_has_been_set("--proper_elasticity")) // { // // Assign the Lagrangian coordinates -- sensible // // because we've completely rebuilt the mesh // // and haven't copied across any Lagrange multipliers // Bulk_mesh_pt->set_lagrangian_nodal_coordinates(); // } // Loop over the contact elements to pass pointer to penetrator //------------------------------------------------------------- n_element=Surface_contact_mesh_pt->nelement(); for(unsigned e=0;e<n_element;e++) { // Upcast from GeneralisedElement NonlinearSurfaceContactElement<ELEMENT> *el_pt = dynamic_cast<NonlinearSurfaceContactElement<ELEMENT>*>( Surface_contact_mesh_pt->element_pt(e)); // Set pointer to penetrator el_pt->set_penetrator_pt(ProblemParameters::Penetrator_pt); } } /// Pointer to bulk mesh RefineableSolidTriangleMesh<ELEMENT>* Bulk_mesh_pt; /// Pointer to the "surface" mesh Mesh* Surface_contact_mesh_pt; /// ID of contact boundary unsigned Contact_boundary_id; /// ID of bottom boundary unsigned Bottom_boundary_id; /// ID of left boundary unsigned Left_boundary_id; /// ID of right boundary unsigned Right_boundary_id; /// Trace file ofstream Trace_file; // Setup labels for output DocInfo Doc_info; /// Backup of Surface_contact_mesh_pt so the Lagrange multipliers /// can be projected across BackupMeshForProjection<TElement<1,3> >* Backed_up_surface_contact_mesh_pt; }; // end of problem class //========start_of_constructor============================================ /// Constructor for contact problem in square domain //======================================================================== template<class ELEMENT> ContactProblem<ELEMENT>::ContactProblem() { // Initialise Backed_up_surface_contact_mesh_pt=0; // Output directory Doc_info.set_directory("RESLT"); // Output number Doc_info.number()=0; // Open trace file Trace_file.open("RESLT/trace.dat"); // Allow for crap initial guess Problem::Max_residuals=10000.0; // Allocate the timestepper -- this constructs the Problem's // time object with a sufficient amount of storage to store the // previous timsteps. add_time_stepper_pt(new BDF<2>); double x_ll=0.0; double x_ur=1.0; double y_ll=0.0; double y_ur=1.0; // Pointer to the closed curve that defines the outer boundary TriangleMeshClosedCurve* closed_curve_pt=0; // Build outer boundary as Polygon // The boundary is bounded by five distinct boundaries, each // represented by its own polyline Vector<TriangleMeshCurveSection*> boundary_polyline_pt(4); // Vertex coordinates on boundary Vector<Vector<double> > bound_coords(2); // Left boundary bound_coords[0].resize(2); bound_coords[0][0]=x_ll; bound_coords[0][1]=y_ur; bound_coords[1].resize(2); bound_coords[1][0]=x_ll; bound_coords[1][1]=y_ll; // Build the boundary polyline Left_boundary_id=0; boundary_polyline_pt[0]=new TriangleMeshPolyLine(bound_coords, Left_boundary_id); // Bottom boundary bound_coords[0].resize(2); bound_coords[0][0]=x_ll; bound_coords[0][1]=y_ll; bound_coords[1].resize(2); bound_coords[1][0]=x_ur; bound_coords[1][1]=y_ll; // Build the boundary polyline Bottom_boundary_id=1; boundary_polyline_pt[1]=new TriangleMeshPolyLine(bound_coords, Bottom_boundary_id); // Right boundary bound_coords[0].resize(2); bound_coords[0][0]=x_ur; bound_coords[0][1]=y_ll; bound_coords[1].resize(2); bound_coords[1][0]=x_ur; bound_coords[1][1]=y_ur; // Build the boundary polyline Right_boundary_id=2; boundary_polyline_pt[2]=new TriangleMeshPolyLine(bound_coords, Right_boundary_id); // Contact boundary unsigned npt_contact=4; Vector<Vector<double> > contact_bound_coords(npt_contact); contact_bound_coords[0].resize(2); contact_bound_coords[0][0]=x_ur; contact_bound_coords[0][1]=y_ur; for (unsigned j=1;j<npt_contact-1;j++) { contact_bound_coords[j].resize(2); contact_bound_coords[j][0]=x_ur-(x_ur-x_ll)*double(j)/double(npt_contact-1); contact_bound_coords[j][1]=y_ur; } contact_bound_coords[npt_contact-1].resize(2); contact_bound_coords[npt_contact-1][0]=x_ll; contact_bound_coords[npt_contact-1][1]=y_ur; // Build boundary poly line Contact_boundary_id=3; TriangleMeshPolyLine*contact_boundary_pt= new TriangleMeshPolyLine(contact_bound_coords, Contact_boundary_id); boundary_polyline_pt[3]=contact_boundary_pt; // Create the triangle mesh polygon for outer boundary //---------------------------------------------------- TriangleMeshPolygon *outer_polygon = new TriangleMeshPolygon(boundary_polyline_pt); // Set the pointer closed_curve_pt = outer_polygon; // Now build the mesh //=================== // Use the TriangleMeshParameters object for helping on the manage of the // TriangleMesh parameters TriangleMeshParameters triangle_mesh_parameters(closed_curve_pt); // Specify the maximum area element double uniform_element_area=ProblemParameters::El_area; triangle_mesh_parameters.element_area() = uniform_element_area; // Create the mesh Bulk_mesh_pt=new RefineableSolidTriangleMesh<ELEMENT>(triangle_mesh_parameters, time_stepper_pt()); // Set error estimator for bulk mesh Z2ErrorEstimator* error_estimator_pt=new Z2ErrorEstimator; Bulk_mesh_pt->spatial_error_estimator_pt()=error_estimator_pt; // Create the surface mesh as an empty mesh Surface_contact_mesh_pt=new Mesh; // Build 'em create_contact_elements(); // Set boundary condition and complete the build of all elements complete_problem_setup(); // Add the two sub meshes to the problem add_sub_mesh(Bulk_mesh_pt); add_sub_mesh(Surface_contact_mesh_pt); // Combine all submeshes into a single global Mesh build_global_mesh(); // Do equation numbering cout <<"Number of equations: " << assign_eqn_numbers() << std::endl; } // end of constructor //=======start_of_doc_solution============================================ /// Doc the solution //======================================================================== template<class ELEMENT> void ContactProblem<ELEMENT>::doc_solution() { oomph_info << "Outputting for step: " << Doc_info.number() << std::endl; ofstream some_file; char filename[100]; // Number of plot points unsigned npts; npts=5; // Output solution sprintf(filename,"%s/soln%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); Bulk_mesh_pt->output(some_file,npts); some_file.close(); // Output solution coarsely (only element vertices for easier // mesh visualisation) sprintf(filename,"%s/coarse_soln%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); Bulk_mesh_pt->output(some_file,2); some_file.close(); // Output contact elements sprintf(filename,"%s/contact%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); unsigned nel=Surface_contact_mesh_pt->nelement(); for (unsigned e=0;e<nel;e++) { dynamic_cast<NonlinearSurfaceContactElement<ELEMENT>* >( Surface_contact_mesh_pt->element_pt(e))->output(some_file,20); } some_file.close(); // Output penetrator sprintf(filename,"%s/penetrator%i.dat",Doc_info.directory().c_str(), Doc_info.number()); some_file.open(filename); unsigned nplot=500; ProblemParameters::Penetrator_pt->output(some_file,nplot); some_file.close(); // Write mesh "volume" to trace file Trace_file << time_pt()->time() << " " << Bulk_mesh_pt->total_size() << std::endl; //Increment counter for solutions Doc_info.number()++; } // end of doc_solution /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// /// ///////////////////////////////////////////////////////////////////// //=======start_of_main==================================================== /// Driver code //======================================================================== int main(int argc, char* argv[]) { FiniteElement::Accept_negative_jacobian=true; // Store command line arguments CommandLineArgs::setup(argc,argv); // Define possible command line arguments and parse the ones that // were actually specified // Suppress adaptation CommandLineArgs::specify_command_line_flag("--no_adapt"); // Initial element size CommandLineArgs::specify_command_line_flag("--el_area", &ProblemParameters::El_area); // Resolve after adaptation // hierher CommandLineArgs::specify_command_line_flag("--resolve_after_adapt"); // Suppress adaptation CommandLineArgs::specify_command_line_flag("--validate"); // Parse command line CommandLineArgs::parse_and_assign(); // Doc what has actually been specified on the command line CommandLineArgs::doc_specified_flags(); // Create generalised Hookean constitutive equations ProblemParameters::Constitutive_law_pt = new GeneralisedHookean(&ProblemParameters::Nu); // Define centre of penetrator ProblemParameters::Centre.resize(2); ProblemParameters::Centre[0]=0.5; ProblemParameters::Centre[1]=1.15; // Initial/max y-position: Lift off the surface by a bit... ProblemParameters::Y_c_max=1.0+ProblemParameters::Radius+0.01; // Create penetrator ProblemParameters::Penetrator_pt = new CircularPenetrator(&ProblemParameters::Centre, ProblemParameters::Radius); // Build problem ContactProblem<ProjectablePVDElement<TPVDElement<2,3> > > problem; //Output initial condition problem.doc_solution(); unsigned max_adapt=1; if (CommandLineArgs::command_line_flag_has_been_set("--no_adapt")) { max_adapt=0; } // Number of parameter increments per period unsigned nstep_for_period=40; // 100; // Parameter variation unsigned nperiod=3; // Initial timestep double dt=1.0/double(nstep_for_period); // Initialise timestep -- also sets the weights for all timesteppers // in the problem. problem.initialise_dt(dt); double t_max=double(nperiod); if (CommandLineArgs::command_line_flag_has_been_set("--validate")) { t_max=10.0*dt; } //while (ProblemParameters::Centre[1]>1.08) while (problem.time_pt()->time()<t_max) { // Dummy double adaptivity (timestep is always accepted because // tolerance is set to huge value; mainly used to automatically // re-solve with smaller timestep increment after non-convergence double epsilon_t=DBL_MAX; bool first=false; unsigned suppress_resolve_after_spatial_adapt_flag=1; if (CommandLineArgs::command_line_flag_has_been_set("--resolve_after_adapt")) { suppress_resolve_after_spatial_adapt_flag=0; } // hierher suppress_resolve_after_spatial_adapt_flag=0; double next_dt= problem.doubly_adaptive_unsteady_newton_solve( dt, epsilon_t, max_adapt, suppress_resolve_after_spatial_adapt_flag, first); dt = next_dt; //Output solution problem.doc_solution(); } } // end of main
28.60166
82
0.649838
[ "mesh", "object", "vector", "solid" ]
d4add560e7869e38608d69ed19c34aadf9c4deee
1,104
cc
C++
srcs/apt-1.0.9.2/apt-pkg/vendor.cc
Ziul/tcc1
97dc2b9afcd6736aa8158066b95a698301629543
[ "CC-BY-3.0" ]
null
null
null
srcs/apt-1.0.9.2/apt-pkg/vendor.cc
Ziul/tcc1
97dc2b9afcd6736aa8158066b95a698301629543
[ "CC-BY-3.0" ]
2
2015-11-21T02:30:20.000Z
2015-11-21T02:30:35.000Z
srcs/apt-1.0.9.2/apt-pkg/vendor.cc
Ziul/tcc1
97dc2b9afcd6736aa8158066b95a698301629543
[ "CC-BY-3.0" ]
null
null
null
#include<config.h> #include <apt-pkg/vendor.h> #include <apt-pkg/configuration.h> #include <iostream> #include <map> #include <string> #include <utility> #include <vector> Vendor::Vendor(std::string VendorID, std::string Origin, std::vector<struct Vendor::Fingerprint *> *FingerprintList) { this->VendorID = VendorID; this->Origin = Origin; for (std::vector<struct Vendor::Fingerprint *>::iterator I = FingerprintList->begin(); I != FingerprintList->end(); ++I) { if (_config->FindB("Debug::Vendor", false)) std::cerr << "Vendor \"" << VendorID << "\": Mapping \"" << (*I)->Print << "\" to \"" << (*I)->Description << '"' << std::endl; Fingerprints[(*I)->Print] = (*I)->Description; } delete FingerprintList; } const std::string Vendor::LookupFingerprint(std::string Print) const { std::map<std::string,std::string>::const_iterator Elt = Fingerprints.find(Print); if (Elt == Fingerprints.end()) return ""; else return (*Elt).second; } APT_CONST bool Vendor::CheckDist(std::string /*Dist*/) { return true; }
26.285714
89
0.622283
[ "vector" ]
d4aece98982717d28d05e4450330ac0b23b35bfc
465
hpp
C++
vector.hpp
dominiKoeppl/distinct_squares
af497ea9e87e65cfeecf6d2a00fdc4df00c3180b
[ "BSD-2-Clause" ]
2
2017-02-04T14:18:56.000Z
2021-06-12T07:24:02.000Z
vector.hpp
koeppl/distinct_squares
ded607a7f7ad381b5c7fb759b4301989bfd2b2d8
[ "BSD-2-Clause" ]
null
null
null
vector.hpp
koeppl/distinct_squares
ded607a7f7ad381b5c7fb759b4301989bfd2b2d8
[ "BSD-2-Clause" ]
null
null
null
#pragma once #ifndef VECTOR_HPP #define VECTOR_HPP #include <vector> #include <stdexcept> template<class T> class Vector : public std::vector<T> { public: using std::vector<T>::vector; #ifndef NDEBUG T& operator[](size_t n) /*override*/ { DCHECK_LT(n, this->size()); return std::vector<T>::at(n); } const T& operator[](size_t n) const /*override*/ { DCHECK_LT(n, this->size()); return std::vector<T>::at(n); } #endif }; #endif /* VECTOR_HPP */
17.884615
52
0.651613
[ "vector" ]
d4b001baadfab649286b850246f6ae6456d88143
2,299
hpp
C++
include/UnityEngine/UI/IMask.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/IMask.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
include/UnityEngine/UI/IMask.hpp
marksteward/BeatSaber-Quest-Codegen
a76f063f71cef207a9f048ad7613835f554911a7
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: RectTransform class RectTransform; } // Completed forward declares // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.UI.IMask // [TokenAttribute] Offset: FFFFFFFF // [EditorBrowsableAttribute] Offset: E5F16C // [ObsoleteAttribute] Offset: E5F16C class IMask { public: // Creating value type constructor for type: IMask IMask() noexcept {} // public UnityEngine.RectTransform get_rectTransform() // Offset: 0xFFFFFFFF UnityEngine::RectTransform* get_rectTransform(); // public System.Boolean Enabled() // Offset: 0xFFFFFFFF bool Enabled(); }; // UnityEngine.UI.IMask #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::IMask*, "UnityEngine.UI", "IMask"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::UI::IMask::get_rectTransform // Il2CppName: get_rectTransform template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::RectTransform* (UnityEngine::UI::IMask::*)()>(&UnityEngine::UI::IMask::get_rectTransform)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::IMask*), "get_rectTransform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: UnityEngine::UI::IMask::Enabled // Il2CppName: Enabled template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::UI::IMask::*)()>(&UnityEngine::UI::IMask::Enabled)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::UI::IMask*), "Enabled", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
41.8
175
0.695955
[ "vector" ]
d4b26da7c090c843e9914415d559642057dc8ff6
1,369
cpp
C++
PrehistoricEngine/src/engine/platform/vulkan/rendering/descriptors/VKDescriptorSet.cpp
Andrispowq/PrehistoricEngine---C-
04159c9119b2f5e0148de21a85aa0dab2d6ba60e
[ "Apache-2.0" ]
1
2020-12-04T13:36:03.000Z
2020-12-04T13:36:03.000Z
PrehistoricEngine/src/engine/platform/vulkan/rendering/descriptors/VKDescriptorSet.cpp
Andrispowq/PrehistoricEngine---C-
04159c9119b2f5e0148de21a85aa0dab2d6ba60e
[ "Apache-2.0" ]
null
null
null
PrehistoricEngine/src/engine/platform/vulkan/rendering/descriptors/VKDescriptorSet.cpp
Andrispowq/PrehistoricEngine---C-
04159c9119b2f5e0148de21a85aa0dab2d6ba60e
[ "Apache-2.0" ]
null
null
null
#include "Includes.hpp" #include "VKDescriptorSet.h" namespace Prehistoric { VKDescriptorSet::VKDescriptorSet(const VKDescriptorSet& other) : device(other.device), swapchain(other.swapchain), set_index(other.set_index) { bindings.reserve(other.bindings.size()); for (VKDescriptorSetBinding* binding : other.bindings) { bindings.push_back(new VKDescriptorSetBinding(*binding)); } } VKDescriptorSet::~VKDescriptorSet() { for (const auto& binding : bindings) { delete binding; } vkDestroyDescriptorSetLayout(device->getDevice(), layout, nullptr); } void VKDescriptorSet::addBinding(VKDescriptorSetBinding* binding) { bindings.push_back(binding); } void VKDescriptorSet::finalise() { std::vector<VkDescriptorSetLayoutBinding> _bindings; _bindings.reserve(bindings.size()); for (auto& binding : bindings) { binding->finalise(); _bindings.push_back(binding->getBinding()); } VkDescriptorSetLayoutCreateInfo _createInfo = {}; _createInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; _createInfo.bindingCount = (uint32_t)_bindings.size(); _createInfo.pBindings = _bindings.data(); if (vkCreateDescriptorSetLayout(device->getDevice(), &_createInfo, nullptr, &layout) != VK_SUCCESS) { PR_LOG_RUNTIME_ERROR("VKDescriptorSet couldn't create a VkDescriptorSetLayout object!\n"); } } };
25.351852
101
0.750183
[ "object", "vector" ]
d4b53b38ef5f79001d8c04644dc628674234121f
7,609
cpp
C++
Jolt/Physics/Body/BodyCreationSettings.cpp
sherief/JoltPhysics
aa6910724d54e81a451bef6deb1544bd6b33541f
[ "MIT" ]
null
null
null
Jolt/Physics/Body/BodyCreationSettings.cpp
sherief/JoltPhysics
aa6910724d54e81a451bef6deb1544bd6b33541f
[ "MIT" ]
null
null
null
Jolt/Physics/Body/BodyCreationSettings.cpp
sherief/JoltPhysics
aa6910724d54e81a451bef6deb1544bd6b33541f
[ "MIT" ]
null
null
null
// SPDX-FileCopyrightText: 2021 Jorrit Rouwe // SPDX-License-Identifier: MIT #include <Jolt/Jolt.h> #include <Jolt/Physics/Body/BodyCreationSettings.h> #include <Jolt/ObjectStream/TypeDeclarations.h> #include <Jolt/Core/StreamIn.h> #include <Jolt/Core/StreamOut.h> JPH_NAMESPACE_BEGIN JPH_IMPLEMENT_SERIALIZABLE_NON_VIRTUAL(BodyCreationSettings) { JPH_ADD_ATTRIBUTE(BodyCreationSettings, mPosition) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mRotation) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mUserData) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mShape) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mCollisionGroup) JPH_ADD_ENUM_ATTRIBUTE(BodyCreationSettings, mObjectLayer) JPH_ADD_ENUM_ATTRIBUTE(BodyCreationSettings, mMotionType) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mAllowDynamicOrKinematic) JPH_ADD_ENUM_ATTRIBUTE(BodyCreationSettings, mMotionQuality) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mAllowSleeping) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mFriction) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mRestitution) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mLinearDamping) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mAngularDamping) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mMaxLinearVelocity) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mMaxAngularVelocity) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mGravityFactor) JPH_ADD_ENUM_ATTRIBUTE(BodyCreationSettings, mOverrideMassProperties) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mInertiaMultiplier) JPH_ADD_ATTRIBUTE(BodyCreationSettings, mMassPropertiesOverride) } void BodyCreationSettings::SaveBinaryState(StreamOut &inStream) const { inStream.Write(mPosition); inStream.Write(mRotation); mCollisionGroup.SaveBinaryState(inStream); inStream.Write(mObjectLayer); inStream.Write(mMotionType); inStream.Write(mAllowDynamicOrKinematic); inStream.Write(mMotionQuality); inStream.Write(mAllowSleeping); inStream.Write(mFriction); inStream.Write(mRestitution); inStream.Write(mLinearDamping); inStream.Write(mAngularDamping); inStream.Write(mMaxLinearVelocity); inStream.Write(mMaxAngularVelocity); inStream.Write(mGravityFactor); inStream.Write(mOverrideMassProperties); inStream.Write(mInertiaMultiplier); mMassPropertiesOverride.SaveBinaryState(inStream); } void BodyCreationSettings::RestoreBinaryState(StreamIn &inStream) { inStream.Read(mPosition); inStream.Read(mRotation); mCollisionGroup.RestoreBinaryState(inStream); inStream.Read(mObjectLayer); inStream.Read(mMotionType); inStream.Read(mAllowDynamicOrKinematic); inStream.Read(mMotionQuality); inStream.Read(mAllowSleeping); inStream.Read(mFriction); inStream.Read(mRestitution); inStream.Read(mLinearDamping); inStream.Read(mAngularDamping); inStream.Read(mMaxLinearVelocity); inStream.Read(mMaxAngularVelocity); inStream.Read(mGravityFactor); inStream.Read(mOverrideMassProperties); inStream.Read(mInertiaMultiplier); mMassPropertiesOverride.RestoreBinaryState(inStream); } Shape::ShapeResult BodyCreationSettings::ConvertShapeSettings() { // If we already have a shape, return it if (mShapePtr != nullptr) { mShape = nullptr; Shape::ShapeResult result; result.Set(const_cast<Shape *>(mShapePtr.GetPtr())); return result; } // Check if we have shape settings if (mShape == nullptr) { Shape::ShapeResult result; result.SetError("No shape present!"); return result; } // Create the shape Shape::ShapeResult result = mShape->Create(); if (result.IsValid()) mShapePtr = result.Get(); mShape = nullptr; return result; } const Shape *BodyCreationSettings::GetShape() const { // If we already have a shape, return it if (mShapePtr != nullptr) return mShapePtr; // Check if we have shape settings if (mShape == nullptr) return nullptr; // Create the shape Shape::ShapeResult result = mShape->Create(); if (result.IsValid()) return result.Get(); Trace("Error: %s", result.GetError().c_str()); JPH_ASSERT(false, "An error occurred during shape creation. Use ConvertShapeSettings() to convert the shape and get the error!"); return nullptr; } MassProperties BodyCreationSettings::GetMassProperties() const { // Calculate mass properties MassProperties mass_properties; switch (mOverrideMassProperties) { case EOverrideMassProperties::CalculateMassAndInertia: mass_properties = GetShape()->GetMassProperties(); mass_properties.mInertia *= mInertiaMultiplier; mass_properties.mInertia(3, 3) = 1.0f; break; case EOverrideMassProperties::CalculateInertia: mass_properties = GetShape()->GetMassProperties(); mass_properties.ScaleToMass(mMassPropertiesOverride.mMass); mass_properties.mInertia *= mInertiaMultiplier; mass_properties.mInertia(3, 3) = 1.0f; break; case EOverrideMassProperties::MassAndInertiaProvided: mass_properties = mMassPropertiesOverride; break; } return mass_properties; } void BodyCreationSettings::SaveWithChildren(StreamOut &inStream, ShapeToIDMap *ioShapeMap, MaterialToIDMap *ioMaterialMap, GroupFilterToIDMap *ioGroupFilterMap) const { // Save creation settings SaveBinaryState(inStream); // Save shape if (ioShapeMap != nullptr && ioMaterialMap != nullptr) GetShape()->SaveWithChildren(inStream, *ioShapeMap, *ioMaterialMap); else inStream.Write(~uint32(0)); // Save group filter const GroupFilter *group_filter = mCollisionGroup.GetGroupFilter(); if (ioGroupFilterMap == nullptr || group_filter == nullptr) { // Write null ID inStream.Write(~uint32(0)); } else { GroupFilterToIDMap::const_iterator group_filter_id = ioGroupFilterMap->find(group_filter); if (group_filter_id != ioGroupFilterMap->end()) { // Existing group filter, write ID inStream.Write(group_filter_id->second); } else { // New group filter, write the ID uint32 new_group_filter_id = (uint32)ioGroupFilterMap->size(); (*ioGroupFilterMap)[group_filter] = new_group_filter_id; inStream.Write(new_group_filter_id); // Write the group filter group_filter->SaveBinaryState(inStream); } } } BodyCreationSettings::BCSResult BodyCreationSettings::sRestoreWithChildren(StreamIn &inStream, IDToShapeMap &ioShapeMap, IDToMaterialMap &ioMaterialMap, IDToGroupFilterMap &ioGroupFilterMap) { BCSResult result; // Read creation settings BodyCreationSettings settings; settings.RestoreBinaryState(inStream); if (inStream.IsEOF() || inStream.IsFailed()) { result.SetError("Error reading body creation settings"); return result; } // Read shape Shape::ShapeResult shape_result = Shape::sRestoreWithChildren(inStream, ioShapeMap, ioMaterialMap); if (shape_result.HasError()) { result.SetError(shape_result.GetError()); return result; } settings.SetShape(shape_result.Get()); // Read group filter const GroupFilter *group_filter = nullptr; uint32 group_filter_id = ~uint32(0); inStream.Read(group_filter_id); if (group_filter_id != ~uint32(0)) { // Check if it already exists if (group_filter_id >= ioGroupFilterMap.size()) { // New group filter, restore it GroupFilter::GroupFilterResult group_filter_result = GroupFilter::sRestoreFromBinaryState(inStream); if (group_filter_result.HasError()) { result.SetError(group_filter_result.GetError()); return result; } group_filter = group_filter_result.Get(); JPH_ASSERT(group_filter_id == ioGroupFilterMap.size()); ioGroupFilterMap.push_back(group_filter); } else { // Existing group filter group_filter = ioGroupFilterMap[group_filter_id]; } } // Set the group filter on the part settings.mCollisionGroup.SetGroupFilter(group_filter); result.Set(settings); return result; } JPH_NAMESPACE_END
30.558233
190
0.786963
[ "shape" ]
d4b58d07c4701137b7fc7ffa3260af9784c88db5
2,729
cpp
C++
src/Base/MultiValueSeqGraphView.cpp
rafaelxero/choreonoid
c7273027655f4bc72568888ffd863a1d289d6fdc
[ "MIT" ]
null
null
null
src/Base/MultiValueSeqGraphView.cpp
rafaelxero/choreonoid
c7273027655f4bc72568888ffd863a1d289d6fdc
[ "MIT" ]
null
null
null
src/Base/MultiValueSeqGraphView.cpp
rafaelxero/choreonoid
c7273027655f4bc72568888ffd863a1d289d6fdc
[ "MIT" ]
null
null
null
/** @author Shin'ichiro Nakaoka */ #include "MultiValueSeqGraphView.h" #include "ViewManager.h" #include <boost/lexical_cast.hpp> #include "gettext.h" using namespace std; using namespace cnoid; using namespace std::placeholders; void MultiValueSeqGraphView::initializeClass(ExtensionManager* ext) { ext->viewManager().registerClass<MultiValueSeqGraphView>( "MultiValueSeqGraphView", N_("Multi Value Seq"), ViewManager::SINGLE_OPTIONAL); } MultiValueSeqGraphView::MultiValueSeqGraphView() { setDefaultLayoutArea(View::BOTTOM); } MultiValueSeqGraphView::~MultiValueSeqGraphView() { } int MultiValueSeqGraphView::currentNumParts(const ItemList<>& items) const { MultiValueSeqItem* item = static_cast<MultiValueSeqItem*>(items.front().get()); return item->seq()->numParts(); } ItemList<> MultiValueSeqGraphView::extractTargetItems(const ItemList<>& items) const { return ItemList<MultiValueSeqItem>(items); } void MultiValueSeqGraphView::addGraphDataHandlers(Item* item, int partIndex, std::vector<GraphDataHandlerPtr>& out_handlers) { auto seqItem = static_cast<MultiValueSeqItem*>(item); auto seq = seqItem->seq(); if(partIndex < seq->numParts()){ GraphDataHandlerPtr handler(new GraphDataHandler()); handler->setID(partIndex); handler->setLabel(boost::lexical_cast<string>(partIndex)); //handler->setValueLimits(llimit, ulimit); //handler->setVelocityLimits(lvlimit, uvlimit); handler->setFrameProperties(seq->numFrames(), seq->frameRate()); handler->setDataRequestCallback( std::bind(&MultiValueSeqGraphView::onDataRequest, this, seq, partIndex, _1, _2, _3)); handler->setDataModifiedCallback( std::bind(&MultiValueSeqGraphView::onDataModified, this, seqItem, partIndex, _1, _2, _3)); out_handlers.push_back(handler); } } void MultiValueSeqGraphView::updateGraphDataHandler(Item* item, GraphDataHandlerPtr handler) { auto seq = static_cast<MultiValueSeqItem*>(item)->seq(); handler->setFrameProperties(seq->numFrames(), seq->frameRate()); handler->update(); } void MultiValueSeqGraphView::onDataRequest (std::shared_ptr<MultiValueSeq> seq, int partIndex, int frame, int size, double* out_values) { MultiValueSeq::Part part = seq->part(partIndex); for(int i=0; i < size; ++i){ out_values[i] = part[frame + i]; } } void MultiValueSeqGraphView::onDataModified (MultiValueSeqItem* item, int partIndex, int frame, int size, double* values) { MultiValueSeq::Part part = item->seq()->part(partIndex); for(int i=0; i < size; ++i){ part[frame + i] = values[i]; } GraphViewBase::notifyUpdateByEditing(item); }
27.846939
124
0.711616
[ "vector" ]
d4b59241f8517aa42b53f64b412c354725e57f61
4,218
cpp
C++
src/game/server/tf/func_forcefield.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/server/tf/func_forcefield.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/server/tf/func_forcefield.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #include "cbase.h" #include "func_forcefield.h" #include "tf_shareddefs.h" #include "tf_gamerules.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_AUTO_LIST( IFuncForceFieldAutoList ); //=========================================================================================================== LINK_ENTITY_TO_CLASS( func_forcefield, CFuncForceField ); BEGIN_DATADESC( CFuncForceField ) END_DATADESC() IMPLEMENT_SERVERCLASS_ST( CFuncForceField, DT_FuncForceField ) END_SEND_TABLE() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFuncForceField::Spawn( void ) { BaseClass::Spawn(); SetActive( IsOn() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CFuncForceField::UpdateTransmitState() { return SetTransmitState( FL_EDICT_ALWAYS ); } //----------------------------------------------------------------------------- // Purpose: Only transmit this entity to clients that aren't in our team //----------------------------------------------------------------------------- int CFuncForceField::ShouldTransmit( const CCheckTransmitInfo *pInfo ) { return FL_EDICT_ALWAYS; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFuncForceField::TurnOff( void ) { BaseClass::TurnOff(); SetActive( false ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFuncForceField::TurnOn( void ) { BaseClass::TurnOn(); SetActive( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CFuncForceField::ShouldCollide( int collisionGroup, int contentsMask ) const { // Force fields are off during a team win if ( TFGameRules()->State_Get() == GR_STATE_TEAM_WIN ) return false; if ( GetTeamNumber() == TEAM_UNASSIGNED ) return false; if ( collisionGroup == COLLISION_GROUP_PLAYER_MOVEMENT ) { switch ( GetTeamNumber() ) { case TF_TEAM_BLUE: if ( !( contentsMask & CONTENTS_BLUETEAM ) ) return false; break; case TF_TEAM_RED: if ( !( contentsMask & CONTENTS_REDTEAM ) ) return false; break; } return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CFuncForceField::SetActive( bool bActive ) { if ( bActive ) { // We're a trigger, but we want to be solid. Our ShouldCollide() will make // us non-solid to members of the team that spawns here. RemoveSolidFlags( FSOLID_TRIGGER ); RemoveSolidFlags( FSOLID_NOT_SOLID ); } else { AddSolidFlags( FSOLID_NOT_SOLID ); AddSolidFlags( FSOLID_TRIGGER ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool PointsCrossForceField( const Vector& vecStart, const Vector &vecEnd, int nTeamToIgnore ) { // Setup the ray. Ray_t ray; ray.Init( vecStart, vecEnd ); for ( int i = 0; i < IFuncForceFieldAutoList::AutoList().Count(); ++i ) { CFuncForceField *pEntity = static_cast< CFuncForceField* >( IFuncForceFieldAutoList::AutoList()[i] ); if ( pEntity->m_iDisabled ) continue; if ( pEntity->GetTeamNumber() == nTeamToIgnore && nTeamToIgnore != TEAM_UNASSIGNED ) continue; trace_t trace; enginetrace->ClipRayToEntity( ray, MASK_ALL, pEntity, &trace ); if ( trace.fraction < 1.0f ) { return true; } } return false; }
27.933775
109
0.458511
[ "vector", "solid" ]
d4b5e4bba2f036846a6e2c2afe6807dee041c522
6,742
cpp
C++
src/lib/cli_cpp/cmd/A_CLI_Command.cpp
marvins/cli-cpp
4f98a09d5cfeffe0d5c330cda3272ae207c511d1
[ "MIT" ]
4
2020-10-08T03:09:10.000Z
2022-03-13T09:22:51.000Z
src/lib/cli_cpp/cmd/A_CLI_Command.cpp
marvins/cli-cpp
4f98a09d5cfeffe0d5c330cda3272ae207c511d1
[ "MIT" ]
4
2015-05-30T17:40:46.000Z
2015-07-01T01:10:16.000Z
src/lib/cli_cpp/cmd/A_CLI_Command.cpp
marvins/cli-cpp
4f98a09d5cfeffe0d5c330cda3272ae207c511d1
[ "MIT" ]
2
2015-06-02T20:07:39.000Z
2020-12-16T09:25:38.000Z
/** * @file A_CLI_Command.cpp * @author Marvin Smith * @date 5/19/2015 */ #include "A_CLI_Command.hpp" // C++ Standard Libraries #include <iostream> // CLI Libraries #include "../utility/String_Utilities.hpp" namespace CLI{ namespace CMD{ /***********************************/ /* Constructor */ /***********************************/ A_CLI_Command::A_CLI_Command( const CommandParseStatus& mode ) : m_class_name("A_CLI_Command"), m_mode(mode), m_names(0), m_formal_name(""), m_description(""), m_command_argument_list(0), m_response_expected(false) { } /***********************************/ /* Constructor */ /***********************************/ A_CLI_Command::A_CLI_Command( const CommandParseStatus& mode, const std::vector<std::string>& names, const std::string& formal_name, const std::string& description ) : m_class_name("A_CLI_Command"), m_mode(mode), m_names(names), m_formal_name(formal_name), m_description(description), m_command_argument_list(0) { } /************************************/ /* Add Name */ /************************************/ void A_CLI_Command::Add_Name( const std::string& name ) { m_names.push_back( name ); } /***************************************************/ /* Add Command Argument */ /***************************************************/ void A_CLI_Command::Add_Argument( const A_Command_Argument& arg ) { m_command_argument_list.push_back(arg); } /****************************/ /* Set formal Name */ /****************************/ void A_CLI_Command::Set_Formal_Name( const std::string& formal_name ) { m_formal_name = formal_name; } /************************************/ /* Check Arguments */ /************************************/ bool A_CLI_Command::Check_Argument_Type( const int& argument_idx, const std::string& test_argument )const { // Check the size if( argument_idx < 0 || argument_idx >= (int)m_command_argument_list.size() ){ return false; } // Compare return m_command_argument_list[argument_idx].Is_Valid_Type( test_argument ); } /****************************/ /* Is Valid */ /****************************/ bool A_CLI_Command::Is_Name_Match( const std::string& name )const { // Iterate over all supported names for( size_t i=0; i<m_names.size(); i++ ){ if( m_names[i] == name ){ return true; } } return false; } /*******************************************/ /* Check Name Substring Match */ /*******************************************/ bool A_CLI_Command::Is_Name_Substring( const std::string& input_string, std::string& match_result )const { // Match list std::vector<std::string> match_list; // Iterate over the name list for( size_t i=0; i<m_names.size(); i++ ) { // If the name is less than the input, it cannot match if( m_names[i].size() < input_string.size() ){ continue; } // If the sizes are the same, do a string compare else if( m_names[i].size() == input_string.size() ){ if( m_names[i] == input_string ){ match_list.push_back(m_names[i]); } else{ continue; } } // Otherwise, the name is greater than the input, so check the substring match else{ // Look for a perfect substring match if( m_names[i].substr(0, input_string.size()) == input_string ){ match_list.push_back(m_names[i]); } } } // Check if we found any matches if( (int)match_list.size() <= 0 ){ match_result = ""; return false; } // Find the minimum spanning substring match_result = match_list[0]; for( size_t i=1; i<match_list.size(); i++ ){ match_result = UTILS::String_Substring_Match( match_result, match_list[i]); } // success return true; } /********************************************/ /* Check if Argument is a Match */ /********************************************/ bool A_CLI_Command::Is_Argument_Substring( const int& argument_index, const std::string& argument_name, std::string& match_name )const { // Don't go over bounds if( argument_index >= (int)m_command_argument_list.size() ){ return false; } // Pass to argument return m_command_argument_list[argument_index].Is_Argument_Substring( argument_name, match_name ); } /********************************/ /* Equivalent Operator */ /********************************/ bool A_CLI_Command::operator ==( A_CLI_Command const& other )const { // Check the name if( m_formal_name != other.m_formal_name ){ return false; } // Check the mode if( m_mode != other.m_mode ){ return false; } // Check the name list if( m_names.size() != other.m_names.size() ){ return false; } for( int i=0; i<(int)m_names.size(); i++ ){ if( m_names[i] != other.m_names[i] ){ return false; } } // return success return true; } /*****************************************/ /* Write as a Command */ /*****************************************/ A_Command A_CLI_Command::To_Command()const{ return A_Command( m_names[0], Get_Description(), m_response_expected, m_command_argument_list ); } /*************************************************/ /* Write as a debugging string */ /*************************************************/ std::string A_CLI_Command::To_Debug_String()const { // Create the stream std::stringstream sin; sin << m_class_name << ":\n"; sin << " Formal Name: " << Get_Formal_Name() << std::endl; sin << " Description: " << Get_Description() << std::endl; // Iterate over arguments sin << " Arguments:\n"; for( size_t i=0; i<m_command_argument_list.size(); i++ ){ sin << m_command_argument_list[i].To_Debug_String(8) << std::endl; } // Return output return sin.str(); } } // End of CMD Namespace } // End of CLI Namespace
26.648221
88
0.474043
[ "vector" ]
d4b8293efb38cb9771eb5112d4ac6f2413d0cd2e
1,346
hpp
C++
ReactNativeFrontend/ios/Pods/boost/boost/geometry/index/detail/rtree/visitors/is_leaf.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
326
2015-02-08T13:47:49.000Z
2022-03-16T02:13:59.000Z
ReactNativeFrontend/ios/Pods/boost/boost/geometry/index/detail/rtree/visitors/is_leaf.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
623
2015-01-02T23:45:23.000Z
2022-03-09T11:15:23.000Z
ReactNativeFrontend/ios/Pods/boost/boost/geometry/index/detail/rtree/visitors/is_leaf.hpp
Harshitha91/Tmdb-react-native-node
e06e3f25a7ee6946ef07a1f524fdf62e48424293
[ "Apache-2.0" ]
215
2015-01-14T15:50:38.000Z
2022-02-23T03:58:36.000Z
// Boost.Geometry Index // // R-tree leaf node checking visitor implementation // // Copyright (c) 2011-2015 Adam Wulkiewicz, Lodz, Poland. // // This file was modified by Oracle on 2019. // Modifications copyright (c) 2019 Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_IS_LEAF_HPP #define BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_IS_LEAF_HPP namespace boost { namespace geometry { namespace index { namespace detail { namespace rtree { namespace visitors { template <typename MembersHolder> struct is_leaf : public MembersHolder::visitor_const { typedef typename MembersHolder::internal_node internal_node; typedef typename MembersHolder::leaf leaf; is_leaf() : result(false) {} inline void operator()(internal_node const&) { // result = false; } inline void operator()(leaf const&) { result = true; } bool result; }; }}} // namespace detail::rtree::visitors }}} // namespace boost::geometry::index #endif // BOOST_GEOMETRY_INDEX_DETAIL_RTREE_VISITORS_IS_LEAF_HPP
26.392157
79
0.732541
[ "geometry" ]
d4b8e17eab7c6d0f0ffdad28c19402a73c9d1535
5,074
cpp
C++
SPOJ/SPOJ - OTOCI/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
SPOJ/SPOJ - OTOCI/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
SPOJ/SPOJ - OTOCI/Accepted (2).cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 2020-09-30 18:55:33 * solution_verdict: Accepted language: C++ * run_time (ms): 2290 memory_used (MB): 4.8 * problem: https://vjudge.net/problem/SPOJ-OTOCI ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<sstream> #include<unordered_map> #include<unordered_set> #include<chrono> #include<stack> #include<deque> #include<random> #define long long long using namespace std; const int N=1e6; /* represented tree: the actual tree. tree we want to represent. actual tree are forest of some rooted trees. like dsu tree. preferred child: u is called preferred child of v if last accessed node in v's subtree is in u's subtree. preferred child can be null if v is last accessed node or v has no accessed node. preferred edge: edge between node and preferred child. preferred path: continuous path where each edge is preferred edge. preferred path can be a single node. a tree will have many preferred path. each preferred path is node disjoint and every node is in exactly one preferred path. splay tree: splay trees represent preferred path. one splay tree for each path. splay trees are balanced binary search tree where nodes are keyed by their depth in actual tree. path-parent pointer: path parent pointer connects two splay trees. path parent pointer is stored in the root of splay tree and points to parent of the topmost (lowest depth) node of preferred path. so a path parent pointer is an edge of represented tree which is not preferred. */ struct node { int p,ch[2];//parent and child; int dt,sm;//value of the node and sum of subtree(in splay) bool rev;//splay tree operation. int sz;//size of the subtree(in splay). int lz;//lazy add node(){} node(int v):p(-1),dt(v),sm(v),rev(0),sz(1),lz(0){ ch[0]=ch[1]=-1; } }; node t[N+2]; void tooLazy(int x)//lazy propagation { if(t[x].lz) { t[x].dt+=t[x].lz,t[x].sm+=t[x].lz*t[x].sz; if(t[x].ch[0]+1)t[t[x].ch[0]].lz+=t[x].lz; if(t[x].ch[1]+1)t[t[x].ch[1]].lz+=t[x].lz; } if(t[x].rev) { swap(t[x].ch[0],t[x].ch[1]); if(t[x].ch[0]+1)t[t[x].ch[0]].rev^=1; if(t[x].ch[1]+1)t[t[x].ch[1]].rev^=1; } t[x].lz=0,t[x].rev=0; } void cal(int x)//splay tree operation { t[x].sz=1,t[x].sm=t[x].dt; for(int i=0;i<2;i++) { if(t[x].ch[i]+1==0)continue; tooLazy(t[x].ch[i]); t[x].sz+=t[t[x].ch[i]].sz;t[x].sm+=t[t[x].ch[i]].sm; } } bool isRoot(int x) { return (t[x].p==-1)||((t[t[x].p].ch[0]!=x)&&(t[t[x].p].ch[1]!=x)); } void rotate(int x)//splay tree { int p=t[x].p,pp=t[p].p; if(!isRoot(p))t[pp].ch[t[pp].ch[1]==p]=x; bool d=t[p].ch[0]==x; t[p].ch[!d]=t[x].ch[d],t[x].ch[d]=p; if(t[p].ch[!d]+1)t[t[p].ch[!d]].p=p; t[x].p=pp,t[p].p=x;cal(p),cal(x); } int splay(int x)//splay tree { while(!isRoot(x)) { int p=t[x].p,pp=t[p].p; if(!isRoot(p))tooLazy(pp); tooLazy(p),tooLazy(x); if(!isRoot(p))rotate((t[pp].ch[0]==p)^(t[p].ch[0]==x)?x:p); rotate(x); } return tooLazy(x),x; } int access(int v) { int last=-1; for(int w=v;w+1;cal(last=w),splay(v),w=t[v].p) splay(w),t[w].ch[1]=(last==-1?-1:v); return last; } void init(int v,int w){t[v]=node(w);}//node v initialization with value w. int findRoot(int v) { access(v),tooLazy(v); while(t[v].ch[0]+1)v=t[v].ch[0],tooLazy(v); return splay(v); } bool isConnected(int v,int w) { access(v),access(w); return v==w?true:t[v].p!=-1; } void makeRoot(int v) { access(v);t[v].rev^=1; } long query(int u,int v)//query on path u-v { makeRoot(v),access(u); return t[u].sm; } void update(int u,int v,int x)//add x to all node in u-v path { makeRoot(v),access(u); t[u].lz+=x; } void add(int u,int v)//add an edge between u and v. { if(isConnected(u,v))return ; makeRoot(v);t[v].p=u; } void cut(int u,int v)//cut edge between u and v, given they already have edge. { makeRoot(v),access(u); t[u].ch[0]=t[t[u].ch[0]].p=-1; } int lca(int u,int v)//lca between u and v. { access(u);return access(v); } int a[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n,q;cin>>n; for(int i=1;i<=n;i++) { cin>>a[i];init(i,a[i]); } cin>>q; while(q--) { string s;cin>>s; if(s=="bridge") { int a,b;cin>>a>>b; if(isConnected(a,b))cout<<"no\n"; else { cout<<"yes\n";add(a,b); } } else if(s=="penguins") { int v,x;cin>>v>>x; update(v,v,x-a[v]);a[v]=x; } else { int a,b;cin>>a>>b; if(isConnected(a,b))cout<<query(a,b)<<'\n'; else cout<<"impossible\n"; } } return 0; }
24.872549
111
0.565826
[ "vector" ]
d4ba3bb6e40eaca0354448abe2ff71f125749972
1,390
hpp
C++
radix_sort/headers/count_sort_rad.hpp
im029/Algorithms_DataStructures
5d60d298c382935955934f84a59d0fe8c43a2bad
[ "MIT" ]
null
null
null
radix_sort/headers/count_sort_rad.hpp
im029/Algorithms_DataStructures
5d60d298c382935955934f84a59d0fe8c43a2bad
[ "MIT" ]
null
null
null
radix_sort/headers/count_sort_rad.hpp
im029/Algorithms_DataStructures
5d60d298c382935955934f84a59d0fe8c43a2bad
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> /** count_sort.hpp purpose: sorts a vector using count sort @author: Ishant Malik; Algorithm taken from CLRS @version: 1.0.0 08/04/2018 */ void count_sort(std::vector<std::vector<int > *> *const arr, std::vector<std::vector<int> *> *const arr2, const int key) { // variable to store range of numbers at given place value. initally we assume that first one is the range int k = arr->at(0)->at(key); // find the range by finding maximum of the elements at given place value for (unsigned int i = 1; i < arr->size(); i++) if (k < arr->at(i)->at(key)) k = arr->at(i)->at(key); // create an auxiliary array and initally set elements to zero std::vector<int> aux_array; for (int i = 0; i <= k; i++) aux_array.push_back(0); // count the numbers. for (int j = 0; j < arr->size(); j++) aux_array[arr->at(j)->at(key)] = aux_array[arr->at(j)->at(key)] + 1; // cumulate the values for (int i = 1; i <= k; i++) aux_array[i] = aux_array[i] + aux_array[i - 1]; // sort the values by placing them at correct positions in array B for (int j = arr->size() - 1; j >= 0; j--) { arr2->at(aux_array[arr->at(j)->at(key)] - 1) = arr->at(j); aux_array[arr->at(j)->at(key)] = aux_array[arr->at(j)->at(key)] - 1; } //reorder the arr1 to match arr2 for next iteration for (int i = 0; i < arr2->size(); i++) arr->at(i) = arr2->at(i); }
32.325581
120
0.627338
[ "vector" ]
d4bccecba6ee10d52564af60557d07cbe4ad9aa5
1,222
hpp
C++
third_party/boost/simd/function/genmask.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/function/genmask.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/genmask.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_GENMASK_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_GENMASK_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-bitwise This function object returns a mask of bits. This mask is full of ones if the input element is non @ref Zero else full of zeros. @see genmaskc @par Header <boost/simd/function/genmask.hpp> @par Example: @snippet genmask.cpp genmask @par Possible output: @snippet genmask.txt genmask @par Alias: @c if_allbits_else_zero @see if_allbits_else **/ ///@{ as_arithmetic_t<LogicalValue> genmask(const LogicalValue& a); Value genmask(const Value& a); ///@} } } #endif #include <boost/simd/function/scalar/genmask.hpp> #include <boost/simd/function/simd/genmask.hpp> #endif
23.5
100
0.596563
[ "object" ]
d4bd65c8b060d8aa681f55d281b8540935c8d0bd
1,475
cpp
C++
LeetCode/algorithms/permutations/solution.cpp
cuihaoleo/exercises
401dc2f19b6474e84e357a79a53754684fc93784
[ "WTFPL" ]
1
2015-08-30T10:06:41.000Z
2015-08-30T10:06:41.000Z
LeetCode/algorithms/permutations/solution.cpp
cuihaoleo/exercises
401dc2f19b6474e84e357a79a53754684fc93784
[ "WTFPL" ]
null
null
null
LeetCode/algorithms/permutations/solution.cpp
cuihaoleo/exercises
401dc2f19b6474e84e357a79a53754684fc93784
[ "WTFPL" ]
null
null
null
#include <vector> #include <numeric> #include <algorithm> using std::vector; int factorial(int n) { int ret = 1; for (int i = 2; i <= n; i++) ret *= i; return ret; } class Solution { public: vector<vector<int>> permute(vector<int>& nums) { int n = nums.size(); int returnSize = factorial(n); vector<vector<int>> result(returnSize, vector<int>(n)); // Johnson–Trotter algorithm vector<bool> dir(n, false); vector<int> pos(n); vector<int> val(n); std::iota(pos.begin(), pos.end(), 0); val = pos; result[0] = nums; for (int i = 1; i < returnSize; i++) { // find the greatest movable element int chosen, oldPos, newPos, swapped; for (chosen = n - 1; chosen >= 0; chosen--) { oldPos = pos[chosen]; newPos = oldPos + (dir[chosen] ? 1:-1); if (newPos >= 0 && newPos < n && (swapped = val[newPos]) < chosen) break; } // swap pos[swapped] = oldPos; pos[chosen] = newPos; val[oldPos] = swapped; val[newPos] = chosen; // assign the result for (int j = 0; j < n; j++) result[i][j] = nums[val[j]]; // change directions for (int j = chosen + 1; j < n; j++) dir[j] = !dir[j]; } return result; } };
25
82
0.463729
[ "vector" ]
d4cf96920a92864b736ab0cb71156307db4cb0b6
8,010
cpp
C++
src/usb-hid/raw/rawinput.cpp
Florin9doi/USBqemu-wheel
2206de0fc818dc4334acd766b88b7d07ff4edb54
[ "Unlicense" ]
75
2015-02-05T05:56:49.000Z
2022-03-18T23:05:01.000Z
src/usb-hid/raw/rawinput.cpp
Florin9doi/USBqemu-wheel
2206de0fc818dc4334acd766b88b7d07ff4edb54
[ "Unlicense" ]
56
2015-08-08T16:37:35.000Z
2022-01-13T21:31:28.000Z
src/usb-hid/raw/rawinput.cpp
Florin9doi/USBqemu-wheel
2206de0fc818dc4334acd766b88b7d07ff4edb54
[ "Unlicense" ]
20
2015-09-06T19:12:57.000Z
2022-03-22T19:39:06.000Z
#include "rawinput.h" #include "../../Win32/Config.h" #include "qemu-usb/input-keymap.h" #include "qemu-usb/input-keymap-win32-to-qcode.h" namespace usb_hid { namespace raw { #define CHECK(exp) \ do \ { \ if (!(exp)) \ goto Error; \ } while (0) #define SAFE_FREE(p) \ do \ { \ if (p) \ { \ free(p); \ (p) = NULL; \ } \ } while (0) // VKEY from https://docs.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes // and convert to HID usage id from "10 Keyboard/Keypad Page (0x07)" // https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf int RawInput::TokenOut(const uint8_t* data, int len) { // std::array<uint8_t, 8> report{ 0 }; // memcpy(report.data() + 1, data, report.size() - 1); return len; } static void ParseRawInput(PRAWINPUT pRawInput, HIDState* hs) { PHIDP_PREPARSED_DATA pPreparsedData = NULL; HIDP_CAPS Caps; PHIDP_BUTTON_CAPS pButtonCaps = NULL; PHIDP_VALUE_CAPS pValueCaps = NULL; UINT bufferSize = 0; ULONG usageLength, value; TCHAR name[1024] = {0}; UINT nameSize = 1024; RID_DEVICE_INFO devInfo = {0}; std::wstring devName; USHORT capsLength = 0; USAGE usage[32] = {0}; int numberOfButtons; GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_DEVICENAME, name, &nameSize); devName = name; std::transform(devName.begin(), devName.end(), devName.begin(), ::toupper); CHECK(GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_PREPARSEDDATA, NULL, &bufferSize) == 0); CHECK(pPreparsedData = (PHIDP_PREPARSED_DATA)malloc(bufferSize)); CHECK((int)GetRawInputDeviceInfo(pRawInput->header.hDevice, RIDI_PREPARSEDDATA, pPreparsedData, &bufferSize) >= 0); CHECK(HidP_GetCaps(pPreparsedData, &Caps) == HIDP_STATUS_SUCCESS); //Get pressed buttons CHECK(pButtonCaps = (PHIDP_BUTTON_CAPS)malloc(sizeof(HIDP_BUTTON_CAPS) * Caps.NumberInputButtonCaps)); //If fails, maybe wheel only has axes capsLength = Caps.NumberInputButtonCaps; HidP_GetButtonCaps(HidP_Input, pButtonCaps, &capsLength, pPreparsedData); numberOfButtons = pButtonCaps->Range.UsageMax - pButtonCaps->Range.UsageMin + 1; usageLength = countof(usage); //numberOfButtons; NTSTATUS stat; if ((stat = HidP_GetUsages( HidP_Input, pButtonCaps->UsagePage, 0, usage, &usageLength, pPreparsedData, (PCHAR)pRawInput->data.hid.bRawData, pRawInput->data.hid.dwSizeHid)) == HIDP_STATUS_SUCCESS) { for (uint32_t i = 0; i < usageLength; i++) { uint16_t btn = usage[i] - pButtonCaps->Range.UsageMin; } } /// Get axes' values CHECK(pValueCaps = (PHIDP_VALUE_CAPS)malloc(sizeof(HIDP_VALUE_CAPS) * Caps.NumberInputValueCaps)); capsLength = Caps.NumberInputValueCaps; if (HidP_GetValueCaps(HidP_Input, pValueCaps, &capsLength, pPreparsedData) == HIDP_STATUS_SUCCESS) { for (USHORT i = 0; i < capsLength; i++) { if (HidP_GetUsageValue( HidP_Input, pValueCaps[i].UsagePage, 0, pValueCaps[i].Range.UsageMin, &value, pPreparsedData, (PCHAR)pRawInput->data.hid.bRawData, pRawInput->data.hid.dwSizeHid) != HIDP_STATUS_SUCCESS) { continue; // if here then maybe something is up with HIDP_CAPS.NumberInputValueCaps } switch (pValueCaps[i].Range.UsageMin) { case HID_USAGE_GENERIC_X: //0x30 case HID_USAGE_GENERIC_Y: case HID_USAGE_GENERIC_Z: case HID_USAGE_GENERIC_RX: case HID_USAGE_GENERIC_RY: case HID_USAGE_GENERIC_RZ: //0x35 //int axis = (value * 0x3FFF) / pValueCaps[i].LogicalMax; break; case HID_USAGE_GENERIC_HATSWITCH: //fprintf(stderr, "Hat: %02X\n", value); break; } } } Error: SAFE_FREE(pPreparsedData); SAFE_FREE(pButtonCaps); SAFE_FREE(pValueCaps); } static void ParseRawInputKB(RAWKEYBOARD& k, HIDState* hs) { if (hs->kind != HID_KEYBOARD || !hs->kbd.eh_entry) return; static uint32_t nr = 0; OSDebugOut(TEXT("%ud kb: %hu %hu %hu %u\n"), nr, k.MakeCode, k.VKey, k.Flags, k.ExtraInformation); nr++; if (nr > 10) nr = 0; if (KEYBOARD_OVERRUN_MAKE_CODE == k.MakeCode) return; QKeyCode qcode = Q_KEY_CODE_UNMAPPED; if (k.VKey < (int)qemu_input_map_win32_to_qcode.size()) qcode = qemu_input_map_win32_to_qcode[k.VKey]; //TODO if (k.Flags & RI_KEY_E0) { if (Q_KEY_CODE_SHIFT == qcode) qcode = Q_KEY_CODE_SHIFT_R; else if (Q_KEY_CODE_CTRL == qcode) qcode = Q_KEY_CODE_CTRL_R; else if (Q_KEY_CODE_ALT == qcode) qcode = Q_KEY_CODE_ALT_R; } InputEvent ev{}; ev.type = INPUT_EVENT_KIND_KEY; ev.u.key.down = !(k.Flags & RI_KEY_BREAK); ev.u.key.key.type = KEY_VALUE_KIND_QCODE; ev.u.key.key.u.qcode = qcode; hs->kbd.eh_entry(hs, &ev); } static void SendPointerEvent(InputEvent& ev, HIDState* hs) { if (hs->ptr.eh_entry) { hs->ptr.eh_entry(hs, &ev); } } static void ParseRawInputMS(RAWMOUSE& m, HIDState* hs) { if (!hs->ptr.eh_entry || (hs->kind != HID_MOUSE && hs->kind != HID_TABLET)) return; int b = 0, z = 0; InputEvent ev{}; if (m.usButtonFlags & RI_MOUSE_WHEEL) z = (short)m.usButtonData / WHEEL_DELTA; //OSDebugOut(TEXT("mouse: %d %d %u %hd\n"), m.lLastX, m.lLastY, m.ulButtons, z); ev.type = INPUT_EVENT_KIND_BTN; if (m.ulButtons & RI_MOUSE_LEFT_BUTTON_DOWN) { ev.u.btn.button = INPUT_BUTTON_LEFT; ev.u.btn.down = true; SendPointerEvent(ev, hs); } if (m.ulButtons & RI_MOUSE_LEFT_BUTTON_UP) { ev.u.btn.button = INPUT_BUTTON_LEFT; ev.u.btn.down = false; SendPointerEvent(ev, hs); } if (m.ulButtons & RI_MOUSE_RIGHT_BUTTON_DOWN) { ev.u.btn.button = INPUT_BUTTON_RIGHT; ev.u.btn.down = true; SendPointerEvent(ev, hs); } if (m.ulButtons & RI_MOUSE_RIGHT_BUTTON_UP) { ev.u.btn.button = INPUT_BUTTON_RIGHT; ev.u.btn.down = false; SendPointerEvent(ev, hs); } if (m.ulButtons & RI_MOUSE_MIDDLE_BUTTON_DOWN) { ev.u.btn.button = INPUT_BUTTON_MIDDLE; ev.u.btn.down = true; SendPointerEvent(ev, hs); } if (m.ulButtons & RI_MOUSE_MIDDLE_BUTTON_UP) { ev.u.btn.button = INPUT_BUTTON_MIDDLE; ev.u.btn.down = false; SendPointerEvent(ev, hs); } if (z != 0) { ev.u.btn.button = (z < 0) ? INPUT_BUTTON_WHEEL_DOWN : INPUT_BUTTON_WHEEL_UP; for (int i = 0; i < z; i++) { ev.u.btn.down = true; SendPointerEvent(ev, hs); ev.u.btn.down = false; // TODO needs an UP event? SendPointerEvent(ev, hs); } } if (m.usFlags & MOUSE_MOVE_ABSOLUTE) { /*ev.type = INPUT_EVENT_KIND_ABS; ev.u.abs.axis = INPUT_AXIS_X; ev.u.abs.value = m.lLastX; SendPointerEvent(ev, hs); ev.u.abs.axis = INPUT_AXIS_Y; ev.u.abs.value = m.lLastY; SendPointerEvent(ev, hs);*/ } else { ev.type = INPUT_EVENT_KIND_REL; ev.u.rel.axis = INPUT_AXIS_X; ev.u.rel.value = m.lLastX; SendPointerEvent(ev, hs); ev.u.rel.axis = INPUT_AXIS_Y; ev.u.rel.value = m.lLastY; SendPointerEvent(ev, hs); } if (hs->ptr.eh_sync) hs->ptr.eh_sync(hs); } void RawInput::ParseRawInput(PRAWINPUT pRawInput) { if (pRawInput->header.dwType == RIM_TYPEKEYBOARD) ParseRawInputKB(pRawInput->data.keyboard, mHIDState); else if (pRawInput->header.dwType == RIM_TYPEMOUSE) ParseRawInputMS(pRawInput->data.mouse, mHIDState); // else // ParseRawInput(pRawInput, mHIDState); } int RawInput::Open() { Close(); shared::rawinput::RegisterCallback(this); return 0; } int RawInput::Close() { Reset(); shared::rawinput::UnregisterCallback(this); return 0; } int RawInput::Configure(int port, const char* dev_type, HIDType type, void* data) { Win32Handles* h = (Win32Handles*)data; INT_PTR res = RESULT_CANCELED; return res; } } // namespace raw } // namespace usb_hid
27.244898
118
0.650062
[ "transform" ]