hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c17fb51b9965c2495e4001235648056f36fafc18 | 655 | cpp | C++ | solutions/beecrowd/1281/1281.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 18 | 2015-01-22T04:08:51.000Z | 2022-01-08T22:36:47.000Z | solutions/beecrowd/1281/1281.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 4 | 2016-04-25T12:32:46.000Z | 2021-06-15T18:01:30.000Z | solutions/beecrowd/1281/1281.cpp | deniscostadsc/playground | 11fa8e2b708571940451f005e1f55af0b6e5764a | [
"MIT"
] | 25 | 2015-03-02T06:21:51.000Z | 2021-09-12T20:49:21.000Z | #include <cstdint>
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
int main() {
double price, result;
int32_t n, p, q, quantity;
std::map< std::string, double > prices;
std::string fruit;
std::cin >> n;
while (n--) {
result = 0.0;
prices.clear();
std::cin >> p;
while (p--) {
std::cin >> fruit >> price;
prices[fruit] = price;
}
std::cin >> q;
while (q--) {
std::cin >> fruit >> quantity;
result += prices[fruit] * quantity;
}
printf("R$ %.2lf\n", result);
}
return 0;
}
| 17.236842 | 47 | 0.467176 | deniscostadsc |
c1812d08d9d03987552ec67444543443d73ad5ea | 2,137 | cpp | C++ | C++/cat-and-mouse.cpp | black-shadows/LeetCode-Solutions | b1692583f7b710943ffb19b392b8bf64845b5d7a | [
"Fair",
"Unlicense"
] | 1 | 2020-04-16T08:38:14.000Z | 2020-04-16T08:38:14.000Z | cat-and-mouse.cpp | Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise | f1111b4edd401a3fc47111993bd7250cf4dc76da | [
"MIT"
] | null | null | null | cat-and-mouse.cpp | Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise | f1111b4edd401a3fc47111993bd7250cf4dc76da | [
"MIT"
] | 1 | 2021-12-25T14:48:56.000Z | 2021-12-25T14:48:56.000Z | // Time: O(n^3)
// Space: O(n^2)
class Solution {
private:
template <typename A, typename B, typename C>
struct TupleHash {
size_t operator()(const tuple<A, B, C>& p) const {
size_t seed = 0;
A a; B b; C c;
tie(a, b, c) = p;
seed ^= std::hash<A>{}(a) + 0x9e3779b9 + (seed<<6) + (seed>>2);
seed ^= std::hash<B>{}(b) + 0x9e3779b9 + (seed<<6) + (seed>>2);
seed ^= std::hash<C>{}(c) + 0x9e3779b9 + (seed<<6) + (seed>>2);
return seed;
}
};
using Lookup = unordered_map<tuple<int, int, bool>, int, TupleHash<int, int, bool>>;
public:
int catMouseGame(vector<vector<int>>& graph) {
Lookup lookup;
return move(graph, &lookup, MOUSE_START, CAT_START, true);
}
private:
enum Location {HOLE, MOUSE_START, CAT_START};
enum Result {DRAW, MOUSE, CAT};
int move(const vector<vector<int>>& graph, Lookup *lookup, int i, int other_i, bool is_mouse_turn) {
const auto& key = make_tuple(i, other_i, is_mouse_turn);
if (lookup->count(key)) {
return (*lookup)[key];
}
(*lookup)[key] = DRAW;
int skip, target, win, lose;
if (is_mouse_turn) {
tie(skip, target, win, lose) = make_tuple(other_i, HOLE, MOUSE, CAT);
} else {
tie(skip, target, win, lose) = make_tuple(HOLE, other_i, CAT, MOUSE);
}
for (const auto& nei : graph[i]) {
if (nei == target) {
(*lookup)[key] = win;
return win;
}
}
int result = lose;
for (const auto& nei : graph[i]) {
if (nei == skip) {
continue;
}
auto tmp = move(graph, lookup, other_i, nei, !is_mouse_turn);
if (tmp == win) {
result = win;
break;
}
if (tmp == DRAW) {
result = DRAW;
}
}
(*lookup)[key] = result;
return result;
}
};
| 31.895522 | 105 | 0.463734 | black-shadows |
c181376c76225121a45f8f7bcdb424de4fa33935 | 27,425 | cc | C++ | mindspore/ccsrc/minddata/dataset/engine/cache/cache_server.cc | huxian123/mindspore | ec5ba10c82bbd6eccafe32d3a1149add90105bc8 | [
"Apache-2.0"
] | 2 | 2021-04-22T07:00:59.000Z | 2021-11-08T02:49:09.000Z | mindspore/ccsrc/minddata/dataset/engine/cache/cache_server.cc | nudt-eddie/mindspore | 55372b41fdfae6d2b88d7078971e06d537f6c558 | [
"Apache-2.0"
] | 1 | 2020-12-29T06:46:38.000Z | 2020-12-29T06:46:38.000Z | mindspore/ccsrc/minddata/dataset/engine/cache/cache_server.cc | nudt-eddie/mindspore | 55372b41fdfae6d2b88d7078971e06d537f6c558 | [
"Apache-2.0"
] | 1 | 2021-05-10T03:30:36.000Z | 2021-05-10T03:30:36.000Z | /**
* Copyright 2020 Huawei Technologies Co., Ltd
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "minddata/dataset/engine/cache/cache_server.h"
#include <algorithm>
#include <functional>
#include <limits>
#include "minddata/dataset/core/constants.h"
#include "minddata/dataset/engine/cache/cache_service.h"
#include "minddata/dataset/engine/cache/cache_request.h"
#include "minddata/dataset/util/bit.h"
#include "minddata/dataset/util/path.h"
#include "minddata/dataset/util/random.h"
#ifdef CACHE_LOCAL_CLIENT
#include "minddata/dataset/util/sig_handler.h"
#endif
namespace mindspore {
namespace dataset {
CacheServer *CacheServer::instance_ = nullptr;
std::once_flag CacheServer::init_instance_flag_;
Status CacheServer::DoServiceStart() {
#ifdef CACHE_LOCAL_CLIENT
// We need to destroy the shared memory if user hits Control-C
RegisterHandlers();
#endif
if (!top_.empty()) {
Path spill(top_);
RETURN_IF_NOT_OK(spill.CreateDirectories());
MS_LOG(INFO) << "CacheServer will use disk folder: " << top_;
}
RETURN_IF_NOT_OK(vg_.ServiceStart());
// There will be num_workers_ threads working on the grpc queue and
// the same number of threads working on the CacheServerRequest queue.
// Like a connector object we will set up the same number of queues but
// we do not need to preserve any order. We will set the capacity of
// each queue to be 128 since we are just pushing memory pointers which
// is only 8 byte each.
const int32_t que_capacity = 128;
// This is the request queue from the client
cache_q_ = std::make_shared<QueueList<CacheServerRequest *>>();
cache_q_->Init(num_workers_, que_capacity);
// For the grpc completion queue to work, we need to allocate some
// tags which in our case are instances of CacheServerQuest.
// They got recycled and we will allocate them in advance and push
// them into some free list. We need more (two or three times) the
// size of the cache_q. While each worker is working on a CacheSerRequest,
// we need some extra running injecting in the the qrpc completion queue.
const int32_t multiplier = 3;
const int32_t free_list_capacity = multiplier * (que_capacity + 1);
free_list_ = std::make_shared<QueueList<CacheServerRequest *>>();
free_list_->Init(num_workers_, free_list_capacity);
// We need to have a reference to the services memory pool in case
// the Services goes out of scope earlier than us since it is a singleton
mp_ = Services::GetInstance().GetServiceMemPool();
Allocator<CacheServerRequest> alloc(mp_);
tag_.reserve(num_workers_);
// Now we populate all free list.
for (auto m = 0; m < num_workers_; ++m) {
// Ideally we allocate all the free list in one malloc. But it turns out it exceeds the
// Arena size. So we will we will allocate one segment at a time.
auto my_tag = std::make_unique<MemGuard<CacheServerRequest, Allocator<CacheServerRequest>>>(alloc);
// Allocate the tag and assign it the current queue
RETURN_IF_NOT_OK(my_tag->allocate(free_list_capacity, m));
for (int i = 0; i < free_list_capacity; ++i) {
RETURN_IF_NOT_OK(free_list_->operator[](m)->Add((*my_tag)[i]));
}
tag_.push_back(std::move(my_tag));
}
RETURN_IF_NOT_OK(cache_q_->Register(&vg_));
RETURN_IF_NOT_OK(free_list_->Register(&vg_));
// Spawn a few threads to serve the real request.
auto f = std::bind(&CacheServer::ServerRequest, this, std::placeholders::_1);
for (auto i = 0; i < num_workers_; ++i) {
RETURN_IF_NOT_OK(vg_.CreateAsyncTask("Cache service worker", std::bind(f, i)));
}
// Start the comm layer
try {
comm_layer_ = std::make_shared<CacheServerGreeterImpl>(port_, shared_memory_sz_in_gb_);
RETURN_IF_NOT_OK(comm_layer_->Run());
} catch (const std::exception &e) {
RETURN_STATUS_UNEXPECTED(e.what());
}
// Finally loop forever to handle the request.
auto r = std::bind(&CacheServer::RpcRequest, this, std::placeholders::_1);
for (auto i = 0; i < num_workers_; ++i) {
RETURN_IF_NOT_OK(vg_.CreateAsyncTask("rpc worker", std::bind(r, i)));
}
return Status::OK();
}
Status CacheServer::DoServiceStop() {
Status rc;
Status rc2;
// First stop all the threads.
RETURN_IF_NOT_OK(vg_.ServiceStop());
// Clean up all the caches if any.
UniqueLock lck(&rwLock_);
auto it = all_caches_.begin();
while (it != all_caches_.end()) {
auto cs = std::move(it->second);
rc2 = cs->ServiceStop();
if (rc2.IsError()) {
rc = rc2;
}
++it;
}
return rc;
}
CacheService *CacheServer::GetService(connection_id_type id) const {
SharedLock lck(&rwLock_);
auto it = all_caches_.find(id);
if (it != all_caches_.end()) {
return it->second.get();
}
return nullptr;
}
Status CacheServer::CreateService(CacheRequest *rq, CacheReply *reply) {
CHECK_FAIL_RETURN_UNEXPECTED(rq->has_connection_info(), "Missing connection info");
std::string cookie;
auto session_id = rq->connection_info().session_id();
auto crc = rq->connection_info().crc();
// We concat both numbers to form the internal connection id.
auto connection_id = GetConnectionID(session_id, crc);
CHECK_FAIL_RETURN_UNEXPECTED(!rq->buf_data().empty(), "Missing info to create cache");
auto &create_cache_buf = rq->buf_data(0);
auto p = flatbuffers::GetRoot<CreateCacheRequestMsg>(create_cache_buf.data());
auto flag = static_cast<CreateCacheRequest::CreateCacheFlag>(p->flag());
auto cache_mem_sz = p->cache_mem_sz();
// We can't do spilling unless this server is setup with a spill path in the first place
bool spill =
(flag & CreateCacheRequest::CreateCacheFlag::kSpillToDisk) == CreateCacheRequest::CreateCacheFlag::kSpillToDisk;
bool generate_id =
(flag & CreateCacheRequest::CreateCacheFlag::kGenerateRowId) == CreateCacheRequest::CreateCacheFlag::kGenerateRowId;
if (spill && top_.empty()) {
RETURN_STATUS_UNEXPECTED("Server is not set up with spill support.");
}
flatbuffers::FlatBufferBuilder fbb;
flatbuffers::Offset<flatbuffers::String> off_cookie;
// Before creating the cache, first check if this is a request for a shared usage of an existing cache
// If two CreateService come in with identical connection_id, we need to serialize the create.
// The first create will be successful and be given a special cookie.
UniqueLock lck(&rwLock_);
// Early exit if we are doing global shutdown
if (global_shutdown_) {
return Status::OK();
}
auto end = all_caches_.end();
auto it = all_caches_.find(connection_id);
bool duplicate = false;
if (it == end) {
std::unique_ptr<CacheService> cs;
try {
cs = std::make_unique<CacheService>(cache_mem_sz, spill ? top_ : "", generate_id);
RETURN_IF_NOT_OK(cs->ServiceStart());
cookie = cs->cookie();
all_caches_.emplace(connection_id, std::move(cs));
} catch (const std::bad_alloc &e) {
return Status(StatusCode::kOutOfMemory);
}
} else {
duplicate = true;
MS_LOG(INFO) << "Duplicate request for " + std::to_string(connection_id) + " to create cache service";
}
off_cookie = fbb.CreateString(cookie);
CreateCacheReplyMsgBuilder bld(fbb);
bld.add_connection_id(connection_id);
bld.add_cookie(off_cookie);
auto off = bld.Finish();
fbb.Finish(off);
reply->set_result(fbb.GetBufferPointer(), fbb.GetSize());
// Track the history of all the sessions that we have created so far.
history_sessions_.insert(session_id);
// We can return OK but we will return a duplicate key so user can act accordingly to either ignore it
// treat it as OK.
return duplicate ? Status(StatusCode::kDuplicateKey) : Status::OK();
}
Status CacheServer::DestroyCache(CacheService *cs, CacheRequest *rq) {
// We need a strong lock to protect the map.
UniqueLock lck(&rwLock_);
// it is already destroyed. Ignore it.
if (cs != nullptr) {
auto id = rq->connection_id();
MS_LOG(WARNING) << "Dropping cache with connection id " << std::to_string(id);
// std::map will invoke the destructor of CacheService. So we don't need to do anything here.
auto n = all_caches_.erase(id);
if (n == 0) {
// It has been destroyed by another duplicate request.
MS_LOG(INFO) << "Duplicate request for " + std::to_string(id) + " to create cache service";
}
}
return Status::OK();
}
inline Status CacheRow(CacheService *cs, CacheRequest *rq, CacheReply *reply) {
auto connection_id = rq->connection_id();
if (cs == nullptr) {
std::string errMsg = "Cache id " + std::to_string(connection_id) + " not found";
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
} else {
auto sz = rq->buf_data_size();
std::vector<const void *> buffers;
buffers.reserve(sz);
// First piece of data is the cookie and is required
CHECK_FAIL_RETURN_UNEXPECTED(!rq->buf_data().empty(), "Missing cookie");
auto &cookie = rq->buf_data(0);
// Only if the cookie matches, we can accept insert into this cache that has a build phase
if (!cs->HasBuildPhase() || cookie == cs->cookie()) {
// Push the address of each buffer (in the form of std::string coming in from protobuf) into
// a vector of buffer
for (auto i = 1; i < sz; ++i) {
buffers.push_back(rq->buf_data(i).data());
}
row_id_type id = -1;
RETURN_IF_NOT_OK(cs->CacheRow(buffers, &id));
reply->set_result(std::to_string(id));
} else {
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Cookie mismatch");
}
}
return Status::OK();
}
Status CacheServer::FastCacheRow(CacheService *cs, CacheRequest *rq, CacheReply *reply) {
auto connection_id = rq->connection_id();
auto shared_pool = comm_layer_->GetSharedMemoryPool();
auto *base = shared_pool->SharedMemoryBaseAddr();
// Ensure we got 3 pieces of data coming in
CHECK_FAIL_RETURN_UNEXPECTED(rq->buf_data_size() == 3, "Incomplete data");
// First piece of data is the cookie and is required
auto &cookie = rq->buf_data(0);
// Second piece of data is the address where we can find the serialized data
auto addr = strtoll(rq->buf_data(1).data(), nullptr, 10);
auto p = reinterpret_cast<void *>(reinterpret_cast<int64_t>(base) + addr);
// Third piece of data is the size of the serialized data that we need to transfer
auto sz = strtoll(rq->buf_data(2).data(), nullptr, 10);
// Successful or not, we need to free the memory on exit.
Status rc;
if (cs == nullptr) {
std::string errMsg = "Cache id " + std::to_string(connection_id) + " not found";
rc = Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
} else {
// Only if the cookie matches, we can accept insert into this cache that has a build phase
if (!cs->HasBuildPhase() || cookie == cs->cookie()) {
row_id_type id = -1;
ReadableSlice src(p, sz);
rc = cs->FastCacheRow(src, &id);
reply->set_result(std::to_string(id));
} else {
rc = Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Cookie mismatch");
}
}
// Return the block to the shared memory.
shared_pool->Deallocate(p);
return rc;
}
Status CacheServer::BatchFetchRows(CacheService *cs, CacheRequest *rq, CacheReply *reply) {
auto connection_id = rq->connection_id();
if (cs == nullptr) {
std::string errMsg = "Cache id " + std::to_string(connection_id) + " not found";
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
} else {
CHECK_FAIL_RETURN_UNEXPECTED(!rq->buf_data().empty(), "Missing row id");
auto &row_id_buf = rq->buf_data(0);
auto p = flatbuffers::GetRoot<TensorRowIds>(row_id_buf.data());
std::vector<row_id_type> row_id;
auto sz = p->row_id()->size();
row_id.reserve(sz);
for (auto i = 0; i < sz; ++i) {
row_id.push_back(p->row_id()->Get(i));
}
int64_t mem_sz = 0;
std::vector<key_size_pair> v;
RETURN_IF_NOT_OK(cs->PreBatchFetch(row_id, &v, &mem_sz));
auto client_flag = rq->flag();
bool local_client = BitTest(client_flag, kLocalClientSupport);
// For large amount data to be sent back, we will use shared memory provided it is a local
// client that has local bypass support
bool local_bypass = local_client ? (mem_sz >= kLocalByPassThreshold) : false;
reply->set_flag(local_bypass ? kDataIsInSharedMemory : 0);
if (local_bypass) {
// We will use shared memory
auto shared_pool = comm_layer_->GetSharedMemoryPool();
auto *base = shared_pool->SharedMemoryBaseAddr();
void *q = nullptr;
RETURN_IF_NOT_OK(shared_pool->Allocate(mem_sz, &q));
WritableSlice dest(q, mem_sz);
RETURN_IF_NOT_OK(cs->BatchFetch(row_id, v, &dest));
// We can't return the absolute address which makes no sense to the client.
// Instead we return the difference.
auto difference = reinterpret_cast<int64_t>(q) - reinterpret_cast<int64_t>(base);
reply->set_result(std::to_string(difference));
} else {
// We are going to use std::string to allocate and hold the result which will be eventually
// 'moved' to the protobuf message (which underneath is also a std::string) for the purpose
// to minimize memory copy.
std::string mem;
try {
mem.resize(mem_sz);
CHECK_FAIL_RETURN_UNEXPECTED(mem.capacity() >= mem_sz, "Programming error");
} catch (const std::bad_alloc &e) {
return Status(StatusCode::kOutOfMemory);
}
WritableSlice dest(mem.data(), mem_sz);
RETURN_IF_NOT_OK(cs->BatchFetch(row_id, v, &dest));
reply->set_result(std::move(mem));
}
}
return Status::OK();
}
inline Status GetStat(CacheService *cs, CacheRequest *rq, CacheReply *reply) {
auto connection_id = rq->connection_id();
if (cs == nullptr) {
std::string errMsg = "Connection " + std::to_string(connection_id) + " not found";
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
} else {
CacheService::ServiceStat svc_stat;
RETURN_IF_NOT_OK(cs->GetStat(&svc_stat));
flatbuffers::FlatBufferBuilder fbb;
ServiceStatMsgBuilder bld(fbb);
bld.add_num_disk_cached(svc_stat.stat_.num_disk_cached);
bld.add_num_mem_cached(svc_stat.stat_.num_mem_cached);
bld.add_avg_cache_sz(svc_stat.stat_.average_cache_sz);
bld.add_max_row_id(svc_stat.max_);
bld.add_min_row_id(svc_stat.min_);
bld.add_state(svc_stat.state_);
auto offset = bld.Finish();
fbb.Finish(offset);
reply->set_result(fbb.GetBufferPointer(), fbb.GetSize());
}
return Status::OK();
}
inline Status CacheSchema(CacheService *cs, CacheRequest *rq) {
auto connection_id = rq->connection_id();
if (cs == nullptr) {
std::string errMsg = "Connection " + std::to_string(connection_id) + " not found";
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
} else {
CHECK_FAIL_RETURN_UNEXPECTED(!rq->buf_data().empty(), "Missing schema information");
auto &create_schema_buf = rq->buf_data(0);
RETURN_IF_NOT_OK(cs->CacheSchema(create_schema_buf.data(), create_schema_buf.size()));
}
return Status::OK();
}
inline Status FetchSchema(CacheService *cs, CacheRequest *rq, CacheReply *reply) {
auto connection_id = rq->connection_id();
if (cs == nullptr) {
std::string errMsg = "Connection " + std::to_string(connection_id) + " not found";
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
} else {
// We are going to use std::string to allocate and hold the result which will be eventually
// 'moved' to the protobuf message (which underneath is also a std::string) for the purpose
// to minimize memory copy.
std::string mem;
RETURN_IF_NOT_OK(cs->FetchSchema(&mem));
reply->set_result(std::move(mem));
}
return Status::OK();
}
inline Status BuildPhaseDone(CacheService *cs, CacheRequest *rq) {
auto connection_id = rq->connection_id();
if (cs == nullptr) {
std::string errMsg = "Connection " + std::to_string(connection_id) + " not found";
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
} else {
// First piece of data is the cookie
CHECK_FAIL_RETURN_UNEXPECTED(!rq->buf_data().empty(), "Missing cookie");
auto &cookie = rq->buf_data(0);
// We can only allow to switch phase is the cookie match.
if (cookie == cs->cookie()) {
RETURN_IF_NOT_OK(cs->BuildPhaseDone());
} else {
return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Cookie mismatch");
}
}
return Status::OK();
}
Status CacheServer::PurgeCache(CacheService *cs) {
SharedLock lck(&rwLock_);
// If shutdown in progress, ignore the command.
if (global_shutdown_) {
return Status::OK();
}
// it is already purged. Ignore it.
if (cs != nullptr) {
RETURN_IF_NOT_OK(cs->Purge());
}
return Status::OK();
}
inline Status GenerateClientSessionID(session_id_type session_id, CacheReply *reply) {
reply->set_result(std::to_string(session_id));
return Status::OK();
}
/// \brief This is the main loop the cache server thread(s) are running.
/// Each thread will pop a request and send the result back to the client using grpc
/// \return
Status CacheServer::ServerRequest(int32_t worker_id) {
TaskManager::FindMe()->Post();
auto &my_que = cache_q_->operator[](worker_id);
// Loop forever until we are interrupted or shutdown.
while (!global_shutdown_) {
CacheServerRequest *cache_req = nullptr;
RETURN_IF_NOT_OK(my_que->PopFront(&cache_req));
auto &rq = cache_req->rq_;
auto &reply = cache_req->reply_;
CacheService *cs = nullptr;
// Request comes in roughly two sets. One set is at the cache level with a connection id.
// The other set is working at a high level and without a connection id
if (!rq.has_connection_info()) {
cs = GetService(rq.connection_id());
}
// Except for creating a new session, we expect cs is not null.
switch (cache_req->type_) {
case BaseRequest::RequestType::kCacheRow: {
// Look into the flag to see where we can find the data and
// call the appropriate method.
auto flag = rq.flag();
if (BitTest(flag, kDataIsInSharedMemory)) {
cache_req->rc_ = FastCacheRow(cs, &rq, &reply);
} else {
cache_req->rc_ = CacheRow(cs, &rq, &reply);
}
break;
}
case BaseRequest::RequestType::kBatchFetchRows: {
cache_req->rc_ = BatchFetchRows(cs, &rq, &reply);
break;
}
case BaseRequest::RequestType::kCreateCache: {
cache_req->rc_ = CreateService(&rq, &reply);
break;
}
case BaseRequest::RequestType::kPurgeCache: {
cache_req->rc_ = PurgeCache(cs);
break;
}
case BaseRequest::RequestType::kDestroyCache: {
cache_req->rc_ = DestroyCache(cs, &rq);
break;
}
case BaseRequest::RequestType::kGetStat: {
cache_req->rc_ = GetStat(cs, &rq, &reply);
break;
}
case BaseRequest::RequestType::kCacheSchema: {
cache_req->rc_ = CacheSchema(cs, &rq);
break;
}
case BaseRequest::RequestType::kFetchSchema: {
cache_req->rc_ = FetchSchema(cs, &rq, &reply);
break;
}
case BaseRequest::RequestType::kBuildPhaseDone: {
cache_req->rc_ = BuildPhaseDone(cs, &rq);
break;
}
case BaseRequest::RequestType::kDropSession: {
cache_req->rc_ = DestroySession(&rq);
break;
}
case BaseRequest::RequestType::kGenerateSessionId: {
cache_req->rc_ = GenerateClientSessionID(GenerateSessionID(), &reply);
break;
}
case BaseRequest::RequestType::kAllocateSharedBlock: {
cache_req->rc_ = AllocateSharedMemory(&rq, &reply);
break;
}
case BaseRequest::RequestType::kFreeSharedBlock: {
cache_req->rc_ = FreeSharedMemory(&rq);
break;
}
case BaseRequest::RequestType::kStopService: {
// This command shutdowns everything.
cache_req->rc_ = GlobalShutdown();
break;
}
default:
std::string errMsg("Unknown request type : ");
errMsg += std::to_string(static_cast<uint16_t>(cache_req->type_));
cache_req->rc_ = Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, errMsg);
}
// Notify it is done, and move on to the next request.
Status2CacheReply(cache_req->rc_, &reply);
cache_req->st_ = CacheServerRequest::STATE::FINISH;
// We will re-tag the request back to the grpc queue. Once it comes back from the client,
// the CacheServerRequest, i.e. the pointer cache_req, will be free
if (!global_shutdown_) {
cache_req->responder_.Finish(reply, grpc::Status::OK, cache_req);
}
}
return Status::OK();
}
connection_id_type CacheServer::GetConnectionID(session_id_type session_id, uint32_t crc) const {
connection_id_type connection_id =
(static_cast<connection_id_type>(session_id) << 32u) | static_cast<connection_id_type>(crc);
return connection_id;
}
session_id_type CacheServer::GetSessionID(connection_id_type connection_id) const {
return static_cast<session_id_type>(connection_id >> 32u);
}
CacheServer::CacheServer(const std::string &spill_path, int32_t num_workers, int32_t port,
int32_t shared_meory_sz_in_gb)
: top_(spill_path),
num_workers_(num_workers),
port_(port),
shared_memory_sz_in_gb_(shared_meory_sz_in_gb),
global_shutdown_(false) {}
Status CacheServer::Run() {
RETURN_IF_NOT_OK(ServiceStart());
// This is called by the main function and we shouldn't exit. Otherwise the main thread
// will just shutdown. So we will call some function that never return unless error.
// One good case will be simply to wait for all threads to return.
RETURN_IF_NOT_OK(vg_.join_all(Task::WaitFlag::kBlocking));
return Status::OK();
}
Status CacheServer::GetFreeRequestTag(int32_t queue_id, CacheServerRequest **q) {
RETURN_UNEXPECTED_IF_NULL(q);
CacheServer &cs = CacheServer::GetInstance();
CacheServerRequest *p;
RETURN_IF_NOT_OK(cs.free_list_->operator[](queue_id)->PopFront(&p));
*q = p;
return Status::OK();
}
Status CacheServer::ReturnRequestTag(CacheServerRequest *p) {
RETURN_UNEXPECTED_IF_NULL(p);
int32_t myQID = p->getQid();
// Free any memory from the protobufs
p->~CacheServerRequest();
// Re-initialize the memory
new (p) CacheServerRequest(myQID);
// Now we return it back to free list.
CacheServer &cs = CacheServer::GetInstance();
RETURN_IF_NOT_OK(cs.free_list_->operator[](myQID)->Add(p));
return Status::OK();
}
Status CacheServer::DestroySession(CacheRequest *rq) {
CHECK_FAIL_RETURN_UNEXPECTED(rq->has_connection_info(), "Missing session id");
auto drop_session_id = rq->connection_info().session_id();
UniqueLock lck(&rwLock_);
for (auto &cs : all_caches_) {
auto connection_id = cs.first;
auto session_id = GetSessionID(connection_id);
// We can just call DestroyCache() but we are holding a lock already. Doing so will cause deadlock.
// So we will just manually do it.
if (session_id == drop_session_id) {
// std::map will invoke the destructor of CacheService. So we don't need to do anything here.
auto n = all_caches_.erase(connection_id);
MS_LOG(INFO) << "Destroy " << n << " copies of cache with id " << connection_id;
}
}
return Status::OK();
}
session_id_type CacheServer::GenerateSessionID() const {
SharedLock lock(&rwLock_);
auto mt = GetRandomDevice();
std::uniform_int_distribution<session_id_type> distribution(0, std::numeric_limits<session_id_type>::max());
session_id_type session_id;
bool duplicate = false;
do {
session_id = distribution(mt);
auto it = history_sessions_.find(session_id);
duplicate = (it != history_sessions_.end());
} while (duplicate);
return session_id;
}
Status CacheServer::AllocateSharedMemory(CacheRequest *rq, CacheReply *reply) {
auto requestedSz = strtoll(rq->buf_data(0).data(), nullptr, 10);
auto shared_pool = comm_layer_->GetSharedMemoryPool();
auto *base = shared_pool->SharedMemoryBaseAddr();
void *p = nullptr;
RETURN_IF_NOT_OK(shared_pool->Allocate(requestedSz, &p));
// We can't return the absolute address which makes no sense to the client.
// Instead we return the difference.
auto difference = reinterpret_cast<int64_t>(p) - reinterpret_cast<int64_t>(base);
reply->set_result(std::to_string(difference));
return Status::OK();
}
Status CacheServer::FreeSharedMemory(CacheRequest *rq) {
auto shared_pool = comm_layer_->GetSharedMemoryPool();
auto *base = shared_pool->SharedMemoryBaseAddr();
auto addr = strtoll(rq->buf_data(0).data(), nullptr, 10);
auto p = reinterpret_cast<void *>(reinterpret_cast<int64_t>(base) + addr);
shared_pool->Deallocate(p);
return Status::OK();
}
Status CacheServer::RpcRequest(int32_t worker_id) {
TaskManager::FindMe()->Post();
RETURN_IF_NOT_OK(comm_layer_->HandleRequest(worker_id));
return Status::OK();
}
Status CacheServer::GlobalShutdown() {
// Let's shutdown in proper order.
bool expected = false;
if (global_shutdown_.compare_exchange_strong(expected, true)) {
MS_LOG(WARNING) << "Shutting down server.";
// Shutdown the grpc queue. No longer accept any new comer.
// The threads we spawn to work on the grpc queue will exit themselves once
// they notice the queue has been shutdown.
comm_layer_->Shutdown();
// Now we interrupt any threads that are waiting on cache_q_
vg_.interrupt_all();
// The next thing to do drop all the caches.
UniqueLock lck(&rwLock_);
for (auto &it : all_caches_) {
auto id = it.first;
MS_LOG(WARNING) << "Dropping cache with connection id " << std::to_string(id);
// Wait for all outstanding work to be finished.
auto &cs = it.second;
UniqueLock cs_lock(&cs->rw_lock_);
// std::map will invoke the destructor of CacheService. So we don't need to do anything here.
(void)all_caches_.erase(id);
}
}
return Status::OK();
}
Status CacheServer::Builder::SanityCheck() {
if (shared_memory_sz_in_gb_ <= 0) {
RETURN_STATUS_UNEXPECTED("Shared memory size (in GB unit) must be positive");
}
if (num_workers_ <= 0) {
RETURN_STATUS_UNEXPECTED("Number of parallel workers must be positive");
}
if (!top_.empty()) {
auto p = top_.data();
if (p[0] != '/') {
RETURN_STATUS_UNEXPECTED("Spilling directory must be an absolute path");
}
// Check if the spill directory is writable
Path spill(top_);
auto t = spill / Services::GetUniqueID();
Status rc = t.CreateDirectory();
if (rc.IsOk()) {
rc = t.Remove();
}
if (rc.IsError()) {
RETURN_STATUS_UNEXPECTED("Spilling directory is not writable\n" + rc.ToString());
}
}
return Status::OK();
}
} // namespace dataset
} // namespace mindspore
| 40.330882 | 120 | 0.691778 | huxian123 |
c182280f9209c80a121f69cdabff864bdffb567e | 8,923 | cpp | C++ | utils/geo/demo1.cpp | AuraUAS/aura-core | 4711521074db72ba9089213e14455d89dc5306c0 | [
"MIT",
"BSD-2-Clause-FreeBSD"
] | 8 | 2016-08-03T19:35:03.000Z | 2019-12-15T06:25:05.000Z | utils/geo/demo1.cpp | jarilq/aura-core | 7880ed265396bf8c89b783835853328e6d7d1589 | [
"MIT",
"BSD-2-Clause-FreeBSD"
] | 4 | 2018-09-27T15:48:56.000Z | 2018-11-05T12:38:10.000Z | utils/geo/demo1.cpp | jarilq/aura-core | 7880ed265396bf8c89b783835853328e6d7d1589 | [
"MIT",
"BSD-2-Clause-FreeBSD"
] | 5 | 2017-06-28T19:15:36.000Z | 2020-02-19T19:31:24.000Z | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "math/SGMath.hxx"
void print_vec3( const char *pref, SGVec3d v ) {
printf("%s %.3f %.3f %.3f\n", pref, v[0], v[1], v[2]);
}
SGQuatd compute_ned2body( double roll_deg, double pitch_deg, double yaw_deg ) {
double yaw_rad = yaw_deg * SGD_DEGREES_TO_RADIANS;
double pitch_rad = pitch_deg * SGD_DEGREES_TO_RADIANS;
double roll_rad = roll_deg * SGD_DEGREES_TO_RADIANS;
SGQuatd ned2body
= SGQuatd::fromYawPitchRoll( yaw_rad, pitch_rad, roll_rad );
return ned2body;
}
// compute diagonal field of view of the camera
static double compute_diag_fov( double h_mm, double v_mm, double focal_len_mm )
{
double diag_mm = sqrt(h_mm*h_mm + v_mm*v_mm);
//printf("hmm=%.2f vmm=%.2f dmm=%.2f\n", h_mm, v_mm, diag_mm);
//double hfov = 2.0 * atan( h_mm / (2.0*focal_len_mm) );
//double vfov = 2.0 * atan( v_mm / (2.0*focal_len_mm) );
double dfov = 2.0 * atan( diag_mm / (2.0*focal_len_mm) );
/*printf("hfov=%.2f vfov=%.2f dfov=%.2f\n",
hfov * SGD_RADIANS_TO_DEGREES,
vfov * SGD_RADIANS_TO_DEGREES,
dfov * SGD_RADIANS_TO_DEGREES);*/
return dfov;
}
// compute a base unit vector representing the 'look down' ned give a
// 'half' camera diagonal and the angle to sweep it. Gives us the
// ability to compute a ned vector for the corner of the camera image.
static SGVec3d compute_base_ned_vector( double half_diag, double rotation ) {
SGVec3d vec;
vec.z() = cos( half_diag );
double hdist = sin( half_diag );
vec.x() = cos( rotation ) * hdist;
vec.y() = sin( rotation ) * hdist;
return vec;
}
// Compute lookat NED vector from camera angles and body attitude.
static SGVec3d ned_from_camera_angles1( double pan_deg, double tilt_deg,
SGQuatd ned2body )
{
SGVec3d dir_body;
double pan_rad = pan_deg * SGD_DEGREES_TO_RADIANS;
double tilt_rad = tilt_deg * SGD_DEGREES_TO_RADIANS;
dir_body.z() = sin( tilt_rad );
double hdist = cos( tilt_rad );
dir_body.x() = cos( pan_rad ) * hdist;
dir_body.y() = sin( pan_rad ) * hdist;
SGVec3d dir_ned = ned2body.backTransform(dir_body);
return dir_ned;
}
// Estimate wgs84 target point from current ned lookat vector.
// (Estimate is based on current lookat ground altitude which needs to
// be updated regularly from external source for best accuracy.)
static SGGeod wgs84_from_ned( double ground_elev_m,
SGGeod pos_geod,
SGVec3d dir_ned )
{
double agl_m = pos_geod.getElevationM() - ground_elev_m;
//printf("agl_m = %.2f\n", agl_m);
double a = atan2(dir_ned.x(), dir_ned.y());
double proj_deg = (M_PI/2.0 - a) * SGD_RADIANS_TO_DEGREES;
//printf("proj_deg = %.8f\n", proj_deg);
double d_factor = sqrt( dir_ned.x()*dir_ned.x() + dir_ned.y()*dir_ned.y() );
//printf("d_factor = %.2f\n", d_factor);
double proj_dist = 0.0;
if ( dir_ned.z() > 0.0 ) {
proj_dist = (agl_m / dir_ned.z()) * d_factor;
// sanity check: don't look more than 100km beyond
// current location and don't look backwards
if ( proj_dist < 0.0 ) {
proj_dist = 0.0;
}
if ( proj_dist > 100000.0 ) {
proj_dist = 100000.0;
}
} else {
// if lookat vector is at or above the horizon, put
// the wgs84 point just below the horizon
proj_dist = 100000.0;
}
SGGeod ground_geod = pos_geod;
ground_geod.setElevationM( ground_elev_m );
SGGeod new_target;
double final_course;
SGGeodesy::direct( ground_geod, proj_deg, proj_dist,
new_target, final_course);
new_target.setElevationM( ground_elev_m );
return new_target;
}
SGVec3d offset_from_reference( SGGeod p, SGGeod ref ) {
SGVec3d result;
double course1, course2, dist;
SGGeodesy::inverse( ref, p, course1, course2, dist );
//printf("c1 = %.2f c2 = %.2f dist = %.2f\n", course1, course2, dist);
double angle = course1 * SGD_DEGREES_TO_RADIANS;
double x = sin(angle) * dist;
double y = cos(angle) * dist;
//printf(" x=%.2f y=%.2f\n", x, y);
result[0] = x;
result[1] = y;
result[2] = p.getElevationM() - ref.getElevationM();
return result;
}
void usage( char *prog ) {
printf("%s lon_deg lat_deg alt_m ground_alt_m roll_deg pitch_deg yaw_deg h_mm v_mm focal_len_mm ref_lat, ref_lon\n", prog);
printf("Samsung NX210 h_mm=23.5 v_mm=15.7 focal_len_mm=30.0\n");
exit(-1);
}
double h_mm = 23.5;
double v_mm = 15.7;
double focal_len_mm = 30.0;
int main( int argc, char **argv ) {
if ( argc != 13 ) {
usage( argv[0] );
}
double lon_deg = atof(argv[1]);
double lat_deg = atof(argv[2]);
double alt_m = atof(argv[3]);
double ground_m = atof(argv[4]);
double roll_deg = atof(argv[5]);
double pitch_deg = atof(argv[6]);
double yaw_deg = atof(argv[7]);
double h_mm = atof(argv[8]);
double v_mm = atof(argv[9]);
double focal_len_mm = atof(argv[10]);
double ref_lon_deg = atof(argv[11]);
double ref_lat_deg = atof(argv[12]);
// Samsung NX210
// h_mm = 23.5;
// v_mm = 15.7;
//double focal_len_mm = 30.0;
// compute camera parameters
double diag_fov = compute_diag_fov( h_mm, v_mm, focal_len_mm );
double half_diag_fov = 0.5 * diag_fov;
double diag_angle = atan2(v_mm, h_mm);
//printf("diag_fov = %.2f\n", diag_fov * SGD_RADIANS_TO_DEGREES);
//printf("diag_angle = %.2f\n", diag_angle * SGD_RADIANS_TO_DEGREES);
// aircraft position (as a geod)
SGGeod pos_geod = SGGeod::fromDegM( lon_deg, lat_deg, alt_m );
// aircraft orientation (as a quaternion)
SGQuatd ned2body = compute_ned2body( roll_deg, pitch_deg, yaw_deg );
// reference position (as a geod)
SGGeod ref_geod = SGGeod::fromDegM( ref_lon_deg, ref_lat_deg, ground_m );
SGVec3d vec;
vec = compute_base_ned_vector( 0.0, 0.0 );
SGVec3d lookat_ned = ned2body.backTransform(vec);
SGGeod lookat_wgs84 = wgs84_from_ned( ground_m, pos_geod, lookat_ned );
SGVec3d lookat_pos = offset_from_reference( lookat_wgs84, ref_geod );
// ll = lower left, ur = upper right, etc.
vec = compute_base_ned_vector( half_diag_fov, -SGD_PI_2 - diag_angle );
SGVec3d ll_ned = ned2body.backTransform(vec);
SGGeod ll_wgs84 = wgs84_from_ned( ground_m, pos_geod, ll_ned );
SGVec3d ll_pos = offset_from_reference( ll_wgs84, ref_geod );
vec = compute_base_ned_vector( half_diag_fov, SGD_PI_2 + diag_angle );
SGVec3d lr_ned = ned2body.backTransform(vec);
SGGeod lr_wgs84 = wgs84_from_ned( ground_m, pos_geod, lr_ned );
SGVec3d lr_pos = offset_from_reference( lr_wgs84, ref_geod );
vec = compute_base_ned_vector( half_diag_fov, SGD_PI_2 - diag_angle );
SGVec3d ur_ned = ned2body.backTransform(vec);
SGGeod ur_wgs84 = wgs84_from_ned( ground_m, pos_geod, ur_ned );
SGVec3d ur_pos = offset_from_reference( ur_wgs84, ref_geod );
vec = compute_base_ned_vector( half_diag_fov, -SGD_PI_2 + diag_angle );
SGVec3d ul_ned = ned2body.backTransform(vec);
SGGeod ul_wgs84 = wgs84_from_ned( ground_m, pos_geod, ul_ned );
SGVec3d ul_pos = offset_from_reference( ul_wgs84, ref_geod );
print_vec3("lookat:", lookat_pos);
print_vec3("lower-left:", ll_pos);
print_vec3("lower-right:", lr_pos);
print_vec3("upper-right:", ur_pos);
print_vec3("upper-left:", ul_pos);
/*
printf("lookat: %.10f %.10f %.3f\n",
lookat_wgs84.getLongitudeDeg(),
lookat_wgs84.getLatitudeDeg(),
lookat_wgs84.getElevationM());
printf("lowerleft: %.10f %.10f %.3f\n",
ll_wgs84.getLongitudeDeg(),
ll_wgs84.getLatitudeDeg(),
ll_wgs84.getElevationM());
printf("lowerright: %.10f %.10f %.3f\n",
lr_wgs84.getLongitudeDeg(),
lr_wgs84.getLatitudeDeg(),
lr_wgs84.getElevationM());
printf("upperright: %.10f %.10f %.3f\n",
ur_wgs84.getLongitudeDeg(),
ur_wgs84.getLatitudeDeg(),
ur_wgs84.getElevationM());
printf("upperleft: %.10f %.10f %.3f\n",
ul_wgs84.getLongitudeDeg(),
ul_wgs84.getLatitudeDeg(),
ul_wgs84.getElevationM());
*/
// attempt a google map leech
double clat = 45.347222;
double clon = -93.498523;
double lat_spn = 0.006492 * 0.5;
double lon_spn = 0.013937 * 0.5;
ll_wgs84 = SGGeod::fromDegM( clon-lon_spn, clat-lat_spn, ground_m );
ll_pos = offset_from_reference( ll_wgs84, ref_geod );
lr_wgs84 = SGGeod::fromDegM( clon+lon_spn, clat-lat_spn, ground_m );
lr_pos = offset_from_reference( lr_wgs84, ref_geod );
ur_wgs84 = SGGeod::fromDegM( clon+lon_spn, clat+lat_spn, ground_m );
ur_pos = offset_from_reference( ur_wgs84, ref_geod );
ul_wgs84 = SGGeod::fromDegM( clon-lon_spn, clat+lat_spn, ground_m );
ul_pos = offset_from_reference( ul_wgs84, ref_geod );
print_vec3("glower-left:", ll_pos);
print_vec3("glower-right:", lr_pos);
print_vec3("gupper-right:", ur_pos);
print_vec3("gupper-left:", ul_pos);
}
| 33.545113 | 127 | 0.670066 | AuraUAS |
c184369c50700cd126a7f04f0e0b682b146c1330 | 143 | cpp | C++ | building_cpp_with_sfml_wave_01/main.cpp | michaelgautier/codeexpo | f10a38d41cfbea521fc5938360d4481f966593ae | [
"Apache-2.0"
] | 1 | 2019-05-14T15:13:42.000Z | 2019-05-14T15:13:42.000Z | building_cpp_with_sfml_wave_01/main.cpp | michaelgautier/codeexpo | f10a38d41cfbea521fc5938360d4481f966593ae | [
"Apache-2.0"
] | null | null | null | building_cpp_with_sfml_wave_01/main.cpp | michaelgautier/codeexpo | f10a38d41cfbea521fc5938360d4481f966593ae | [
"Apache-2.0"
] | null | null | null | #include "program.h"
using namespace Gautier::SFMLApp;
int main()
{
Program SFMLAppProgram;
SFMLAppProgram.Execute();
return 0;
}
| 14.3 | 34 | 0.692308 | michaelgautier |
c1868d48624a8a26e01e0810da3e31770a8091d1 | 2,957 | cc | C++ | src/heap/finalization-registry-cleanup-task.cc | gilanghamidy/DifferentialFuzzingWASM-v8 | 28a546d241027a5fb715cacd26fd31d06b4bb0c1 | [
"BSD-3-Clause"
] | 1 | 2020-12-25T00:58:59.000Z | 2020-12-25T00:58:59.000Z | src/heap/finalization-registry-cleanup-task.cc | gilanghamidy/DifferentialFuzzingWASM-v8 | 28a546d241027a5fb715cacd26fd31d06b4bb0c1 | [
"BSD-3-Clause"
] | 2 | 2020-02-29T08:38:40.000Z | 2020-03-03T04:15:40.000Z | src/heap/finalization-registry-cleanup-task.cc | gilanghamidy/DifferentialFuzzingWASM-v8 | 28a546d241027a5fb715cacd26fd31d06b4bb0c1 | [
"BSD-3-Clause"
] | 1 | 2020-09-05T18:28:16.000Z | 2020-09-05T18:28:16.000Z | // Copyright 2020 the V8 project 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 "src/heap/finalization-registry-cleanup-task.h"
#include "src/execution/frames.h"
#include "src/execution/interrupts-scope.h"
#include "src/execution/stack-guard.h"
#include "src/execution/v8threads.h"
#include "src/heap/heap-inl.h"
#include "src/objects/js-weak-refs-inl.h"
#include "src/tracing/trace-event.h"
namespace v8 {
namespace internal {
FinalizationRegistryCleanupTask::FinalizationRegistryCleanupTask(Heap* heap)
: CancelableTask(heap->isolate()), heap_(heap) {}
void FinalizationRegistryCleanupTask::SlowAssertNoActiveJavaScript() {
#ifdef ENABLE_SLOW_DCHECKS
class NoActiveJavaScript : public ThreadVisitor {
public:
void VisitThread(Isolate* isolate, ThreadLocalTop* top) override {
for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
DCHECK(!it.frame()->is_java_script());
}
}
};
NoActiveJavaScript no_active_js_visitor;
Isolate* isolate = heap_->isolate();
no_active_js_visitor.VisitThread(isolate, isolate->thread_local_top());
isolate->thread_manager()->IterateArchivedThreads(&no_active_js_visitor);
#endif // ENABLE_SLOW_DCHECKS
}
void FinalizationRegistryCleanupTask::RunInternal() {
Isolate* isolate = heap_->isolate();
DCHECK(!isolate->host_cleanup_finalization_group_callback());
SlowAssertNoActiveJavaScript();
TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8",
"V8.FinalizationRegistryCleanupTask");
HandleScope handle_scope(isolate);
Handle<JSFinalizationRegistry> finalization_registry;
// There could be no dirty FinalizationRegistries. When a context is disposed
// by the embedder, its FinalizationRegistries are removed from the dirty
// list.
if (!heap_->DequeueDirtyJSFinalizationRegistry().ToHandle(
&finalization_registry)) {
return;
}
finalization_registry->set_scheduled_for_cleanup(false);
// Since FinalizationRegistry cleanup callbacks are scheduled by V8, enter the
// FinalizationRegistry's context.
Handle<Context> context(
Context::cast(finalization_registry->native_context()), isolate);
Handle<Object> callback(finalization_registry->cleanup(), isolate);
v8::Context::Scope context_scope(v8::Utils::ToLocal(context));
v8::TryCatch catcher(reinterpret_cast<v8::Isolate*>(isolate));
catcher.SetVerbose(true);
// Exceptions are reported via the message handler. This is ensured by the
// verbose TryCatch.
InvokeFinalizationRegistryCleanupFromTask(context, finalization_registry,
callback);
// Repost if there are remaining dirty FinalizationRegistries.
heap_->set_is_finalization_registry_cleanup_task_posted(false);
heap_->PostFinalizationRegistryCleanupTaskIfNeeded();
}
} // namespace internal
} // namespace v8
| 37.910256 | 80 | 0.748732 | gilanghamidy |
c18879c2f0c496713cb539480a752414bebb9ea4 | 270 | cpp | C++ | OSE Resources Mesh ASSIMP/Resources/Mesh/MeshLoaderFactoryASSIMP.cpp | rexapex/OSE-V2-Game-Engine- | cbf8040d4b017275c073373f8438b227e691858d | [
"MIT"
] | 1 | 2019-09-29T17:45:11.000Z | 2019-09-29T17:45:11.000Z | OSE Resources Mesh ASSIMP/Resources/Mesh/MeshLoaderFactoryASSIMP.cpp | rexapex/OSE-V2-Game-Engine- | cbf8040d4b017275c073373f8438b227e691858d | [
"MIT"
] | 10 | 2020-11-13T13:41:26.000Z | 2020-11-16T18:46:57.000Z | OSE Resources Mesh ASSIMP/Resources/Mesh/MeshLoaderFactoryASSIMP.cpp | rexapex/OSE-Game-Engine | cbf8040d4b017275c073373f8438b227e691858d | [
"MIT"
] | null | null | null | #include "pch.h"
#include "MeshLoaderFactoryASSIMP.h"
#include "MeshLoaderASSIMP.h"
namespace ose::resources
{
uptr<MeshLoader> MeshLoaderFactoryASSIMP::NewMeshLoader(std::string const & project_path)
{
return ose::make_unique<MeshLoaderASSIMP>(project_path);
}
}
| 22.5 | 90 | 0.781481 | rexapex |
c18cb54a11ca97b2edfd4006c9a68a268f7448fc | 1,920 | cc | C++ | examples/inspection.cc | swift-nav/albatross | 54f2edec3f19149f04a2e2e3bbb0b05aba7faba6 | [
"MIT"
] | 15 | 2018-04-10T02:05:06.000Z | 2022-02-07T23:33:27.000Z | examples/inspection.cc | swift-nav/albatross | 54f2edec3f19149f04a2e2e3bbb0b05aba7faba6 | [
"MIT"
] | 79 | 2018-04-19T20:36:18.000Z | 2021-08-04T16:21:19.000Z | examples/inspection.cc | swift-nav/albatross | 54f2edec3f19149f04a2e2e3bbb0b05aba7faba6 | [
"MIT"
] | 4 | 2018-04-06T03:12:16.000Z | 2020-09-11T03:25:08.000Z | /*
* Copyright (C) 2018 Swift Navigation Inc.
* Contact: Swift Navigation <dev@swiftnav.com>
*
* This source is subject to the license found in the file 'LICENSE' which must
* be distributed together with this source. All other rights reserved.
*
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <albatross/GP>
#include <gflags/gflags.h>
#include "example_utils.h"
DEFINE_string(input, "", "path to csv containing input data.");
DEFINE_string(n, "10", "number of training points to use.");
int main(int argc, char *argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
int n = std::stoi(FLAGS_n);
const double low = -3.;
const double high = 13.;
const double meas_noise = 1.;
if (FLAGS_input == "") {
FLAGS_input = "input.csv";
}
maybe_create_training_data(FLAGS_input, n, low, high, meas_noise);
auto data = read_csv_input(FLAGS_input);
using namespace albatross;
std::cout << "Defining the model." << std::endl;
using Noise = IndependentNoise<double>;
using SquaredExp = SquaredExponential<EuclideanDistance>;
Constant constant(100.);
Noise noise(meas_noise);
SquaredExp squared_exponential(3.5, 5.7);
auto cov = constant + noise + squared_exponential;
auto model = gp_from_covariance(cov);
std::cout << "Using Model:" << std::endl;
std::cout << model.pretty_string() << std::endl;
const auto fit_model = model.fit(data);
const auto constant_state =
constant.get_state_space_representation(data.features);
auto posterior_state = fit_model.predict(constant_state).joint();
std::cout << "The posterior estimate of the constant term is: ";
std::cout << posterior_state.mean << " +/- " << posterior_state.covariance
<< std::endl;
}
| 30.967742 | 79 | 0.707292 | swift-nav |
c1912ea74245bba0a13490e451db7b7bd44d188f | 4,369 | cc | C++ | chrome/browser/extensions/api/app_current_window_internal/app_current_window_internal_api.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | chrome/browser/extensions/api/app_current_window_internal/app_current_window_internal_api.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/extensions/api/app_current_window_internal/app_current_window_internal_api.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/app_current_window_internal/app_current_window_internal_api.h"
#include "base/command_line.h"
#include "chrome/browser/extensions/shell_window_registry.h"
#include "chrome/browser/ui/extensions/native_app_window.h"
#include "chrome/browser/ui/extensions/shell_window.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/api/app_current_window_internal.h"
#include "chrome/common/extensions/api/app_window.h"
namespace SetBounds = extensions::api::app_current_window_internal::SetBounds;
using extensions::api::app_current_window_internal::Bounds;
namespace SetIcon = extensions::api::app_current_window_internal::SetIcon;
namespace extensions {
namespace {
const char kNoAssociatedShellWindow[] =
"The context from which the function was called did not have an "
"associated shell window.";
const char kNoExperimental[] =
"This function is experimental. Use --enable-experimental-extension-apis "
"to enable.";
} // namespace
bool AppCurrentWindowInternalExtensionFunction::RunImpl() {
ShellWindowRegistry* registry = ShellWindowRegistry::Get(profile());
DCHECK(registry);
content::RenderViewHost* rvh = render_view_host();
if (!rvh)
// No need to set an error, since we won't return to the caller anyway if
// there's no RVH.
return false;
ShellWindow* window = registry->GetShellWindowForRenderViewHost(rvh);
if (!window) {
error_ = kNoAssociatedShellWindow;
return false;
}
return RunWithWindow(window);
}
bool AppCurrentWindowInternalFocusFunction::RunWithWindow(ShellWindow* window) {
window->GetBaseWindow()->Activate();
return true;
}
bool AppCurrentWindowInternalFullscreenFunction::RunWithWindow(
ShellWindow* window) {
window->Fullscreen();
return true;
}
bool AppCurrentWindowInternalMaximizeFunction::RunWithWindow(
ShellWindow* window) {
window->Maximize();
return true;
}
bool AppCurrentWindowInternalMinimizeFunction::RunWithWindow(
ShellWindow* window) {
window->Minimize();
return true;
}
bool AppCurrentWindowInternalRestoreFunction::RunWithWindow(
ShellWindow* window) {
window->Restore();
return true;
}
bool AppCurrentWindowInternalDrawAttentionFunction::RunWithWindow(
ShellWindow* window) {
window->GetBaseWindow()->FlashFrame(true);
return true;
}
bool AppCurrentWindowInternalClearAttentionFunction::RunWithWindow(
ShellWindow* window) {
window->GetBaseWindow()->FlashFrame(false);
return true;
}
bool AppCurrentWindowInternalShowFunction::RunWithWindow(
ShellWindow* window) {
window->GetBaseWindow()->Show();
return true;
}
bool AppCurrentWindowInternalHideFunction::RunWithWindow(
ShellWindow* window) {
window->GetBaseWindow()->Hide();
return true;
}
bool AppCurrentWindowInternalSetBoundsFunction::RunWithWindow(
ShellWindow* window) {
// Start with the current bounds, and change any values that are specified in
// the incoming parameters.
gfx::Rect bounds = window->GetClientBounds();
scoped_ptr<SetBounds::Params> params(SetBounds::Params::Create(*args_));
CHECK(params.get());
if (params->bounds.left)
bounds.set_x(*(params->bounds.left));
if (params->bounds.top)
bounds.set_y(*(params->bounds.top));
if (params->bounds.width)
bounds.set_width(*(params->bounds.width));
if (params->bounds.height)
bounds.set_height(*(params->bounds.height));
bounds.Inset(-window->GetBaseWindow()->GetFrameInsets());
window->GetBaseWindow()->SetBounds(bounds);
return true;
}
bool AppCurrentWindowInternalSetIconFunction::RunWithWindow(
ShellWindow* window) {
if (!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalExtensionApis)) {
error_ = kNoExperimental;
return false;
}
scoped_ptr<SetIcon::Params> params(SetIcon::Params::Create(*args_));
CHECK(params.get());
// The |icon_url| parameter may be a blob url (e.g. an image fetched with an
// XMLHttpRequest) or a resource url.
GURL url(params->icon_url);
if (!url.is_valid())
url = GetExtension()->GetResourceURL(params->icon_url);
window->SetAppIconUrl(url);
return true;
}
} // namespace extensions
| 30.340278 | 102 | 0.750057 | pozdnyakov |
c1916fcbacd55009a99677cac0d6f078e316d7c4 | 14,367 | cpp | C++ | 1 course/lab_6_dyn_array/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 1 course/lab_6_dyn_array/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | 1 course/lab_6_dyn_array/main.cpp | SgAkErRu/labs | 9cf71e131513beb3c54ad3599f2a1e085bff6947 | [
"BSD-3-Clause"
] | null | null | null | // ver 1.2 - 08.04.19
#include <iostream>
#include <fstream>
#include <ctime>
#include <cmath>
using namespace std;
void filling_array_from_keyboard (short int *A, int N)
{
cout << "*** Осуществляется заполнение динамического массива значениями с клавиатуры ***" << endl;
cout << "Задайте значения элементов динамического массива: " << endl;
int chislo;
for (int i = 0; i < N; i++)
{
cout << "Для " << i+1 << "-го: ";
cin >> chislo;
A[i] = chislo;
}
}
void filling_array_random (short int *A, int N, int min, int max)
{
cout << "*** Осуществляется заполнение динамического массива случайными целыми числами ***" << endl;
int chislo;
int ostatok = (max - min) + 1;
for (int i = 0; i < N; i++)
{
chislo = min + rand() % ( ostatok );
A[i] = chislo;
}
}
void filling_array_from_file (short int *A, int N, string filename)
{
cout << "*** Осуществляется заполнение динамического массива из файла " << filename << " ***" << endl;
int chislo;
ifstream input(filename);
if (input) // проверка открытия
{
for (int i = 0; i < N; i++)
{
input >> chislo;
A[i] = chislo;
}
input.close();
} else cout << endl << "error! Не удалось открыть файл " << filename << endl;
}
void print_array (const short int *A, int N)
{
for (int i = 0; i < N; i++) cout << A[i] << " ";
cout << endl;
}
void diapazon_rand (int &min, int& max)
{
cout << "Задайте диапазон генерирования случайных чисел." << endl;
cout << "Нижняя граница: ";
cin >> min;
cout << "Верхняя граница: ";
cin >> max;
while (min >= max)
{
cout << "error!" << endl;
cout << "Верхняя граница: ";
cin >> max;
}
}
void sposob_zapolneniya (short int *A, int N)
{
int choice;
cout << "*** Выбор способа заполнения ***" << endl;
cout << "1. Заполнение с клавиатуры." << endl;
cout << "2. Заполнение случайными числами." << endl;
cout << "3. Заполнение из файла." << endl;
cout << "Выберите способ заполнения: ";
cin >> choice;
while (choice < 1 || choice > 3)
{
cout << "error!" << endl;
cout << "Выберите способ заполнения: ";
cin >> choice;
}
switch (choice)
{
case 1:
{
filling_array_from_keyboard(A, N);
break;
}
case 2:
{
int min, max;
diapazon_rand(min,max);
filling_array_random(A,N,min,max);
break;
}
case 3:
string filename;
cout << "Введите название файла: ";
cin >> filename;
filling_array_from_file(A,N,filename);
break;
}
}
//Проверка на полный квадрат (если корень double числа равен корню приведенному к int, то число - полный квадрат)
bool full_square (short int chislo)
{
double sqrt_chislo = sqrt(chislo);
if (chislo >= 0 && sqrt_chislo == static_cast<short int> (sqrt_chislo)) return true;
else return false;
}
// Поиск первого квадрата в массиве
short int first_full_square (const short int *A, int N)
{
for(int i = 0; i < N; i++)
{
if (full_square( A[i] )) return A[i];
}
return -1; // значит полных квадратов в массиве нет
}
// Является ли число числом Фибоначчи
bool is_fibonachi (short int chislo)
{
int summa(0), a1 (0), a2(1);
while (summa < chislo)
{
summa = a1 + a2;
a1 = a2;
a2 = summa;
}
if (chislo == summa) return true;
else return false;
}
//Поиск var - числа, в котором нет заданной цифры
bool find_var (short int chislo, short int zadannaya_cifra)
{
if (chislo < 0) chislo = -chislo;
short int ostatok;
if (chislo == zadannaya_cifra) return false;
while (chislo > 0)
{
ostatok = chislo % 10;
if (ostatok == zadannaya_cifra) return false;
chislo /= 10;
}
return true;
}
//Копирование массивов (из temp в A)
void Copy(const short int *temp, short int *A, int N)
{
for (int i = 0; i < N; ++i)
A[i] = temp[i];
}
//Выясняем размер массива после добавления элементов
int insert_future_size_of_array (const short int *A, int N, short int zadannaya_cifra)
{
int N_out = N;
for (int i = 0; i < N; i++)
{
if (find_var(A[i],zadannaya_cifra)) N_out++;
}
return N_out;
}
// Добавление первого полного квадрата после числа, в котором нет заданной цифры
void insert_after_var (const short int *A, short int *temp, int N, short int fullsquare, short int zadannaya_cifra)
{
int i_temp = 0;
for (int i = 0; i < N; i++)
{
temp[i_temp] = A[i];
if (find_var(A[i],zadannaya_cifra))
{
i_temp++;
temp[i_temp] = fullsquare;
}
i_temp++;
}
}
// Добавление до числа, в котором нет заданной цифры
void insert_before_var (const short int *A, short int *temp, int N, short int fullsquare, short int zadannaya_cifra)
{
int i_temp = 0;
for (int i = 0; i < N; i++)
{
if (find_var(A[i],zadannaya_cifra))
{
temp[i_temp] = fullsquare;
i_temp++;
temp[i_temp] = A[i];
}
else temp[i_temp] = A[i];
i_temp++;
}
}
//Выясняем размер массива после удаления элементов
int delete_future_size_of_array (const short int *A, int N)
{
int N_out = N;
for (int i = 0; i < N; i++)
{
if (is_fibonachi(A[i]))
{
N_out--;
}
}
return N_out;
}
// Удаление чисел Фибоначчи
void delete_fibonachi (const short int *A, short int *temp, int N)
{
int i_temp = 0;
for (int i = 0; i < N; i++)
{
if (!is_fibonachi(A[i]))
{
temp[i_temp] = A[i];
i_temp++;
}
}
}
void display_menu ()
{
cout << "*** Меню ***" << endl;
cout << "1. Задание 1.1 - Добавить первый элемент, являющийся полным квадратом после числа, в которых нет заданной цифры." << endl;
cout << "2. Задание 1.2 - Добавить первый элемент, являющийся полным квадратом перед числом, в котором нет заданной цифры." << endl;
cout << "3. Задание 2 - Удалить все числа Фибоначчи." << endl;
cout << "4. Завершить работу программы." << endl;
}
int main()
{
srand((unsigned)time(0));
system("chcp 1251 > nul");
cout << "Лабораторная работа №6 Вариант 13.\nАвтор: Катунин Сергей. ДИПРБ-11.\n" << endl;
// Первый вывод условий меню
display_menu();
// Ввод размера массива
int N;
cout << endl << "Задайте размер динамического массива: ";
cin >> N;
// Проверка на дурака
while (N < 1)
{
cout << "error!" << endl;
cout << "Задайте размер динамического массива: ";
cin >> N;
}
// Конец ввода
short int *A = new short int[N]; // объявляю указатель на рабочий массив и выделяю для него размер N
short int *temp; // объявляю указатель на временный массив
// Список (массив, вектор) заполняется один раз
sposob_zapolneniya(A,N);
cout << "Полученный динамический массив: ";
print_array(A,N);
int menu;
while (menu != 4 && N > 0)
{ //пока пользователь хочет продолжать работу или размер > 0 - работа продолжается
display_menu(); // меню
cout << "Выберите пункт меню: ";
cin >> menu; // выбираем пункт меню и запоминаем номер
//проверка на дурака
while (menu < 0 || menu > 4)
{
cout << "error!" << endl;
cout << "Выберите пункт меню: ";
cin >> menu;
}
if (menu != 4) // завершает работу если пользователь выбрал 4 пункт меню
{
switch (menu) // переходим непосредственно к выполнению заданий
{
case 1:
{
cout << "Выполнение задания 1.1 - Добавить первый элемент, являющийся полным квадратом после числа, в которых нет заданной цифры." << endl;
short int add_elem = first_full_square(A,N); // нахожу первый полный квадрат
if (add_elem == -1) // проверяю, нашлось ли оно
{
cout << "*** В динамическом массиве отсутствуют полные квадраты! ***" << endl;
cout << "Задайте число, которое необходимо добавить: ";
cin >> add_elem; // задаю вручную, если числа не нашлось
}
short int zadannaya_cifra;
cout << "Введите заданную цифру: ";
cin >> zadannaya_cifra; // ввожу заданную цифру
while (zadannaya_cifra < 0 || zadannaya_cifra > 9)
{
cout << "error!" << endl;
cout << "Введите заданную цифру: ";
cin >> zadannaya_cifra;
}
cout << " Динамический массив до изменений: ";
print_array(A,N);
int N_temp = insert_future_size_of_array(A,N,zadannaya_cifra); // вычисляю размер массива после добавления элемента
if (N_temp == N)
{
cout << "Динамический не подвергся изменениям, так как не было найдено числа, в котором нет заданной цифры." << endl;
}
else
{
temp = new short int[N_temp]; // выделяю память под массив temp
insert_after_var(A,temp,N,add_elem,zadannaya_cifra); // переписываю все элементы массива A в массив Temp и заодно добавляю нужные элементы
delete[] A; // очищаю память выделенную для A
N = N_temp; // переопределяю размер N для A
A = new short int[N]; // выделяю память под уже новый массив A
Copy(temp,A,N); // копирую элементы из массива temp в массив A
delete[] temp; // очищаю память выделенную под temp
cout << " Динамический массив после изменений: ";
print_array(A,N);
}
cout << "Задание 1.1 выполнено!" << endl;
break;
}
case 2:
{
cout << "Выполнение задания 1.2 - Добавить первый элемент, являющийся полным квадратом перед числом, в котором нет заданной цифры." << endl;
short int add_elem = first_full_square(A,N); // нахожу первый полный квадрат
if (add_elem == -1) // проверяю, нашлось ли оно
{
cout << "*** В динамическом массиве отсутствуют полные квадраты! ***" << endl;
cout << "Задайте число, которое необходимо добавить: ";
cin >> add_elem; // задаю вручную, если числа не нашлось
}
short int zadannaya_cifra;
cout << "Введите заданную цифру: ";
cin >> zadannaya_cifra; // ввожу заданную цифру
while (zadannaya_cifra < 0 || zadannaya_cifra > 9)
{
cout << "error!" << endl;
cout << "Введите заданную цифру: ";
cin >> zadannaya_cifra;
}
cout << " Динамический массив до изменений: ";
print_array(A,N);
int N_temp = insert_future_size_of_array(A,N,zadannaya_cifra); // вычисляю размер массива после добавления элемента
if (N_temp == N)
{
cout << "Динамический не подвергся изменениям, так как не было найдено числа, в котором нет заданной цифры." << endl;
}
else
{
temp = new short int[N_temp]; // выделяю память под массив temp
insert_before_var(A,temp,N,add_elem,zadannaya_cifra); // переписываю все элементы массива A в массив Temp и заодно добавляю нужные элементы
delete[] A; // очищаю память выделенную для A
N = N_temp; // переопределяю размер N для A
A = new short int[N]; // выделяю память под уже новый массив A
Copy(temp,A,N); // копирую элементы из массива temp в массив A
delete[] temp; // очищаю память выделенную под temp
cout << " Динамический массив после изменений: ";
print_array(A,N);
}
cout << "Задание 1.2 выполнено!" << endl;
break;
}
case 3:
{
cout << " Динамический массив до изменений: ";
print_array(A,N);
int N_temp = delete_future_size_of_array(A,N); // вычисляю размер массива после удаления чисел фибоначчи
if (N_temp == N)
{
cout << "Динамический массив не подвергся изменениям, так как не были найдены числа Фибоначчи." << endl;
}
else
{
temp = new short int[N_temp]; // выделяю память под массив temp
delete_fibonachi(A,temp,N); // переписываю все элементы массива А в массив temp, кроме чисел фибоначчи
delete[] A; // очищаю память выделенную для A
N = N_temp; // переопределяю размер N для A
A = new short int[N]; // выделяю память под уже новый массив A
Copy(temp,A,N); // копирую элементы из массива temp в массив A
delete[] temp; // очищаю память выделенную под temp
cout << " Динамический массив после изменений: ";
print_array(A,N);
}
cout << "Задание 2 выполнено!" << endl;
break;
}
}
}
}
if (N == 0) cout << "Динамический массив опустел в результате удаления элементов.";
else cout << "Программа была завершена по желанию пользователя.";
return 0;
}
| 35.299754 | 163 | 0.523839 | SgAkErRu |
c192cb1f45bb9aa1c09aaf04a25b8692ff7450c0 | 463 | hpp | C++ | include/MessageType.hpp | smalls12/blokus | 33141e55a613c5b74ac5c5ac8807d1972269d788 | [
"Apache-2.0"
] | 1 | 2018-12-28T00:06:30.000Z | 2018-12-28T00:06:30.000Z | include/MessageType.hpp | smalls12/blokus | 33141e55a613c5b74ac5c5ac8807d1972269d788 | [
"Apache-2.0"
] | 1 | 2020-02-07T17:46:26.000Z | 2020-02-07T18:12:07.000Z | include/MessageType.hpp | smalls12/blokus | 33141e55a613c5b74ac5c5ac8807d1972269d788 | [
"Apache-2.0"
] | null | null | null | #pragma once
/* =========================================================
*
* Identifies the type of message before passing down to
* message abstraction layer
*
* ========================================================= */
enum class MessageType
{
REGISTRATION_REQUEST = 0,
REGISTRATION_RESPONSE,
STARTGAME_REQUEST,
STARTGAME_RESPONSE,
PLAYERMOVE_REQUEST,
PLAYERMOVE_RESPONSE,
CHAT_REQUEST,
CHAT_RESPONSE,
UNKNOWN
};
| 21.045455 | 63 | 0.526998 | smalls12 |
c193a0dbbd64bbe5bdca20744fb7a9044b65ecae | 2,442 | hpp | C++ | Plugins/AIOUSB/AIOUSB/deprecated/classlib/AnalogIORange.hpp | networkmodeling/RCVW | 0cd801c5b06824ea295594e227e78eef71d671cc | [
"Apache-2.0"
] | 1 | 2021-06-04T23:44:01.000Z | 2021-06-04T23:44:01.000Z | Plugins/AIOUSB/AIOUSB/deprecated/classlib/AnalogIORange.hpp | networkmodeling/RCVW | 0cd801c5b06824ea295594e227e78eef71d671cc | [
"Apache-2.0"
] | null | null | null | Plugins/AIOUSB/AIOUSB/deprecated/classlib/AnalogIORange.hpp | networkmodeling/RCVW | 0cd801c5b06824ea295594e227e78eef71d671cc | [
"Apache-2.0"
] | 2 | 2021-04-30T22:04:57.000Z | 2021-05-01T19:05:47.000Z | /*
* $RCSfile: AnalogIORange.hpp,v $
* $Date: 2009/12/10 00:10:51 $
* $Revision: 1.1 $
* jEdit:tabSize=4:indentSize=4:collapseFolds=1:
*
* class AnalogIORange declarations
*/
#if ! defined( AnalogIORange_hpp )
#define AnalogIORange_hpp
#include <USBDeviceManager.hpp>
namespace AIOUSB {
/**
* Class AnalogIORange helps manage analog I/O range settings and provides voltage-count conversion utilities.
* A single instance can be used with devices that support just one range, or multiple instances can be used
* with devices that support multiple ranges, such as a separate range per analog I/O channel. This class also
* supports changing the range properties. Some devices, for instance, permit the range to be changed at run-time.
* The class that owns this instance can change the range by calling one or more of the methods of this class.
* Or, for devices that do not support changing the range, the properties can be set up once and left alone. Or,
* some properties can be changed and others left alone. For example, devices that permit changing the voltage
* range usually use a fixed count range.
*/
class AnalogIORange {
protected:
int range; // current range (meaning defined by class that owns this instance)
int minCounts; // minimum A/D or D/A counts for current range (typically 0)
int maxCounts; // maximum A/D or D/A counts for current range (typically 0xfff or 0xffff)
int rangeCounts; // count range (maxCounts - minCounts), to avoid repeatedly calculating this
double minVolts; // minimum volts for current range
double maxVolts; // maximum volts for current range
double rangeVolts; // voltage range (maxVolts - minVolts), to avoid repeatedly calculating this
public:
AnalogIORange();
AnalogIORange( int minCounts, int maxCounts );
virtual ~AnalogIORange();
/**
* Gets the current range ID.
* @return Current range ID (defined by class that owns this instance).
*/
int getRange() const {
return range;
} // getRange()
virtual AnalogIORange &setRange( int range );
AnalogIORange &setCountRange( int minCounts, int maxCounts );
AnalogIORange &setVoltRange( double minVolts, double maxVolts );
double countsToVolts( int counts ) const;
int voltsToCounts( double volts ) const;
}; // class AnalogIORange
} // namespace AIOUSB
#endif
/* end of file */
| 35.391304 | 115 | 0.711302 | networkmodeling |
c19423d8515ffc8dab6df22f350aa7c5456fd559 | 3,527 | cc | C++ | components/policy/core/common/policy_pref_names.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | components/policy/core/common/policy_pref_names.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | components/policy/core/common/policy_pref_names.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 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 "components/policy/core/common/policy_pref_names.h"
namespace policy {
namespace policy_prefs {
// 64-bit serialization of the time last policy usage statistics were collected
// by UMA_HISTOGRAM_ENUMERATION.
const char kLastPolicyStatisticsUpdate[] = "policy.last_statistics_update";
// Enum specifying if/how the SafeSites content filter should be applied.
// See the SafeSitesFilterBehavior policy for details.
const char kSafeSitesFilterBehavior[] = "policy.safe_sites_filter_behavior";
// A list of system features to be disabled (see policy
// "SystemFeaturesDisableList").
const char kSystemFeaturesDisableList[] = "policy.system_features_disable_list";
// Enum specifying the user experience of disabled features.
// See the SystemFeaturesDisableMode policy for details.
const char kSystemFeaturesDisableMode[] = "policy.system_features_disable_mode";
// Blocks access to the listed host patterns.
const char kUrlBlocklist[] = "policy.url_blocklist";
// Allows access to the listed host patterns, as exceptions to the blacklist.
const char kUrlAllowlist[] = "policy.url_allowlist";
// Integer that specifies the policy refresh rate for user-policy in
// milliseconds. Not all values are meaningful, so it is clamped to a sane range
// by the cloud policy subsystem.
const char kUserPolicyRefreshRate[] = "policy.user_refresh_rate";
// Boolean indicates whether the cloud management enrollment is mandatory or
// not.
const char kCloudManagementEnrollmentMandatory[] =
"policy.cloud_management_enrollment_mandatory";
// Integer that sets the minimal limit on the data size in the clipboard to be
// checked against Data Leak Prevention rules.
const char kDlpClipboardCheckSizeLimit[] =
"policy.dlp_clipboard_check_size_limit";
// Boolean policy preference to enable reporting of data leak prevention events.
const char kDlpReportingEnabled[] = "policy.dlp_reporting_enabled";
// A list of Data leak prevention rules.
const char kDlpRulesList[] = "policy.dlp_rules_list";
// A boolean value that can be used to disable native window occlusion
// calculation, even if the Finch feature is enabled.
const char kNativeWindowOcclusionEnabled[] =
"policy.native_window_occlusion_enabled";
// Boolean policy preference for force enabling or disabling the
// IntensiveWakeUpThrottling web feature. Only applied if the policy is managed.
const char kIntensiveWakeUpThrottlingEnabled[] =
"policy.intensive_wake_up_throttling_enabled";
// Boolean that controls whether a window spawned from an anchor targeting
// _blank receives an opener. TODO(crbug.com/898942): Remove this in Chrome 95.
const char kTargetBlankImpliesNoOpener[] =
"policy.target_blank_implies_noopener";
#if defined(OS_ANDROID)
// Boolean policy preference to disable the BackForwardCache feature.
const char kBackForwardCacheEnabled[] = "policy.back_forward_cache_enabled";
#endif // defined(OS_ANDROID)
// Boolean policy to force enable WebSQL in third-party contexts.
const char kWebSQLInThirdPartyContextEnabled[] =
"policy.web_sql_in_third_party_context_enabled";
// Boolean policy preference to disable the User-Agent Client Hints
// updated GREASE algorithm feature.
const char kUserAgentClientHintsGREASEUpdateEnabled[] =
"policy.user_agent_client_hints_grease_update_enabled";
} // namespace policy_prefs
} // namespace policy
| 41.988095 | 80 | 0.799263 | zealoussnow |
c19516318101f87afda968297a424cef154c357a | 3,318 | cpp | C++ | stdlib/imgproc/resize_kernel.cpp | keunhong/scanner | d6439d18b2a363f3cd5e34e12d416bd1e97449fa | [
"Apache-2.0"
] | 1 | 2018-12-05T07:17:49.000Z | 2018-12-05T07:17:49.000Z | stdlib/imgproc/resize_kernel.cpp | quanhua92/scanner | e14153c18078f707fe1b487c0cffb95d6997d737 | [
"Apache-2.0"
] | null | null | null | stdlib/imgproc/resize_kernel.cpp | quanhua92/scanner | e14153c18078f707fe1b487c0cffb95d6997d737 | [
"Apache-2.0"
] | 1 | 2018-10-05T21:37:11.000Z | 2018-10-05T21:37:11.000Z | #include "scanner/api/kernel.h"
#include "scanner/api/op.h"
#include "scanner/util/cuda.h"
#include "scanner/util/memory.h"
#include "scanner/util/opencv.h"
#include "stdlib/stdlib.pb.h"
namespace scanner {
class ResizeKernel : public BatchedKernel {
public:
ResizeKernel(const KernelConfig& config)
: BatchedKernel(config), device_(config.devices[0]) {
args_.ParseFromArray(config.args.data(), config.args.size());
const std::map<std::string, int> INTERP_TYPES = {
{u8"INTER_NEAREST", cv::INTER_NEAREST},
{u8"INTER_LINEAR", cv::INTER_LINEAR},
{u8"INTER_CUBIC", cv::INTER_CUBIC},
{u8"INTER_AREA", cv::INTER_AREA},
{u8"INTER_LANCZOS4", cv::INTER_LANCZOS4},
{u8"INTER_MAX", cv::INTER_MAX},
{u8"WARP_FILL_OUTLIERS", cv::WARP_FILL_OUTLIERS},
{u8"WARP_INVERSE_MAP", cv::WARP_INVERSE_MAP},
};
interp_type_ = cv::INTER_LINEAR;
if (INTERP_TYPES.count(args_.interpolation()) > 0) {
interp_type_ = INTERP_TYPES.at(args_.interpolation());
}
}
void execute(const BatchedElements& input_columns,
BatchedElements& output_columns) override {
auto& frame_col = input_columns[0];
set_device();
const Frame* frame = frame_col[0].as_const_frame();
i32 target_width = args_.width();
i32 target_height = args_.height();
if (args_.preserve_aspect()) {
if (target_width == 0) {
target_width =
frame->width() * target_height / frame->height();
} else {
target_height =
frame->height() * target_width / frame->width();
}
}
if (args_.min()) {
if (frame->width() <= target_width &&
frame->height() <= target_height) {
target_width = frame->width();
target_height = frame->height();
}
}
i32 input_count = num_rows(frame_col);
FrameInfo info(target_height, target_width, frame->channels(), frame->type);
std::vector<Frame*> output_frames = new_frames(device_, info, input_count);
for (i32 i = 0; i < input_count; ++i) {
if (device_.type == DeviceType::CPU) {
cv::Mat img = frame_to_mat(frame_col[i].as_const_frame());
cv::Mat out_mat = frame_to_mat(output_frames[i]);
cv::resize(img, out_mat, cv::Size(target_width, target_height),
0, 0,
interp_type_);
} else {
CUDA_PROTECT({
cvc::GpuMat img = frame_to_gpu_mat(frame_col[i].as_const_frame());
cvc::GpuMat out_mat = frame_to_gpu_mat(output_frames[i]);
cvc::resize(img, out_mat, cv::Size(target_width, target_height),
0, 0,
interp_type_);
});
}
insert_frame(output_columns[0], output_frames[i]);
}
}
void set_device() {
if (device_.type == DeviceType::GPU) {
CUDA_PROTECT({
CU_CHECK(cudaSetDevice(device_.id));
cvc::setDevice(device_.id);
});
}
}
private:
DeviceHandle device_;
proto::ResizeArgs args_;
int interp_type_;
};
REGISTER_OP(Resize).frame_input("frame").frame_output("frame").protobuf_name(
"ResizeArgs");
REGISTER_KERNEL(Resize, ResizeKernel).device(DeviceType::CPU).num_devices(1);
#ifdef HAVE_CUDA
REGISTER_KERNEL(Resize, ResizeKernel).device(DeviceType::GPU).num_devices(1);
#endif
}
| 31.009346 | 80 | 0.630199 | keunhong |
c1951e2242d124f3a46fb98ab36a1ea7db5fdf95 | 1,314 | hpp | C++ | include/ShishGL/Core/EventSystem/EventManager.hpp | Shishqa/ShishGL | 36a3273aecb4b87d040616059ed9487d18abac1a | [
"MIT"
] | null | null | null | include/ShishGL/Core/EventSystem/EventManager.hpp | Shishqa/ShishGL | 36a3273aecb4b87d040616059ed9487d18abac1a | [
"MIT"
] | null | null | null | include/ShishGL/Core/EventSystem/EventManager.hpp | Shishqa/ShishGL | 36a3273aecb4b87d040616059ed9487d18abac1a | [
"MIT"
] | null | null | null | /*============================================================================*/
#ifndef SHISHGL_EVENT_MANAGER_HPP
#define SHISHGL_EVENT_MANAGER_HPP
/*============================================================================*/
#include <type_traits>
#include <queue>
#include "Event.hpp"
/*============================================================================*/
namespace Sh {
class EventManager {
private:
template <typename SomeEvent, typename T>
using Helper =
std::enable_if_t<std::is_base_of<Event, SomeEvent>::value, T>;
public:
template <typename SomeEvent, typename... Args>
static Helper<SomeEvent, void> postEvent(Args&&... args);
virtual ~EventManager() = default;
private:
EventManager() = default;
using EventQueue = std::queue<Event*>;
static EventQueue& Events();
static void flush();
friend class EventSystem;
friend class CoreApplication;
};
}
/*============================================================================*/
#include "EventManager.ipp"
/*============================================================================*/
#endif //SHISHGL_EVENT_MANAGER_HPP
/*============================================================================*/
| 28.565217 | 80 | 0.407915 | Shishqa |
c1993d81cf1dc7d9650ccd9182b64a24e13f924d | 12,064 | cpp | C++ | sp/src/game/server/hoe/hoe_human_medic.cpp | timbaker/heart-of-evil | 4e4729b7ae2dd314fb3695fe8d52545c601d2106 | [
"Unlicense"
] | 2 | 2016-01-11T19:20:59.000Z | 2022-03-06T14:19:37.000Z | sp/src/game/server/hoe/hoe_human_medic.cpp | timbaker/heart-of-evil | 4e4729b7ae2dd314fb3695fe8d52545c601d2106 | [
"Unlicense"
] | null | null | null | sp/src/game/server/hoe/hoe_human_medic.cpp | timbaker/heart-of-evil | 4e4729b7ae2dd314fb3695fe8d52545c601d2106 | [
"Unlicense"
] | null | null | null | #include "cbase.h"
#include "ai_senses.h"
#include "npcevent.h"
#include "hoe_human_medic.h"
#include "schedule_hacks.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DATADESC( CHOEHumanMedic )
DEFINE_FIELD( m_flTimeHealedPlayer, FIELD_TIME ),
DEFINE_USEFUNC( UseMedic ),
END_DATADESC()
//-----------------------------------------------------------------------------
// Animation events.
//-----------------------------------------------------------------------------
Animevent CHOEHumanMedic::AE_HMEDIC_SYRINGE_HELMET;
Animevent CHOEHumanMedic::AE_HMEDIC_SYRINGE_HAND;
Animevent CHOEHumanMedic::AE_HMEDIC_HEAL;
//-----------------------------------------------------------------------------
// Activities
//-----------------------------------------------------------------------------
Activity CHOEHumanMedic::ACT_HMEDIC_HEAL;
Activity CHOEHumanMedic::ACT_HMEDIC_HEAL_CROUCH;
//-----------------------------------------------------------------------------
int CHOEHumanMedic::SelectScheduleCombat( void )
{
if ( HasCondition( COND_NEW_ENEMY ) &&
!EnemyIsBullseye() && // added to stop hiding from the dead-enemy bullseye
IsInSquad() && !IsSquadLeader() && !SquadAnyIdle() )
{
return SCHED_TAKE_COVER_FROM_ENEMY;
}
// This over-rides the default human code for occluded enemies because it establishes a line of fire
// whereas medics are more evasive and care more about healing the wounded than attacking
if ( HasCondition( COND_ENEMY_OCCLUDED ) )
{
if ( IsFollowingHuman() )
{
CHOEHuman *pHuman = HumanPointer( GetTarget() ); // safe because we know it's a human from above
if ( !pHuman->IsAlive() || pHuman->HealthFraction() > 2.0/3.0 || pHuman->WasHealedRecently() )
{
pHuman->StopFollowing(); // FIXME: may have been following someone else
StopFollowing();
return SelectSchedule();
}
else
{
return SCHED_HUMAN_MEDIC_CHASE;
}
}
else if ( IsFollowingPlayer() )
{
if ( GetTarget()->IsAlive() && HealthFraction( GetTarget() ) <= 2.0/3.0 )
{
return SCHED_HUMAN_MEDIC_CHASE;
}
}
else if ( SquadGetWounded( true ) )
{
return SCHED_HUMAN_MEDIC_CHASE;
}
else if ( HasCondition( COND_CAN_RANGE_ATTACK2 ) && OccupyStrategySlotRange( SQUAD_SLOT_HUMAN_GRENADE1, SQUAD_SLOT_HUMAN_GRENADE2 ) )
{
return SCHED_RANGE_ATTACK2;
}
else
{
return SCHED_STANDOFF;
}
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
int CHOEHumanMedic::SelectScheduleHeal( void )
{
if ( !IsFollowing() )
{
// If nearest friendly guy is injured, go over and heal him
CBaseEntity *pHurt = FindHealTarget();
if ( pHurt != NULL )
{
StartFollowing( pHurt );
return SCHED_HUMAN_MEDIC_CHASE;
}
// Search for guy with biggest wounds in squad
if ( SquadGetWounded( true ) )
{
return SCHED_HUMAN_MEDIC_CHASE;
}
}
if ( IsFollowingHuman() )
{
CHOEHuman *pHuman = HumanPointer( GetTarget() ); // safe because we know it's a human from above
if ( !pHuman->IsAlive() || pHuman->HealthFraction() > 2.0/3.0 || pHuman->WasHealedRecently() )
{
pHuman->StopFollowing(); // FIXME: may be following someone else
StopFollowing();
return SelectSchedule();
}
else
{
return SCHED_HUMAN_MEDIC_CHASE;
}
}
else if ( IsFollowingPlayer() )
{
if ( GetTarget()->IsAlive() && HealthFraction( GetTarget() ) <= 2.0/3.0 )
{
return SCHED_HUMAN_MEDIC_CHASE;
}
StopFollowing();
return SelectSchedule();
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
int CHOEHumanMedic::SelectSchedulePriority( void )
{
int sched;
if ( GetState() == NPC_STATE_IDLE || GetState() == NPC_STATE_ALERT )
{
sched = SelectScheduleHeal();
if ( sched != SCHED_NONE )
return sched;
}
// Follow behavior will choose SCHED_RANGE_ATTACK1 if COND_RANGE_ATTACK1 is set.
if ( GetState() == NPC_STATE_COMBAT )
{
if ( HasCondition( COND_NEW_ENEMY )
&& !EnemyIsBullseye() // added to stop hiding from the dead-enemy bullseye
&& IsInSquad() && !IsSquadLeader() && !SquadAnyIdle() )
{
return SCHED_TAKE_COVER_FROM_ENEMY;
}
}
return BaseClass::SelectSchedulePriority();
}
static bool TaskRandomCheck( const Task_t *pTask )
{
return pTask->flTaskData == 0 || random->RandomFloat(0, 1) <= pTask->flTaskData;
}
//-----------------------------------------------------------------------------
void CHOEHumanMedic::StartTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_HUMAN_MEDIC_CHECK_TARGET:
{
CBaseEntity *pTarget = GetFollowTarget();
if ( pTarget != NULL )
{
CHOEHuman *pHuman = HumanPointer( pTarget );
// Make sure target is not dead etc
if ( pTarget->IsPlayer() )
{
if ( pTarget->IsAlive() )
{
TaskComplete();
break;
}
TaskFail( FAIL_NO_TARGET );
}
else if ( !pHuman )
{
TaskFail( FAIL_NO_TARGET );
}
else if ( !pHuman->OkForMedicToHealMe( this ) )
{
// If Target has an enemy, it's more useful to shoot the enemy than to heal target
if ( pHuman->GetEnemy() != NULL && pHuman->HasCondition( COND_SEE_ENEMY ) )
SetEnemy( pHuman->GetEnemy() );
TaskFail( FAIL_NO_TARGET );
}
else
{
TaskComplete();
}
}
else
{
TaskFail( FAIL_NO_TARGET );
}
}
break;
case TASK_HUMAN_MEDIC_SOUND_HEAL:
{
CBaseEntity *pTarget = GetFollowTarget();
if ( pTarget != NULL )
{
#if 1
bool bSpoke = false;
if ( /*TaskRandomCheck( pTask ) &&*/ OkToShout() )
{
#ifdef HOE_HUMAN_RR
SpeechSelection_t selection;
if ( SelectSpeechResponse( TLK_HEAL, NULL, selection ) )
{
SetTalkTarget( pTarget );
DispatchSpeechSelection( selection );
if ( GetSpeechManager() )
{
GetSpeechManager()->ExtendSpeechCategoryTimer( SPEECH_CATEGORY_IDLE, 30 );
GetSpeechManager()->ExtendSpeechCategoryTimer( SPEECH_CATEGORY_INJURY, 30 );
}
bSpoke = true;
}
#else
Speak( "HEAL", 0, pTarget );
#endif
}
if ( !bSpoke )
{
AddLookTarget( pTarget, 1.0, 2.0 );
}
CHOEHuman *pHuman = HumanPointer( pTarget );
if ( pHuman && pHuman->OkForMedicToHealMe( this ) )
{
pHuman->DispatchInteraction( g_interactionHumanMedicHeal, NULL, this );
}
#else
CHuman * pTarget = m_hTargetEnt->MyHumanPointer();
if (pTarget && pTarget->SafeToChangeSchedule() && !pTarget->HasConditions( bits_COND_SEE_ENEMY ) )
{
pTarget->ChangeSchedule( pTarget->GetScheduleOfType( SCHED_HUMAN_WAIT_HEAL ) );
}
#endif
}
TaskComplete();
}
break;
default:
BaseClass::StartTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
void CHOEHumanMedic::RunTask( const Task_t *pTask )
{
switch( pTask->iTask )
{
case TASK_MOVE_TO_TARGET_RANGE:
{
// If we're moving to heal a target, and the target dies, or is healed, stop
if ( IsCurSchedule( SCHED_HUMAN_MEDIC_CHASE ) &&
( !GetFollowTarget() || !GetFollowTarget()->IsAlive() || HealthFraction( GetFollowTarget() ) > 2.0/3.0) )
{
TaskFail( FAIL_NO_TARGET );
return;
}
BaseClass::RunTask( pTask );
break;
}
default:
BaseClass::RunTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
int CHOEHumanMedic::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode )
{
if ( failedSchedule == SCHED_HUMAN_MEDIC_CHASE )
{
if ( GetTarget() != NULL )
{
RememberUnreachable( GetTarget() );
StopFollowing();
}
return SCHED_IDLE_STAND;
}
return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode );
}
//-----------------------------------------------------------------------------
void CHOEHumanMedic::HandleAnimEvent( animevent_t *pEvent )
{
if ( pEvent->event == AE_HMEDIC_HEAL )
{
Heal();
return;
}
if ( pEvent->event == AE_HMEDIC_SYRINGE_HAND )
{
SetBodygroup( HMEDIC_BODYGROUP_SYRINGE, 1 );
return;
}
if ( pEvent->event == AE_HMEDIC_SYRINGE_HELMET )
{
SetBodygroup( HMEDIC_BODYGROUP_SYRINGE, 0 );
return;
}
switch( pEvent->event )
{
case 1:
default:
BaseClass::HandleAnimEvent( pEvent );
break;
}
}
//-----------------------------------------------------------------------------
void CHOEHumanMedic::UseMedic( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
DevMsg("CHOEHumanMedic::UseFunc\n");
}
//-----------------------------------------------------------------------------
CBaseEntity *CHOEHumanMedic::FindHealTarget( void )
{
CBaseEntity *pNearest = NULL;
float flDistToClosest = FLT_MAX;
for ( int i = 0; GetFriendClasses()[i] ; i++ )
{
const char *pszFriend = GetFriendClasses()[i];
if ( HasMemory( bits_MEMORY_PROVOKED ) && !Q_strcmp( pszFriend, "player" ) )
continue;
CBaseEntity *pEntity = NULL;
while ( ( pEntity = gEntList.FindEntityByClassnameWithin( pEntity, pszFriend, GetAbsOrigin(), HUMAN_SPEECH_RADIUS ) ) != 0 )
{
if ( pEntity == this || !pEntity->IsAlive() || HealthFraction( pEntity ) > 2.0/3.0 )
continue;
if ( !GetSenses()->DidSeeEntity( pEntity ) )
continue;
float flDist2 = (pEntity->GetAbsOrigin() - GetAbsOrigin()).LengthSqr();
if ( flDistToClosest < flDist2 )
continue;
if ( IsUnreachable( pEntity ) )
continue;
if ( pEntity->IsPlayer() )
{
if ( TimeRecent( m_flTimeHealedPlayer, 20.0f ) )
{
// Heal the player if he/she/it has been standing and staring at us
// but no more than every 5 seconds.
if ( TimeRecent( m_flTimeHealedPlayer, 5.0f ) || GetTimePlayerStaring() < 2 )
continue;
}
}
else
{
CHOEHuman *pHuman = HumanPointer( pEntity );
if ( pHuman && pHuman->WasHealedRecently() )
continue;
}
pNearest = pEntity;
flDistToClosest = flDist2;
}
}
return pNearest;
}
//-----------------------------------------------------------------------------
void CHOEHumanMedic::Heal( void )
{
CBaseEntity *pTarget = GetTarget();
if ( pTarget == NULL )
return;
StopFollowing();
Vector target = pTarget->GetAbsOrigin() - GetAbsOrigin();
if ( target.Length() > 100 )
return;
// Heal player or human
pTarget->TakeHealth( 25, DMG_GENERIC );
if ( pTarget->IsPlayer() )
{
m_flTimeHealedPlayer = gpGlobals->curtime;
return;
}
CHOEHuman *pHuman = HumanPointer( pTarget );
if ( pHuman )
{
pHuman->m_hMedicThatHealedMe = this;
pHuman->m_flLastMedicHealed = gpGlobals->curtime;
}
}
//-----------------------------------------------------------------------------
Activity CHOEHumanMedic::NPC_TranslateActivity( Activity eNewActivity )
{
eNewActivity = BaseClass::NPC_TranslateActivity( eNewActivity );
bool bCrouch = IsCrouching();
if ( eNewActivity == ACT_HMEDIC_HEAL )
{
if ( bCrouch ) eNewActivity = ACT_HMEDIC_HEAL_CROUCH;
}
return eNewActivity;
}
//-----------------------------------------------------------------------------
void CHOEHumanMedic::Event_Killed( const CTakeDamageInfo &info )
{
if ( !HasAHead() )
SetBodygroup( HMEDIC_BODYGROUP_SYRINGE, 2 );
BaseClass::Event_Killed( info );
}
//-----------------------------------------------------------------------------
bool CHOEHumanMedic::ShouldBlockerMoveAway( CAI_BaseNPC *pBlocker )
{
if ( IsCurSchedule( SCHED_HUMAN_MEDIC_CHASE ) && pBlocker != GetTarget() )
{
return true;
}
return BaseClass::ShouldBlockerMoveAway( pBlocker );
}
HOE_BEGIN_CUSTOM_NPC( hoe_human_medic, CHOEHumanMedic )
DECLARE_TASK( TASK_HUMAN_MEDIC_SOUND_HEAL )
DECLARE_TASK( TASK_HUMAN_MEDIC_CHECK_TARGET )
DECLARE_SCHEDULE( SCHED_HUMAN_MEDIC_HEAL )
DECLARE_SCHEDULE( SCHED_HUMAN_MEDIC_CHASE )
DECLARE_ANIMEVENT( AE_HMEDIC_SYRINGE_HAND )
DECLARE_ANIMEVENT( AE_HMEDIC_SYRINGE_HELMET )
DECLARE_ANIMEVENT( AE_HMEDIC_HEAL )
DECLARE_ACTIVITY( ACT_HMEDIC_HEAL )
DECLARE_ACTIVITY( ACT_HMEDIC_HEAL_CROUCH )
LOAD_SCHEDULES_FILE( npc_human_medic )
HOE_END_CUSTOM_NPC()
| 25.888412 | 135 | 0.606764 | timbaker |
c19b51b3fe764224c02028a55ff9196d04646bc6 | 130 | cc | C++ | build/ARM/arch/arm/pmu.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | 5 | 2019-12-12T16:26:09.000Z | 2022-03-17T03:23:33.000Z | build/ARM/arch/arm/pmu.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | build/ARM/arch/arm/pmu.cc | zhoushuxin/impl_of_HPCA2018 | 594d807fb0c0712bb7766122c4efe3321d012687 | [
"BSD-3-Clause"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:debc68e4dbb38b0effed848d9297d632f5013185a2fedb77865d89d6d835e1e3
size 20574
| 32.5 | 75 | 0.884615 | zhoushuxin |
c19b84e57de39631c337542cc5c6e7a9c4d57b19 | 1,439 | cpp | C++ | src/module.cpp | CrendKing/proxy-copy-handler | 06e00839ef84c596a41851030f35530d79f3a7cd | [
"MIT"
] | 4 | 2020-04-18T04:01:06.000Z | 2022-03-06T09:24:15.000Z | src/module.cpp | CrendKing/proxy-copy-handler | 06e00839ef84c596a41851030f35530d79f3a7cd | [
"MIT"
] | null | null | null | src/module.cpp | CrendKing/proxy-copy-handler | 06e00839ef84c596a41851030f35530d79f3a7cd | [
"MIT"
] | null | null | null | class ProxyCopyHandlerModule : public ATL::CAtlDllModuleT<ProxyCopyHandlerModule> {
} g_module;
extern "C" auto WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) -> BOOL {
return g_module.DllMain(dwReason, lpReserved);
}
_Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllCanUnloadNow() -> HRESULT {
return g_module.DllCanUnloadNow();
}
_Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR *ppv) -> HRESULT {
return g_module.DllGetClassObject(rclsid, riid, ppv);
}
_Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllRegisterServer() -> HRESULT {
return g_module.DllRegisterServer(FALSE);
}
_Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllUnregisterServer() -> HRESULT {
return g_module.DllUnregisterServer(FALSE);
}
_Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllInstall(BOOL bInstall, _In_opt_ PCWSTR pszCmdLine) -> HRESULT {
HRESULT hr = E_FAIL;
static const wchar_t szUserSwitch[] = L"user";
if (pszCmdLine != nullptr) {
if (_wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0) {
ATL::AtlSetPerUserRegistration(true);
}
}
if (bInstall) {
hr = DllRegisterServer();
if (FAILED(hr)) {
DllUnregisterServer();
}
} else {
hr = DllUnregisterServer();
}
return hr;
}
| 31.977778 | 150 | 0.71091 | CrendKing |
c19cdf735fd7d3b989dd6fa2a040fcf18383e1d8 | 6,318 | cpp | C++ | src/shogun/features/streaming/StreamingHashedSparseFeatures.cpp | srgnuclear/shogun | 33c04f77a642416376521b0cd1eed29b3256ac13 | [
"Ruby",
"MIT"
] | 1 | 2015-11-05T18:31:14.000Z | 2015-11-05T18:31:14.000Z | src/shogun/features/streaming/StreamingHashedSparseFeatures.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | src/shogun/features/streaming/StreamingHashedSparseFeatures.cpp | waderly/shogun | 9288b6fa38e001d63c32188f7f847dadea66e2ae | [
"Ruby",
"MIT"
] | null | null | null | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Written (W) 2013 Evangelos Anagnostopoulos
* Copyright (C) 2013 Evangelos Anagnostopoulos
*/
#include <shogun/features/streaming/StreamingHashedSparseFeatures.h>
#include <shogun/features/HashedSparseFeatures.h>
#include <shogun/io/streaming/StreamingFileFromSparseFeatures.h>
namespace shogun
{
template <class ST>
CStreamingHashedSparseFeatures<ST>::CStreamingHashedSparseFeatures()
{
init(NULL, false, 0, 0, false, true);
}
template <class ST>
CStreamingHashedSparseFeatures<ST>::CStreamingHashedSparseFeatures(CStreamingFile* file,
bool is_labelled, int32_t size, int32_t d, bool use_quadr, bool keep_lin_terms)
{
init(file, is_labelled, size, d, use_quadr, keep_lin_terms);
}
template <class ST>
CStreamingHashedSparseFeatures<ST>::CStreamingHashedSparseFeatures(CSparseFeatures<ST>* dot_features,
int32_t d, bool use_quadr, bool keep_lin_terms, float64_t* lab)
{
ASSERT(dot_features);
CStreamingFileFromSparseFeatures<ST>* file =
new CStreamingFileFromSparseFeatures<ST>(dot_features, lab);
bool is_labelled = (lab != NULL);
int32_t size = 1024;
init(file, is_labelled, size, d, use_quadr, keep_lin_terms);
parser.set_free_vectors_on_destruct(false);
seekable=true;
}
template <class ST>
CStreamingHashedSparseFeatures<ST>::~CStreamingHashedSparseFeatures()
{
}
template <class ST>
void CStreamingHashedSparseFeatures<ST>::init(CStreamingFile* file, bool is_labelled,
int32_t size, int32_t d, bool use_quadr, bool keep_lin_terms)
{
dim = d;
SG_ADD(&dim, "dim", "Size of target dimension", MS_NOT_AVAILABLE);
use_quadratic = use_quadr;
keep_linear_terms = keep_lin_terms;
SG_ADD(&use_quadratic, "use_quadratic", "Whether to use quadratic features",
MS_NOT_AVAILABLE);
SG_ADD(&keep_linear_terms, "keep_linear_terms", "Whether to keep the linear terms or not",
MS_NOT_AVAILABLE);
has_labels = is_labelled;
if (file)
{
working_file = file;
SG_REF(working_file);
parser.init(file, is_labelled, size);
seekable = false;
}
else
file = NULL;
set_read_functions();
parser.set_free_vector_after_release(false);
set_generic<ST>();
}
template <class ST>
float32_t CStreamingHashedSparseFeatures<ST>::dot(CStreamingDotFeatures* df)
{
ASSERT(df);
ASSERT(df->get_feature_type() == get_feature_type())
ASSERT(strcmp(df->get_name(),get_name())==0)
CStreamingHashedSparseFeatures<ST>* hdf = (CStreamingHashedSparseFeatures<ST>* ) df;
return current_vector.sparse_dot(hdf->current_vector);
}
template <class ST>
float32_t CStreamingHashedSparseFeatures<ST>::dense_dot(const float32_t* vec2, int32_t vec2_len)
{
ASSERT(vec2_len == dim);
float32_t result = 0;
for (index_t i=0; i<current_vector.num_feat_entries; i++)
result += vec2[current_vector.features[i].feat_index] * current_vector.features[i].entry;
return result;
}
template <class ST>
void CStreamingHashedSparseFeatures<ST>::add_to_dense_vec(float32_t alpha, float32_t* vec2,
int32_t vec2_len, bool abs_val)
{
ASSERT(vec2_len == dim);
if (abs_val)
alpha = CMath::abs(alpha);
for (index_t i=0; i<current_vector.num_feat_entries; i++)
vec2[current_vector.features[i].feat_index] += alpha * current_vector.features[i].entry;
}
template <class ST>
int32_t CStreamingHashedSparseFeatures<ST>::get_dim_feature_space() const
{
return dim;
}
template <class ST>
const char* CStreamingHashedSparseFeatures<ST>::get_name() const
{
return "StreamingHashedSparseFeatures";
}
template <class ST>
int32_t CStreamingHashedSparseFeatures<ST>::get_num_vectors() const
{
return 1;
}
template <class ST>
CFeatures* CStreamingHashedSparseFeatures<ST>::duplicate() const
{
return new CStreamingHashedSparseFeatures<ST>(*this);
}
template <class ST>
void CStreamingHashedSparseFeatures<ST>::set_vector_reader()
{
SG_DEBUG("called inside set_vector_reader\n");
parser.set_read_vector(&CStreamingFile::get_sparse_vector);
}
template <class ST>
void CStreamingHashedSparseFeatures<ST>::set_vector_and_label_reader()
{
parser.set_read_vector_and_label(&CStreamingFile::get_sparse_vector_and_label);
}
template <class ST>
EFeatureType CStreamingHashedSparseFeatures<ST>::get_feature_type() const
{
return F_UINT;
}
template <class ST>
EFeatureClass CStreamingHashedSparseFeatures<ST>::get_feature_class() const
{
return C_STREAMING_SPARSE;
}
template <class ST>
void CStreamingHashedSparseFeatures<ST>::start_parser()
{
if (!parser.is_running())
parser.start_parser();
}
template <class ST>
void CStreamingHashedSparseFeatures<ST>::end_parser()
{
parser.end_parser();
}
template <class ST>
float64_t CStreamingHashedSparseFeatures<ST>::get_label()
{
return current_label;
}
template <class ST>
bool CStreamingHashedSparseFeatures<ST>::get_next_example()
{
SGSparseVector<ST> tmp;
if (parser.get_next_example(tmp.features,
tmp.num_feat_entries, current_label))
{
current_vector = CHashedSparseFeatures<ST>::hash_vector(tmp, dim,
use_quadratic, keep_linear_terms);
tmp.features = NULL;
tmp.num_feat_entries = -1;
return true;
}
return false;
}
template <class ST>
void CStreamingHashedSparseFeatures<ST>::release_example()
{
parser.finalize_example();
}
template <class ST>
int32_t CStreamingHashedSparseFeatures<ST>::get_num_features()
{
return dim;
}
template <class ST>
SGSparseVector<ST> CStreamingHashedSparseFeatures<ST>::get_vector()
{
return current_vector;
}
template class CStreamingHashedSparseFeatures<bool>;
template class CStreamingHashedSparseFeatures<char>;
template class CStreamingHashedSparseFeatures<int8_t>;
template class CStreamingHashedSparseFeatures<uint8_t>;
template class CStreamingHashedSparseFeatures<int16_t>;
template class CStreamingHashedSparseFeatures<uint16_t>;
template class CStreamingHashedSparseFeatures<int32_t>;
template class CStreamingHashedSparseFeatures<uint32_t>;
template class CStreamingHashedSparseFeatures<int64_t>;
template class CStreamingHashedSparseFeatures<uint64_t>;
template class CStreamingHashedSparseFeatures<float32_t>;
template class CStreamingHashedSparseFeatures<float64_t>;
template class CStreamingHashedSparseFeatures<floatmax_t>;
}
| 26.658228 | 101 | 0.790282 | srgnuclear |
c19d9250d7067d3e1874ebc8316af9643769da00 | 1,090 | hpp | C++ | src/shader.hpp | BujakiAttila/GPGPU-GameOfLife | 6fd13fe5f7a6a21c7820822df54d737f750177d2 | [
"MIT"
] | null | null | null | src/shader.hpp | BujakiAttila/GPGPU-GameOfLife | 6fd13fe5f7a6a21c7820822df54d737f750177d2 | [
"MIT"
] | null | null | null | src/shader.hpp | BujakiAttila/GPGPU-GameOfLife | 6fd13fe5f7a6a21c7820822df54d737f750177d2 | [
"MIT"
] | null | null | null | #ifndef _SHADER_
#define _SHADER_
#include <string>
#include <GL/glew.h>
class Shader{
private:
GLuint shaderProgram;
Shader();
bool fileToString(const char* path, char* &out, int& len);
public:
Shader(const char* vertexShaderPath, const char* fragmentShaderPath);
virtual ~Shader();
void shaderFromFile(const char* shaderPath, GLenum shaderType, GLuint& handle);
void linkShaders(GLuint& vertexShader, GLuint& fragmentShader, GLuint& handle);
std::string getShaderInfoLog(GLuint& object);
std::string getProgramInfoLog(GLuint& object);
void enable();
void disable();
GLuint getHandle(){
return shaderProgram;
}
void bindUniformInt(const char* name, int i);
void bindUniformInt2(const char* name, int i1, int i2);
void bindUniformFloat(const char* name, float f);
void bindUniformFloat2(const char* name, float f1, float f2);
void bindUniformFloat3(const char* name, float f1, float f2, float f3);
void bindUniformTexture(const char* name, GLuint texture, GLuint unit);
void bindAttribLocation(GLuint id, const char* name);
};
#endif
| 25.348837 | 81 | 0.73578 | BujakiAttila |
c19fab504630ceb5e28c641dab3be61995a3dbf6 | 589 | cpp | C++ | kattis_numbertree.cpp | dylanashley/programming-problems | aeba99daaaade1071ed3ab8d51d6f36e84493ef6 | [
"MIT"
] | null | null | null | kattis_numbertree.cpp | dylanashley/programming-problems | aeba99daaaade1071ed3ab8d51d6f36e84493ef6 | [
"MIT"
] | null | null | null | kattis_numbertree.cpp | dylanashley/programming-problems | aeba99daaaade1071ed3ab8d51d6f36e84493ef6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main()
{
int height;
int label = 1;
string path;
cin >> height;
if (cin.eof())
{
label = (1 << (height + 1)) - 1;
}
else
{
cin >> path;
for (int i = 0; i < path.length(); ++i)
{
if (path[i] == 'L')
{
label = label << 1;
}
else
{
label = (label << 1) + 1;
}
}
label = (1 << (height + 1)) - label;
}
cout << label << endl;
}
| 15.102564 | 47 | 0.353141 | dylanashley |
c1a05395e177597e8174ca15b7c1be33909f4053 | 3,681 | cpp | C++ | inference-engine/tests/functional/inference_engine/serialization/single_layer/pooling.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2022-02-10T08:05:09.000Z | 2022-02-10T08:05:09.000Z | inference-engine/tests/functional/inference_engine/serialization/single_layer/pooling.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 40 | 2020-12-04T07:46:57.000Z | 2022-02-21T13:04:40.000Z | inference-engine/tests/functional/inference_engine/serialization/single_layer/pooling.cpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2020-08-30T11:48:03.000Z | 2020-08-30T11:48:03.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include "shared_test_classes/single_layer/pooling.hpp"
#include "common_test_utils/test_constants.hpp"
using namespace LayerTestsDefinitions;
namespace {
TEST_P(PoolingLayerTest, Serialize) {
Serialize();
}
const std::vector<InferenceEngine::Precision> netPrecisions = {
InferenceEngine::Precision::FP32,
InferenceEngine::Precision::FP16
};
/* ============= POOLING ============= */
const std::vector<std::vector<size_t >> kernels = {{3, 3},
{3, 5}};
const std::vector<std::vector<size_t >> strides = {{1, 1},
{1, 2}};
const std::vector<std::vector<size_t >> padBegins = {{0, 0},
{0, 2}};
const std::vector<std::vector<size_t >> padEnds = {{0, 0},
{0, 2}};
const std::vector<ngraph::op::RoundingType> roundingTypes = {
ngraph::op::RoundingType::FLOOR,
ngraph::op::RoundingType::CEIL
};
const std::vector<ngraph::op::PadType> padTypes = {
ngraph::op::PadType::EXPLICIT,
ngraph::op::PadType::SAME_UPPER,
ngraph::op::PadType::VALID
};
const std::vector<size_t> inputShape = {511, 11, 13, 15};
const std::vector<bool> excludePad = {true, false};
/* ============= AVERAGE POOLING ============= */
const auto avgExcludePadParams = ::testing::Combine(
::testing::Values(ngraph::helpers::PoolingTypes::AVG),
::testing::ValuesIn(kernels),
::testing::ValuesIn(strides),
::testing::ValuesIn(padBegins),
::testing::ValuesIn(padEnds),
::testing::ValuesIn(roundingTypes),
::testing::ValuesIn(padTypes),
::testing::Values(excludePad[0]));
INSTANTIATE_TEST_CASE_P(smoke_AvgPoolExcluePad, PoolingLayerTest,
::testing::Combine(
avgExcludePadParams,
::testing::ValuesIn(netPrecisions),
::testing::Values(InferenceEngine::Precision::UNSPECIFIED),
::testing::Values(InferenceEngine::Precision::UNSPECIFIED),
::testing::Values(InferenceEngine::Layout::ANY),
::testing::Values(InferenceEngine::Layout::ANY),
::testing::Values(inputShape),
::testing::Values(CommonTestUtils::DEVICE_CPU)),
PoolingLayerTest::getTestCaseName);
const auto avgPadParams = ::testing::Combine(
::testing::Values(ngraph::helpers::PoolingTypes::AVG),
::testing::ValuesIn(kernels),
::testing::ValuesIn(strides),
::testing::ValuesIn(padBegins),
::testing::ValuesIn(padEnds),
::testing::ValuesIn(roundingTypes),
::testing::ValuesIn(padTypes),
::testing::Values(excludePad[1]));
INSTANTIATE_TEST_CASE_P(smoke_AvgPool, PoolingLayerTest,
::testing::Combine(
avgPadParams,
::testing::ValuesIn(netPrecisions),
::testing::Values(InferenceEngine::Precision::UNSPECIFIED),
::testing::Values(InferenceEngine::Precision::UNSPECIFIED),
::testing::Values(InferenceEngine::Layout::ANY),
::testing::Values(InferenceEngine::Layout::ANY),
::testing::Values(inputShape),
::testing::Values(CommonTestUtils::DEVICE_CPU)),
PoolingLayerTest::getTestCaseName);
} // namespace
| 39.580645 | 75 | 0.561261 | JOCh1958 |
c1a4c73501006f4f9b893b09820d43af00459514 | 2,343 | cpp | C++ | Sandbox/src/Sandbox3D/Model/Billboard.cpp | cyandestructor/Sandbox3D | de19e962aeb69f7e6f28fe07263f95920332287a | [
"MIT"
] | null | null | null | Sandbox/src/Sandbox3D/Model/Billboard.cpp | cyandestructor/Sandbox3D | de19e962aeb69f7e6f28fe07263f95920332287a | [
"MIT"
] | null | null | null | Sandbox/src/Sandbox3D/Model/Billboard.cpp | cyandestructor/Sandbox3D | de19e962aeb69f7e6f28fe07263f95920332287a | [
"MIT"
] | null | null | null | #include "Billboard.h"
Billboard::Billboard()
{
static const float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.0f, 0.0f,
0.5f, -0.5f, 0.0f,
1.0f, 0.0f,
-0.5f, 0.5f, 0.0f,
0.0f, 1.0f,
0.5f, 0.5f, 0.0f,
1.0f, 1.0f
};
m_vertexArray = Jass::VertexArray::Create();
auto vbo = Jass::VertexBuffer::Create({ vertices, sizeof(vertices), Jass::DataUsage::StaticDraw });
vbo->SetLayout({
Jass::BufferElement(Jass::ShaderDataType::Float3, "a_position"),
Jass::BufferElement(Jass::ShaderDataType::Float2, "a_texCoords")
});
m_vertexArray->AddVertexBuffer(vbo);
unsigned int indices[] = {
0, 1, 2,
2, 1, 3
};
auto ibo = Jass::IndexBuffer::Create({ indices, 6, Jass::DataUsage::StaticDraw });
m_vertexArray->SetIndexBuffer(ibo);
}
Billboard::Billboard(const Jass::JVec3& position, const Jass::JVec3& scale)
:m_position(position), m_scale(scale)
{
static const float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.0f, 0.0f,
0.5f, -0.5f, 0.0f,
1.0f, 0.0f,
-0.5f, 0.5f, 0.0f,
0.0f, 1.0f,
0.5f, 0.5f, 0.0f,
1.0f, 1.0f
};
m_vertexArray = Jass::VertexArray::Create();
auto vbo = Jass::VertexBuffer::Create({ vertices, sizeof(vertices), Jass::DataUsage::StaticDraw });
vbo->SetLayout({
Jass::BufferElement(Jass::ShaderDataType::Float3, "a_position"),
Jass::BufferElement(Jass::ShaderDataType::Float2, "a_texCoords")
});
m_vertexArray->AddVertexBuffer(vbo);
unsigned int indices[] = {
0, 1, 2,
2, 1, 3
};
auto ibo = Jass::IndexBuffer::Create({ indices, 6, Jass::DataUsage::StaticDraw });
m_vertexArray->SetIndexBuffer(ibo);
}
void Billboard::Render(Jass::Ref<Jass::Shader>& shader, const Light& light, const Jass::Camera& camera)
{
shader->Bind();
const auto& viewMatrix = camera.GetView();
Jass::JVec3 cameraRightWS = { viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0] };
Jass::JVec3 cameraUpWS = { viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1] };
shader->SetFloat3("u_cameraRightWS", cameraRightWS);
shader->SetFloat3("u_cameraUpWS", cameraUpWS);
shader->SetFloat3("u_billboardPosition", m_position);
shader->SetFloat3("u_billboardScale", m_scale);
shader->SetMat4("u_viewProjection", camera.GetViewProjection());
m_material.Prepare(shader, light);
Jass::RenderCommand::DrawIndexed(m_vertexArray);
//Jass::Renderer::Submit(shader, m_vertexArray);
}
| 26.033333 | 103 | 0.673922 | cyandestructor |
c1a772fac95cff54fc9ab0a09ae37a05490478ca | 537 | cpp | C++ | lintcode/rotatestring.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2016-01-20T08:26:34.000Z | 2016-01-20T08:26:34.000Z | lintcode/rotatestring.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | 1 | 2015-10-21T05:38:17.000Z | 2015-11-02T07:42:55.000Z | lintcode/rotatestring.cpp | WIZARD-CXY/pl | 22b7f5d81804f4e333d3cff6433364ba1a0ac7ef | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
/**
* param A: A string
* param offset: Rotate string with offset.
* return: Rotated string.
*/
string rotateString(string A, int offset) {
// wirte your code here
int len=A.size();
if(len==0){
return "";
}
offset%=len;
string res=A;
reverse(res.begin(),res.end());
reverse(res.begin(),res.begin()+offset);
reverse(res.begin()+offset,res.end());
return res;
}
};
| 21.48 | 48 | 0.489758 | WIZARD-CXY |
c1a857079e4988789cdbca79dddf135c1f093773 | 2,306 | hpp | C++ | Graphics/ShaderTools/include/DXCompilerBaseUWP.hpp | AndreyMlashkin/DiligentCore | 20d5d7d2866e831a73437db2dec16bdc61413eb0 | [
"Apache-2.0"
] | null | null | null | Graphics/ShaderTools/include/DXCompilerBaseUWP.hpp | AndreyMlashkin/DiligentCore | 20d5d7d2866e831a73437db2dec16bdc61413eb0 | [
"Apache-2.0"
] | null | null | null | Graphics/ShaderTools/include/DXCompilerBaseUWP.hpp | AndreyMlashkin/DiligentCore | 20d5d7d2866e831a73437db2dec16bdc61413eb0 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019-2021 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* 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.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <Unknwn.h>
#include <guiddef.h>
#include <atlbase.h>
#include <atlcom.h>
#include "dxc/dxcapi.h"
#include "DXCompiler.hpp"
namespace Diligent
{
namespace
{
class DXCompilerBase : public IDXCompiler
{
public:
~DXCompilerBase() override
{
if (Module)
FreeLibrary(Module);
}
protected:
DxcCreateInstanceProc Load(DXCompilerTarget, const String& LibName)
{
if (LibName.size())
{
std::wstring wname{LibName.begin(), LibName.end()};
wname += L".dll";
Module = LoadPackagedLibrary(wname.c_str(), 0);
}
if (Module == nullptr)
Module = LoadPackagedLibrary(L"dxcompiler.dll", 0);
return Module ? reinterpret_cast<DxcCreateInstanceProc>(GetProcAddress(Module, "DxcCreateInstance")) : nullptr;
}
private:
HMODULE Module = nullptr;
};
} // namespace
} // namespace Diligent
| 29.948052 | 119 | 0.694276 | AndreyMlashkin |
c1abcc6c4d69344a88dabfe4514c64506da48639 | 3,470 | cxx | C++ | panda/src/physics/linearCylinderVortexForce.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/physics/linearCylinderVortexForce.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/physics/linearCylinderVortexForce.cxx | cmarshall108/panda3d-python3 | 8bea2c0c120b03ec1c9fd179701fdeb7510bb97b | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file linearCylinderVortexForce.cxx
* @author charles
* @date 2000-07-24
*/
#include "config_physics.h"
#include "linearCylinderVortexForce.h"
#include "nearly_zero.h"
#include "cmath.h"
TypeHandle LinearCylinderVortexForce::_type_handle;
/**
* Simple Constructor
*/
LinearCylinderVortexForce::
LinearCylinderVortexForce(PN_stdfloat radius, PN_stdfloat length, PN_stdfloat coef,
PN_stdfloat a, bool md) :
LinearForce(a, md),
_radius(radius), _length(length), _coef(coef) {
}
/**
* copy Constructor
*/
LinearCylinderVortexForce::
LinearCylinderVortexForce(const LinearCylinderVortexForce ©) :
LinearForce(copy) {
_radius = copy._radius;
_length = copy._length;
_coef = copy._coef;
}
/**
* Destructor
*/
LinearCylinderVortexForce::
~LinearCylinderVortexForce() {
}
/**
* child copier
*/
LinearForce *LinearCylinderVortexForce::
make_copy() {
return new LinearCylinderVortexForce(*this);
}
/**
* returns the centripetal force vector for the passed-in object
*/
LVector3 LinearCylinderVortexForce::
get_child_vector(const PhysicsObject *po) {
// get the force-space transform- this MUST be the relative matrix from the
// point's local coordinate system to the attached node's local system.
// LMatrix4 force_space_xform = LMatrix4::ident_mat();
LVector3 force_vec(0.0f, 0.0f, 0.0f);
// project the point into force_space
LPoint3 point = po->get_position();
// clip along length
if (point[2] < 0.0f || point[2] > _length)
return force_vec;
// clip to radius
PN_stdfloat x_squared = point[0] * point[0];
PN_stdfloat y_squared = point[1] * point[1];
PN_stdfloat dist_squared = x_squared + y_squared;
PN_stdfloat radius_squared = _radius * _radius;
// squared space increases monotonically wrt linear space, so there's no
// need to sqrt to check insideoutside this disc.
if (dist_squared > radius_squared)
return force_vec;
if IS_NEARLY_ZERO(dist_squared)
return force_vec;
PN_stdfloat r = csqrt(dist_squared);
if IS_NEARLY_ZERO(r)
return force_vec;
LVector3 tangential = point;
tangential[2] = 0.0f;
tangential.normalize();
tangential = tangential.cross(LVector3(0,0,1));
LVector3 centripetal = -point;
centripetal[2] = 0.0f;
centripetal.normalize();
LVector3 combined = tangential + centripetal;
combined.normalize();
// a = v^2 r centripetal = centripetal * _coef *
// (tangential.length_squared() (r + get_nearly_zero_value(r)));
centripetal = combined * _coef * po->get_velocity().length();
// centripetal = combined * _coef * (po->get_velocity().length() (r +
// get_nearly_zero_value(r)));
return centripetal;
}
/**
* Write a string representation of this instance to <out>.
*/
void LinearCylinderVortexForce::
output(std::ostream &out) const {
#ifndef NDEBUG //[
out<<"LinearCylinderVortexForce";
#endif //] NDEBUG
}
/**
* Write a string representation of this instance to <out>.
*/
void LinearCylinderVortexForce::
write(std::ostream &out, int indent) const {
#ifndef NDEBUG //[
out.width(indent); out<<""; out<<"LinearCylinderVortexForce:\n";
LinearForce::write(out, indent+2);
#endif //] NDEBUG
}
| 25.514706 | 83 | 0.712968 | cmarshall108 |
c1acef96e757de6f7164ceb13a1438d633c00458 | 2,136 | cc | C++ | ivpd/src/model/GetRenderResultResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | ivpd/src/model/GetRenderResultResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | ivpd/src/model/GetRenderResultResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* 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/ivpd/model/GetRenderResultResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Ivpd;
using namespace AlibabaCloud::Ivpd::Model;
GetRenderResultResult::GetRenderResultResult() :
ServiceResult()
{}
GetRenderResultResult::GetRenderResultResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetRenderResultResult::~GetRenderResultResult()
{}
void GetRenderResultResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["Completed"].isNull())
data_.completed = dataNode["Completed"].asString() == "true";
if(!dataNode["Progress"].isNull())
data_.progress = std::stof(dataNode["Progress"].asString());
if(!dataNode["Code"].isNull())
data_.code = dataNode["Code"].asString();
if(!dataNode["Message"].isNull())
data_.message = dataNode["Message"].asString();
auto resultDataNode = dataNode["ResultData"];
if(!resultDataNode["ImageUrl"].isNull())
data_.resultData.imageUrl = resultDataNode["ImageUrl"].asString();
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
}
std::string GetRenderResultResult::getMessage()const
{
return message_;
}
GetRenderResultResult::Data GetRenderResultResult::getData()const
{
return data_;
}
std::string GetRenderResultResult::getCode()const
{
return code_;
}
| 28.105263 | 75 | 0.733614 | iamzken |
c1af627d759e58563bb83352b9dc2d6045ef4db2 | 49,547 | cpp | C++ | src/energyplus/ForwardTranslator/ForwardTranslatePlantLoop.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 354 | 2015-01-10T17:46:11.000Z | 2022-03-29T10:00:00.000Z | src/energyplus/ForwardTranslator/ForwardTranslatePlantLoop.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 3,243 | 2015-01-02T04:54:45.000Z | 2022-03-31T17:22:22.000Z | src/energyplus/ForwardTranslator/ForwardTranslatePlantLoop.cpp | jmarrec/OpenStudio | 5276feff0d8dbd6c8ef4e87eed626bc270a19b14 | [
"blessing"
] | 157 | 2015-01-07T15:59:55.000Z | 2022-03-30T07:46:09.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. 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 any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include "../ForwardTranslator.hpp"
#include "../../model/Model.hpp"
#include "../../model/PlantLoop.hpp"
#include "../../model/PlantLoop_Impl.hpp"
#include "../../model/AvailabilityManagerAssignmentList.hpp"
#include "../../model/AvailabilityManagerAssignmentList_Impl.hpp"
#include "../../model/AvailabilityManager.hpp"
#include "../../model/AvailabilityManager_Impl.hpp"
#include "../../model/AirLoopHVACOutdoorAirSystem.hpp"
#include "../../model/AirLoopHVACOutdoorAirSystem_Impl.hpp"
#include "../../model/SizingPlant.hpp"
#include "../../model/SizingPlant_Impl.hpp"
#include "../../model/Node.hpp"
#include "../../model/Node_Impl.hpp"
#include "../../model/Splitter.hpp"
#include "../../model/Splitter_Impl.hpp"
#include "../../model/Mixer.hpp"
#include "../../model/Mixer_Impl.hpp"
#include "../../model/PumpVariableSpeed.hpp"
#include "../../model/Schedule.hpp"
#include "../../model/Schedule_Impl.hpp"
#include "../../model/BoilerHotWater.hpp"
#include "../../model/BoilerHotWater_Impl.hpp"
#include "../../model/CentralHeatPumpSystem.hpp"
#include "../../model/CentralHeatPumpSystem_Impl.hpp"
#include "../../model/ChillerElectricEIR.hpp"
#include "../../model/ChillerElectricEIR_Impl.hpp"
#include "../../model/ChillerElectricReformulatedEIR.hpp"
#include "../../model/ChillerElectricReformulatedEIR_Impl.hpp"
#include "../../model/ChillerAbsorption.hpp"
#include "../../model/ChillerAbsorption_Impl.hpp"
#include "../../model/ChillerAbsorptionIndirect.hpp"
#include "../../model/ChillerAbsorptionIndirect_Impl.hpp"
#include "../../model/WaterHeaterMixed.hpp"
#include "../../model/WaterHeaterMixed_Impl.hpp"
#include "../../model/WaterHeaterHeatPump.hpp"
#include "../../model/WaterHeaterHeatPump_Impl.hpp"
#include "../../model/WaterHeaterStratified.hpp"
#include "../../model/WaterHeaterStratified_Impl.hpp"
#include "../../model/CoolingTowerVariableSpeed.hpp"
#include "../../model/CoolingTowerVariableSpeed_Impl.hpp"
#include "../../model/CoolingTowerSingleSpeed.hpp"
#include "../../model/CoolingTowerSingleSpeed_Impl.hpp"
#include "../../model/CoolingTowerTwoSpeed.hpp"
#include "../../model/CoolingTowerTwoSpeed_Impl.hpp"
#include "../../model/GeneratorMicroTurbine.hpp"
#include "../../model/GeneratorMicroTurbine_Impl.hpp"
#include "../../model/GeneratorMicroTurbineHeatRecovery.hpp"
#include "../../model/GeneratorMicroTurbineHeatRecovery_Impl.hpp"
#include "../../model/GroundHeatExchangerVertical.hpp"
#include "../../model/GroundHeatExchangerVertical_Impl.hpp"
#include "../../model/GroundHeatExchangerHorizontalTrench.hpp"
#include "../../model/GroundHeatExchangerHorizontalTrench_Impl.hpp"
#include "../../model/HeatExchangerFluidToFluid.hpp"
#include "../../model/HeatExchangerFluidToFluid_Impl.hpp"
#include "../../model/WaterToAirComponent.hpp"
#include "../../model/WaterToAirComponent_Impl.hpp"
#include "../../model/WaterToWaterComponent.hpp"
#include "../../model/WaterToWaterComponent_Impl.hpp"
#include "../../model/CoilHeatingWaterBaseboard.hpp"
#include "../../model/CoilHeatingWaterBaseboard_Impl.hpp"
#include "../../model/CoilHeatingWaterBaseboardRadiant.hpp"
#include "../../model/CoilHeatingWaterBaseboardRadiant_Impl.hpp"
#include "../../model/CoilCoolingWaterPanelRadiant.hpp"
#include "../../model/CoilCoolingWaterPanelRadiant_Impl.hpp"
#include "../../model/CoilCoolingCooledBeam.hpp"
#include "../../model/CoilCoolingCooledBeam_Impl.hpp"
#include "../../model/CoilCoolingFourPipeBeam.hpp"
#include "../../model/CoilCoolingFourPipeBeam_Impl.hpp"
#include "../../model/CoilHeatingFourPipeBeam.hpp"
#include "../../model/CoilHeatingFourPipeBeam_Impl.hpp"
#include "../../model/StraightComponent.hpp"
#include "../../model/StraightComponent_Impl.hpp"
#include "../../model/CoilHeatingLowTempRadiantConstFlow.hpp"
#include "../../model/CoilHeatingLowTempRadiantConstFlow_Impl.hpp"
#include "../../model/CoilCoolingLowTempRadiantConstFlow.hpp"
#include "../../model/CoilCoolingLowTempRadiantConstFlow_Impl.hpp"
#include "../../model/CoilHeatingLowTempRadiantVarFlow.hpp"
#include "../../model/CoilHeatingLowTempRadiantVarFlow_Impl.hpp"
#include "../../model/CoilCoolingLowTempRadiantVarFlow.hpp"
#include "../../model/CoilCoolingLowTempRadiantVarFlow_Impl.hpp"
#include "../../model/ZoneHVACComponent.hpp"
#include "../../model/ZoneHVACComponent_Impl.hpp"
#include "../../model/SetpointManager.hpp"
#include "../../model/SetpointManagerScheduledDualSetpoint.hpp"
#include "../../model/SetpointManagerScheduledDualSetpoint_Impl.hpp"
#include "../../model/LifeCycleCost.hpp"
#include "../../utilities/idf/IdfExtensibleGroup.hpp"
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/PlantLoop_FieldEnums.hxx>
#include <utilities/idd/BranchList_FieldEnums.hxx>
#include <utilities/idd/Branch_FieldEnums.hxx>
#include <utilities/idd/ConnectorList_FieldEnums.hxx>
#include <utilities/idd/Connector_Splitter_FieldEnums.hxx>
#include <utilities/idd/Connector_Mixer_FieldEnums.hxx>
#include <utilities/idd/Pipe_Adiabatic_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentOperationSchemes_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentOperation_HeatingLoad_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentOperation_CoolingLoad_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentOperation_ComponentSetpoint_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentOperation_Uncontrolled_FieldEnums.hxx>
#include <utilities/idd/PlantEquipmentList_FieldEnums.hxx>
#include <utilities/idd/Sizing_Plant_FieldEnums.hxx>
#include <utilities/idd/AirTerminal_SingleDuct_ConstantVolume_CooledBeam_FieldEnums.hxx>
#include <utilities/idd/AirTerminal_SingleDuct_ConstantVolume_FourPipeBeam_FieldEnums.hxx>
#include <utilities/idd/ZoneHVAC_AirDistributionUnit_FieldEnums.hxx>
#include <utilities/idd/FluidProperties_Name_FieldEnums.hxx>
#include <utilities/idd/AvailabilityManagerAssignmentList_FieldEnums.hxx>
#include "../../utilities/core/Assert.hpp"
using namespace openstudio::model;
using namespace std;
namespace openstudio {
namespace energyplus {
IdfObject ForwardTranslator::populateBranch(IdfObject& branchIdfObject, std::vector<ModelObject>& modelObjects, Loop& loop, bool isSupplyBranch) {
if (modelObjects.size() > 0) {
int i = 0;
for (auto& modelObject : modelObjects) {
boost::optional<Node> inletNode;
boost::optional<Node> outletNode;
std::string objectName;
std::string iddType;
//translate and map each model object
//in most cases, the name and idd object type come directly from the resulting idfObject
if (boost::optional<IdfObject> idfObject = this->translateAndMapModelObject(modelObject)) {
objectName = idfObject->name().get();
iddType = idfObject->iddObject().name();
}
if (modelObject.optionalCast<Node>()) {
// Skip nodes we don't want them showing up on branches
continue;
}
if (auto straightComponent = modelObject.optionalCast<StraightComponent>()) {
inletNode = straightComponent->inletModelObject()->optionalCast<Node>();
outletNode = straightComponent->outletModelObject()->optionalCast<Node>();
//special case for ZoneHVAC:Baseboard:Convective:Water. In E+, this object appears on both the
//zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects:
//ZoneHVACBaseboardConvectiveWater and CoilHeatingWaterBaseboard. The ZoneHVAC goes onto the zone and
//has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need
//to put the name of the containing ZoneHVACBaseboardConvectiveWater onto the branch.
if (boost::optional<CoilHeatingWaterBaseboard> coilBB = modelObject.optionalCast<CoilHeatingWaterBaseboard>()) {
if (boost::optional<ZoneHVACComponent> contZnBB = coilBB->containingZoneHVACComponent()) {
//translate and map containingZoneHVACBBConvWater
if (boost::optional<IdfObject> idfContZnBB = this->translateAndMapModelObject(*contZnBB)) {
//Get the name and the idd object from the idf object version of this
objectName = idfContZnBB->name().get();
iddType = idfContZnBB->iddObject().name();
}
}
}
//special case for ZoneHVAC:Baseboard:RadiantConvective:Water. In E+, this object appears on both the
//zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects:
//ZoneHVACBaseboardRadiantConvectiveWater and CoilHeatingWaterBaseboardRadiant. The ZoneHVAC goes onto the zone and
//has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need
//to put the name of the containing ZoneHVACBaseboardRadiantConvectiveWater onto the branch.
if (auto coilBBRad = modelObject.optionalCast<CoilHeatingWaterBaseboardRadiant>()) {
if (auto contZnBBRad = coilBBRad->containingZoneHVACComponent()) {
//translate and map containingZoneHVACBBRadConvWater
if (auto idfContZnBBRad = this->translateAndMapModelObject(*contZnBBRad)) {
//Get the name and the idd object from the idf object version of this
objectName = idfContZnBBRad->name().get();
iddType = idfContZnBBRad->iddObject().name();
}
}
}
//special case for ZoneHVAC:CoolingPanel:RadiantConvective:Water. In E+, this object appears on both the
//zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects:
//ZoneHVACCoolingPanelRadiantConvectiveWater and CoilCoolingWaterPanelRadiant. The ZoneHVAC goes onto the zone and
//has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need
//to put the name of the containing ZoneHVACCoolingPanelRadiantConvectiveWater onto the branch.
if (auto coilCPRad = modelObject.optionalCast<CoilCoolingWaterPanelRadiant>()) {
if (auto contZnCPRad = coilCPRad->containingZoneHVACComponent()) {
//translate and map containingZoneHVACBBRadConvWater
if (auto idfContZnCPRad = this->translateAndMapModelObject(*contZnCPRad)) {
//Get the name and the idd object from the idf object version of this
objectName = idfContZnCPRad->name().get();
iddType = idfContZnCPRad->iddObject().name();
}
}
}
//special case for AirTerminalSingleDuctConstantVolumeChilledBeam
if (boost::optional<CoilCoolingCooledBeam> coilCB = modelObject.optionalCast<CoilCoolingCooledBeam>()) {
if (boost::optional<StraightComponent> airTerm = coilCB->containingStraightComponent()) {
boost::optional<IdfObject> idfAirDistUnit = this->translateAndMapModelObject(*airTerm);
//translate and map containingStraightComponent
if (idfAirDistUnit) {
//Get the name and idd type of the air terminal inside the air distribution unit
objectName = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalName).get();
iddType = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalObjectType).get();
}
}
}
//special case for AirTerminalSingleDuctConstantVolumeFourPipeBeam: Cooling Side
if (boost::optional<CoilCoolingFourPipeBeam> coilFPB = modelObject.optionalCast<CoilCoolingFourPipeBeam>()) {
if (boost::optional<StraightComponent> airTerm = coilFPB->containingStraightComponent()) {
boost::optional<IdfObject> idfAirDistUnit = this->translateAndMapModelObject(*airTerm);
//translate and map containingStraightComponent
if (idfAirDistUnit) {
//Get the name and idd type of the air terminal inside the air distribution unit
objectName = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalName).get();
iddType = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalObjectType).get();
}
}
}
//special case for AirTerminalSingleDuctConstantVolumeFourPipeBeam: Cooling Side
if (boost::optional<CoilHeatingFourPipeBeam> coilFPB = modelObject.optionalCast<CoilHeatingFourPipeBeam>()) {
if (boost::optional<StraightComponent> airTerm = coilFPB->containingStraightComponent()) {
boost::optional<IdfObject> idfAirDistUnit = this->translateAndMapModelObject(*airTerm);
//translate and map containingStraightComponent
if (idfAirDistUnit) {
//Get the name and idd type of the air terminal inside the air distribution unit
objectName = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalName).get();
iddType = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalObjectType).get();
}
}
}
//special case for ZoneHVAC:LowTemperatureRadiant:ConstantFlow and ZoneHVAC:LowTemperatureRadiant:VariableFlow. In E+, this object appears on both the
//zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects:
//ZoneHVACBaseboardConvectiveWater and CoilHeatingWaterBaseboard. The ZoneHVAC goes onto the zone and
//has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need
//to put the name of the containing ZoneHVACBaseboardConvectiveWater onto the branch.
if (boost::optional<CoilHeatingLowTempRadiantConstFlow> coilHLRC = modelObject.optionalCast<CoilHeatingLowTempRadiantConstFlow>()) {
if (boost::optional<ZoneHVACComponent> znLowTempRadConst = coilHLRC->containingZoneHVACComponent()) {
//translate and map containingZoneHVACBBConvWater
if (boost::optional<IdfObject> idfZnLowTempRadConst = this->translateAndMapModelObject(*znLowTempRadConst)) {
//Get the name and the idd object from the idf object version of this
objectName = idfZnLowTempRadConst->name().get();
iddType = idfZnLowTempRadConst->iddObject().name();
}
}
}
if (boost::optional<CoilCoolingLowTempRadiantConstFlow> coilCLRC = modelObject.optionalCast<CoilCoolingLowTempRadiantConstFlow>()) {
if (boost::optional<ZoneHVACComponent> znLowTempRadConst = coilCLRC->containingZoneHVACComponent()) {
//translate and map containingZoneHVACBBConvWater
if (boost::optional<IdfObject> idfZnLowTempRadConst = this->translateAndMapModelObject(*znLowTempRadConst)) {
//Get the name and the idd object from the idf object version of this
objectName = idfZnLowTempRadConst->name().get();
iddType = idfZnLowTempRadConst->iddObject().name();
}
}
}
if (boost::optional<CoilHeatingLowTempRadiantVarFlow> coilHLRC = modelObject.optionalCast<CoilHeatingLowTempRadiantVarFlow>()) {
if (boost::optional<ZoneHVACComponent> znLowTempRadVar = coilHLRC->containingZoneHVACComponent()) {
//translate and map containingZoneHVACBBConvWater
if (boost::optional<IdfObject> idfZnLowTempRadVar = this->translateAndMapModelObject(*znLowTempRadVar)) {
//Get the name and the idd object from the idf object version of this
objectName = idfZnLowTempRadVar->name().get();
iddType = idfZnLowTempRadVar->iddObject().name();
}
}
}
if (boost::optional<CoilCoolingLowTempRadiantVarFlow> coilCLRC = modelObject.optionalCast<CoilCoolingLowTempRadiantVarFlow>()) {
if (boost::optional<ZoneHVACComponent> znLowTempRadVar = coilCLRC->containingZoneHVACComponent()) {
//translate and map containingZoneHVACBBConvWater
if (boost::optional<IdfObject> idfZnLowTempRadVar = this->translateAndMapModelObject(*znLowTempRadVar)) {
//Get the name and the idd object from the idf object version of this
objectName = idfZnLowTempRadVar->name().get();
iddType = idfZnLowTempRadVar->iddObject().name();
}
}
}
//special case for Generator:MicroTurbine.
//In OpenStudio, this object was broken into 2 objects:
//GeneratorMicroTurbine and GeneratorMicroTurbineHeatRecovery.
//The GeneratorMicroTurbineHeatRecovery goes onto the plantloop. In order to get the correct translation to E+, we need
//to put the name of the linked GeneratorMicroTurbine onto the branch.
if (boost::optional<GeneratorMicroTurbineHeatRecovery> mchpHR = modelObject.optionalCast<GeneratorMicroTurbineHeatRecovery>()) {
if (boost::optional<GeneratorMicroTurbine> mchp = mchpHR->generatorMicroTurbine()) {
//translate and map containingZoneHVACBBConvWater
if (boost::optional<IdfObject> idfmchp = this->translateAndMapModelObject(*mchp)) {
//Get the name and the idd object from the idf object version of this
objectName = idfmchp->name().get();
iddType = idfmchp->iddObject().name();
}
}
}
} else if (auto waterToAirComponent = modelObject.optionalCast<WaterToAirComponent>()) {
if (loop.optionalCast<PlantLoop>()) {
inletNode = waterToAirComponent->waterInletModelObject()->optionalCast<Node>();
outletNode = waterToAirComponent->waterOutletModelObject()->optionalCast<Node>();
} else {
inletNode = waterToAirComponent->airInletModelObject()->optionalCast<Node>();
outletNode = waterToAirComponent->airOutletModelObject()->optionalCast<Node>();
}
} else if (auto waterToWaterComponent = modelObject.optionalCast<WaterToWaterComponent>()) {
// Special case for CentralHeatPump.
// Unlike other WaterToWaterComponent with a tertiary loop (ChillerAbsorption, ChillerAbsorptionIndirect, ChillerElectricEIR, ChillerElectricReformulatedEIR) which all have
// tertiary loop = demand side (so 2 demand side loops and one supply), CentralHeatPumpSystem has tertiary = supply (2 supply side and 1
// demand side loops)
if (auto central_hp = modelObject.optionalCast<CentralHeatPumpSystem>()) {
auto coolingLoop = central_hp->coolingPlantLoop();
auto heatingLoop = central_hp->heatingPlantLoop();
auto sourceLoop = central_hp->sourcePlantLoop();
// supply = cooling Loop
if (loop.handle() == coolingLoop->handle()) {
inletNode = waterToWaterComponent->supplyInletModelObject()->optionalCast<Node>();
outletNode = waterToWaterComponent->supplyOutletModelObject()->optionalCast<Node>();
// tertiary = heating loop
} else if (loop.handle() == heatingLoop->handle()) {
inletNode = waterToWaterComponent->tertiaryInletModelObject()->optionalCast<Node>();
outletNode = waterToWaterComponent->tertiaryOutletModelObject()->optionalCast<Node>();
// demand = source loop
} else if (loop.handle() == sourceLoop->handle()) {
inletNode = waterToWaterComponent->demandInletModelObject()->optionalCast<Node>();
outletNode = waterToWaterComponent->demandOutletModelObject()->optionalCast<Node>();
}
// Regular case
} else if (isSupplyBranch) {
inletNode = waterToWaterComponent->supplyInletModelObject()->optionalCast<Node>();
outletNode = waterToWaterComponent->supplyOutletModelObject()->optionalCast<Node>();
} else {
if (auto tertiaryInletModelObject = waterToWaterComponent->tertiaryInletModelObject()) {
if (auto tertiaryInletNode = tertiaryInletModelObject->optionalCast<Node>()) {
if (loop.demandComponent(tertiaryInletNode->handle())) {
inletNode = tertiaryInletNode;
if (auto tertiaryOutletModelObject = waterToWaterComponent->tertiaryOutletModelObject()) {
outletNode = tertiaryOutletModelObject->optionalCast<Node>();
}
}
}
}
if (!inletNode) {
inletNode = waterToWaterComponent->demandInletModelObject()->optionalCast<Node>();
outletNode = waterToWaterComponent->demandOutletModelObject()->optionalCast<Node>();
}
}
//special case for WaterHeater:HeatPump. In E+, this object appears on both the
//zonehvac:equipmentlist and the branch. In OpenStudio the tank (WaterHeater:Mixed)
//is attached to the plant and the WaterHeaterHeatPump is connected to the zone and zonehvac equipment list.
//Here we resolve all of that since it is the WaterHeaterHeatPump that must show up on both
if (auto tank = modelObject.optionalCast<WaterHeaterMixed>()) {
// containingZoneHVACComponent can be WaterHeaterHeatPump
if (auto hpwh = tank->containingZoneHVACComponent()) {
//translate and map containingZoneHVAC
if (auto hpwhIDF = translateAndMapModelObject(hpwh.get())) {
//Get the name and the idd object from the idf object version of this
objectName = hpwhIDF->name().get();
iddType = hpwhIDF->iddObject().name();
}
}
}
if (auto tank = modelObject.optionalCast<WaterHeaterStratified>()) {
// containingZoneHVACComponent can be WaterHeaterHeatPump
if (auto hpwh = tank->containingZoneHVACComponent()) {
//translate and map containingZoneHVAC
if (auto hpwhIDF = translateAndMapModelObject(hpwh.get())) {
//Get the name and the idd object from the idf object version of this
objectName = hpwhIDF->name().get();
iddType = hpwhIDF->iddObject().name();
}
}
}
} else if (auto oaSystem = modelObject.optionalCast<AirLoopHVACOutdoorAirSystem>()) {
inletNode = oaSystem->returnAirModelObject()->optionalCast<Node>();
outletNode = oaSystem->mixedAirModelObject()->optionalCast<Node>();
} else if (auto unitary = modelObject.optionalCast<ZoneHVACComponent>()) {
inletNode = unitary->inletNode()->optionalCast<Node>();
outletNode = unitary->outletNode()->optionalCast<Node>();
}
if (inletNode && outletNode) {
IdfExtensibleGroup eg = branchIdfObject.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, iddType);
eg.setString(BranchExtensibleFields::ComponentName, objectName);
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNode->name().get());
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNode->name().get());
}
i++;
}
}
return branchIdfObject;
}
boost::optional<IdfObject> ForwardTranslator::translatePlantLoop(PlantLoop& plantLoop) {
// Create a new IddObjectType::PlantLoop
IdfObject idfObject(IddObjectType::PlantLoop);
m_idfObjects.push_back(idfObject);
for (LifeCycleCost lifeCycleCost : plantLoop.lifeCycleCosts()) {
translateAndMapModelObject(lifeCycleCost);
}
OptionalModelObject temp;
boost::optional<std::string> s;
boost::optional<double> value;
// Name
if ((s = plantLoop.name())) {
idfObject.setName(s.get());
}
// Fluid Type
if ((s = plantLoop.fluidType())) {
if (istringEqual(s.get(), "PropyleneGlycol") || istringEqual(s.get(), "EthyleneGlycol")) {
idfObject.setString(PlantLoopFields::FluidType, "UserDefinedFluidType");
boost::optional<int> gc = plantLoop.glycolConcentration();
if (gc) {
boost::optional<IdfObject> fluidProperties = createFluidProperties(s.get(), gc.get());
if (fluidProperties) {
boost::optional<std::string> fluidPropertiesName = fluidProperties->getString(FluidProperties_NameFields::FluidName, true);
if (fluidPropertiesName) {
idfObject.setString(PlantLoopFields::UserDefinedFluidType, fluidPropertiesName.get());
}
}
}
} else {
idfObject.setString(PlantLoopFields::FluidType, s.get());
}
}
// Loop Temperature Setpoint Node Name
if (boost::optional<Node> node = plantLoop.loopTemperatureSetpointNode()) {
idfObject.setString(PlantLoopFields::LoopTemperatureSetpointNodeName, node->name().get());
}
// Maximum Loop Temperature
if ((value = plantLoop.maximumLoopTemperature())) {
idfObject.setDouble(PlantLoopFields::MaximumLoopTemperature, value.get());
}
// Minimum Loop Temperature
if ((value = plantLoop.minimumLoopTemperature())) {
idfObject.setDouble(PlantLoopFields::MinimumLoopTemperature, value.get());
}
// Maximum Loop Flow Rate
if (plantLoop.isMaximumLoopFlowRateAutosized()) {
idfObject.setString(PlantLoopFields::MaximumLoopFlowRate, "Autosize");
} else if ((value = plantLoop.maximumLoopFlowRate())) {
idfObject.setDouble(PlantLoopFields::MaximumLoopFlowRate, value.get());
}
// Minimum Loop Flow Rate
if (plantLoop.isMinimumLoopFlowRateAutosized()) {
idfObject.setString(PlantLoopFields::MinimumLoopFlowRate, "Autosize");
} else if ((value = plantLoop.minimumLoopFlowRate())) {
idfObject.setDouble(PlantLoopFields::MinimumLoopFlowRate, value.get());
}
// LoadDistributionScheme
{
auto scheme = plantLoop.loadDistributionScheme();
idfObject.setString(PlantLoopFields::LoadDistributionScheme, scheme);
}
// AvailabilityManagerAssignmentList
{
// The AvailabilityManagerAssignment list is translated by itself, we just need to set its name on the right IDF field
AvailabilityManagerAssignmentList avmList = plantLoop.getImpl<openstudio::model::detail::PlantLoop_Impl>()->availabilityManagerAssignmentList();
// If the avmList isn't empty of just with an HybridVentilation, it should have been translated
if (boost::optional<IdfObject> _avmList = this->translateAndMapModelObject(avmList)) {
idfObject.setString(PlantLoopFields::AvailabilityManagerListName, _avmList->name().get());
}
}
// PlantLoopDemandCalculationScheme
{
auto spms = plantLoop.supplyOutletNode().setpointManagers();
if (subsetCastVector<model::SetpointManagerScheduledDualSetpoint>(spms).empty()) {
idfObject.setString(PlantLoopFields::PlantLoopDemandCalculationScheme, "SingleSetpoint");
} else {
idfObject.setString(PlantLoopFields::PlantLoopDemandCalculationScheme, "DualSetpointDeadband");
}
}
// Plant Loop Volume
if (plantLoop.isPlantLoopVolumeAutocalculated()) {
idfObject.setString(PlantLoopFields::PlantLoopVolume, "Autocalculate");
} else if ((value = plantLoop.plantLoopVolume())) {
idfObject.setDouble(PlantLoopFields::PlantLoopVolume, value.get());
}
// Common Pipe Simulation
if ((s = plantLoop.commonPipeSimulation())) {
idfObject.setString(PlantLoopFields::CommonPipeSimulation, s.get());
}
// Inlet/Outlet Nodes
idfObject.setString(PlantLoopFields::PlantSideInletNodeName, plantLoop.supplyInletNode().name().get());
idfObject.setString(PlantLoopFields::PlantSideOutletNodeName, plantLoop.supplyOutletNode().name().get());
idfObject.setString(PlantLoopFields::DemandSideInletNodeName, plantLoop.demandInletNode().name().get());
idfObject.setString(PlantLoopFields::DemandSideOutletNodeName, plantLoop.demandOutletNode().name().get());
auto supplyComponents = plantLoop.supplyComponents();
SizingPlant sizingPlant = plantLoop.sizingPlant();
translateAndMapModelObject(sizingPlant);
// Mark where we want the plant operation schemes to go
// Don't actually translate yet because we don't want the components to show up yet
// auto operationSchemeLocation = std::distance(m_idfObjects.begin(),m_idfObjects.end());
// Supply Side
IdfObject _supplyBranchList(IddObjectType::BranchList);
_supplyBranchList.setName(plantLoop.name().get() + " Supply Branches");
_supplyBranchList.clearExtensibleGroups();
m_idfObjects.push_back(_supplyBranchList);
idfObject.setString(PlantLoopFields::PlantSideBranchListName, _supplyBranchList.name().get());
IdfObject _supplyConnectorList(IddObjectType::ConnectorList);
_supplyConnectorList.setName(plantLoop.name().get() + " Supply Connector List");
m_idfObjects.push_back(_supplyConnectorList);
idfObject.setString(PlantLoopFields::PlantSideConnectorListName, _supplyConnectorList.name().get());
Splitter supplySplitter = plantLoop.supplySplitter();
Mixer supplyMixer = plantLoop.supplyMixer();
Node supplyInletNode = plantLoop.supplyInletNode();
Node supplyOutletNode = plantLoop.supplyOutletNode();
IdfObject _supplySplitter(IddObjectType::Connector_Splitter);
_supplySplitter.clearExtensibleGroups();
_supplySplitter.setName(plantLoop.name().get() + " Supply Splitter");
m_idfObjects.push_back(_supplySplitter);
ExtensibleIndex ei2(0, 0);
ei2.group = 0;
ei2.field = ConnectorListExtensibleFields::ConnectorObjectType;
_supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplySplitter.iddObject().name());
ei2.field = ConnectorListExtensibleFields::ConnectorName;
_supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplySplitter.name().get());
IdfObject _supplyMixer(IddObjectType::Connector_Mixer);
_supplyMixer.clearExtensibleGroups();
_supplyMixer.setName(plantLoop.name().get() + " Supply Mixer");
m_idfObjects.push_back(_supplyMixer);
ei2.group = 1;
ei2.field = ConnectorListExtensibleFields::ConnectorObjectType;
_supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplyMixer.iddObject().name());
ei2.field = ConnectorListExtensibleFields::ConnectorName;
_supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplyMixer.name().get());
// Supply inlet branch
IdfObject _supplyInletBranch(IddObjectType::Branch);
_supplyInletBranch.setName(plantLoop.name().get() + " Supply Inlet Branch");
_supplyInletBranch.clearExtensibleGroups();
IdfExtensibleGroup eg = _supplyBranchList.pushExtensibleGroup();
eg.setString(BranchListExtensibleFields::BranchName, _supplyInletBranch.name().get());
_supplySplitter.setString(Connector_SplitterFields::InletBranchName, _supplyInletBranch.name().get());
m_idfObjects.push_back(_supplyInletBranch);
std::vector<ModelObject> supplyInletModelObjects;
supplyInletModelObjects = plantLoop.supplyComponents(supplyInletNode, supplySplitter);
OS_ASSERT(supplyInletModelObjects.size() >= 2);
if (supplyInletModelObjects.size() > 2u) {
populateBranch(_supplyInletBranch, supplyInletModelObjects, plantLoop, true);
} else {
IdfObject pipe(IddObjectType::Pipe_Adiabatic);
pipe.setName(plantLoop.name().get() + " Supply Inlet Pipe");
m_idfObjects.push_back(pipe);
std::string inletNodeName = plantLoop.supplyInletNode().name().get();
std::string outletNodeName = plantLoop.name().get() + " Supply Inlet Pipe Node";
pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName);
pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName);
IdfExtensibleGroup eg = _supplyInletBranch.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name());
eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get());
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName);
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName);
}
// Populate supply equipment branches
std::vector<model::ModelObject> splitterOutletObjects = supplySplitter.outletModelObjects();
std::vector<model::ModelObject> mixerInletObjects = supplyMixer.inletModelObjects();
auto it2 = mixerInletObjects.begin();
unsigned i = 0;
for (auto& splitterOutletObject : splitterOutletObjects) {
i++;
std::stringstream ss;
ss << i;
std::string istring = ss.str();
model::HVACComponent comp1 = splitterOutletObject.optionalCast<model::HVACComponent>().get();
model::HVACComponent comp2 = it2->optionalCast<model::HVACComponent>().get();
std::vector<model::ModelObject> allComponents = plantLoop.supplyComponents(comp1, comp2);
IdfObject _equipmentBranch(IddObjectType::Branch);
_equipmentBranch.clearExtensibleGroups();
_equipmentBranch.setName(plantLoop.name().get() + " Supply Branch " + istring);
m_idfObjects.push_back(_equipmentBranch);
eg = _supplySplitter.pushExtensibleGroup();
eg.setString(Connector_SplitterExtensibleFields::OutletBranchName, _equipmentBranch.name().get());
eg = _supplyMixer.pushExtensibleGroup();
eg.setString(Connector_MixerExtensibleFields::InletBranchName, _equipmentBranch.name().get());
eg = _supplyBranchList.pushExtensibleGroup();
eg.setString(BranchListExtensibleFields::BranchName, _equipmentBranch.name().get());
if (allComponents.size() > 2u) {
populateBranch(_equipmentBranch, allComponents, plantLoop, true);
} else {
IdfObject pipe(IddObjectType::Pipe_Adiabatic);
pipe.setName(plantLoop.name().get() + " Supply Branch " + istring + " Pipe");
m_idfObjects.push_back(pipe);
std::string inletNodeName = pipe.name().get() + " Inlet Node";
std::string outletNodeName = pipe.name().get() + " Outlet Node";
pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName);
pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName);
IdfExtensibleGroup eg = _equipmentBranch.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name());
eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get());
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName);
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName);
}
++it2;
}
// Populate supply outlet branch
IdfObject _supplyOutletBranch(IddObjectType::Branch);
_supplyOutletBranch.setName(plantLoop.name().get() + " Supply Outlet Branch");
_supplyOutletBranch.clearExtensibleGroups();
eg = _supplyBranchList.pushExtensibleGroup();
eg.setString(BranchListExtensibleFields::BranchName, _supplyOutletBranch.name().get());
_supplyMixer.setString(Connector_MixerFields::OutletBranchName, _supplyOutletBranch.name().get());
m_idfObjects.push_back(_supplyOutletBranch);
std::vector<ModelObject> supplyOutletModelObjects;
supplyOutletModelObjects = plantLoop.supplyComponents(supplyMixer, supplyOutletNode);
OS_ASSERT(supplyOutletModelObjects.size() >= 2);
if (supplyOutletModelObjects.size() > 2u) {
populateBranch(_supplyOutletBranch, supplyOutletModelObjects, plantLoop, true);
} else {
IdfObject pipe(IddObjectType::Pipe_Adiabatic);
pipe.setName(plantLoop.name().get() + " Supply Outlet Pipe");
m_idfObjects.push_back(pipe);
std::string inletNodeName = plantLoop.name().get() + " Supply Outlet Pipe Node";
std::string outletNodeName = plantLoop.supplyOutletNode().name().get();
pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName);
pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName);
IdfExtensibleGroup eg = _supplyOutletBranch.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name());
eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get());
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName);
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName);
}
// Demand Side
IdfObject _demandBranchList(IddObjectType::BranchList);
_demandBranchList.setName(plantLoop.name().get() + " Demand Branches");
_demandBranchList.clearExtensibleGroups();
m_idfObjects.push_back(_demandBranchList);
idfObject.setString(PlantLoopFields::DemandSideBranchListName, _demandBranchList.name().get());
IdfObject _demandConnectorList(IddObjectType::ConnectorList);
_demandConnectorList.setName(plantLoop.name().get() + " Demand Connector List");
m_idfObjects.push_back(_demandConnectorList);
idfObject.setString(PlantLoopFields::DemandSideConnectorListName, _demandConnectorList.name().get());
Splitter demandSplitter = plantLoop.demandSplitter();
Mixer demandMixer = plantLoop.demandMixer();
Node demandInletNode = plantLoop.demandInletNode();
Node demandOutletNode = plantLoop.demandOutletNode();
IdfObject _demandSplitter(IddObjectType::Connector_Splitter);
_demandSplitter.clearExtensibleGroups();
_demandSplitter.setName(plantLoop.name().get() + " Demand Splitter");
m_idfObjects.push_back(_demandSplitter);
ExtensibleIndex ei(0, 0);
ei.group = 0;
ei.field = ConnectorListExtensibleFields::ConnectorObjectType;
_demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandSplitter.iddObject().name());
ei.field = ConnectorListExtensibleFields::ConnectorName;
_demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandSplitter.name().get());
IdfObject _demandMixer(IddObjectType::Connector_Mixer);
_demandMixer.clearExtensibleGroups();
_demandMixer.setName(plantLoop.name().get() + " Demand Mixer");
m_idfObjects.push_back(_demandMixer);
ei.group = 1;
ei.field = ConnectorListExtensibleFields::ConnectorObjectType;
_demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandMixer.iddObject().name());
ei.field = ConnectorListExtensibleFields::ConnectorName;
_demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandMixer.name().get());
// Demand inlet branch
IdfObject _demandInletBranch(IddObjectType::Branch);
_demandInletBranch.setName(plantLoop.name().get() + " Demand Inlet Branch");
_demandInletBranch.clearExtensibleGroups();
eg = _demandBranchList.pushExtensibleGroup();
eg.setString(BranchListExtensibleFields::BranchName, _demandInletBranch.name().get());
_demandSplitter.setString(Connector_SplitterFields::InletBranchName, _demandInletBranch.name().get());
m_idfObjects.push_back(_demandInletBranch);
std::vector<ModelObject> demandInletModelObjects;
demandInletModelObjects = plantLoop.demandComponents(demandInletNode, demandSplitter);
OS_ASSERT(demandInletModelObjects.size() >= 2u);
if (demandInletModelObjects.size() > 2u) {
populateBranch(_demandInletBranch, demandInletModelObjects, plantLoop, false);
} else {
IdfObject pipe(IddObjectType::Pipe_Adiabatic);
pipe.setName(plantLoop.name().get() + " Demand Inlet Pipe");
m_idfObjects.push_back(pipe);
std::string inletNodeName = plantLoop.demandInletNode().name().get();
std::string outletNodeName = plantLoop.name().get() + " Demand Inlet Pipe Node";
pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName);
pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName);
IdfExtensibleGroup eg = _demandInletBranch.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name());
eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get());
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName);
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName);
}
// Populate equipment branches
splitterOutletObjects = demandSplitter.outletModelObjects();
mixerInletObjects = demandMixer.inletModelObjects();
it2 = mixerInletObjects.begin();
i = 0;
for (auto& splitterOutletObject : splitterOutletObjects) {
i++;
std::stringstream ss;
ss << i;
std::string istring = ss.str();
model::HVACComponent comp1 = splitterOutletObject.optionalCast<model::HVACComponent>().get();
model::HVACComponent comp2 = it2->optionalCast<model::HVACComponent>().get();
std::vector<model::ModelObject> allComponents = plantLoop.demandComponents(comp1, comp2);
IdfObject _equipmentBranch(IddObjectType::Branch);
_equipmentBranch.clearExtensibleGroups();
_equipmentBranch.setName(plantLoop.name().get() + " Demand Branch " + istring);
m_idfObjects.push_back(_equipmentBranch);
eg = _demandSplitter.pushExtensibleGroup();
eg.setString(Connector_SplitterExtensibleFields::OutletBranchName, _equipmentBranch.name().get());
eg = _demandMixer.pushExtensibleGroup();
eg.setString(Connector_MixerExtensibleFields::InletBranchName, _equipmentBranch.name().get());
eg = _demandBranchList.pushExtensibleGroup();
eg.setString(BranchListExtensibleFields::BranchName, _equipmentBranch.name().get());
if (allComponents.size() > 2u) {
populateBranch(_equipmentBranch, allComponents, plantLoop, false);
} else {
IdfObject pipe(IddObjectType::Pipe_Adiabatic);
pipe.setName(plantLoop.name().get() + " Demand Branch " + istring + " Pipe");
m_idfObjects.push_back(pipe);
std::string inletNodeName = pipe.name().get() + " Inlet Node";
std::string outletNodeName = pipe.name().get() + " Outlet Node";
pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName);
pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName);
IdfExtensibleGroup eg = _equipmentBranch.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name());
eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get());
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName);
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName);
}
++it2;
}
// Install a bypass branch with a pipe
if (splitterOutletObjects.size() > 0u) {
IdfObject _equipmentBranch(IddObjectType::Branch);
_equipmentBranch.clearExtensibleGroups();
_equipmentBranch.setName(plantLoop.name().get() + " Demand Bypass Branch");
m_idfObjects.push_back(_equipmentBranch);
eg = _demandSplitter.pushExtensibleGroup();
eg.setString(Connector_SplitterExtensibleFields::OutletBranchName, _equipmentBranch.name().get());
eg = _demandMixer.pushExtensibleGroup();
eg.setString(Connector_MixerExtensibleFields::InletBranchName, _equipmentBranch.name().get());
eg = _demandBranchList.pushExtensibleGroup();
eg.setString(BranchListExtensibleFields::BranchName, _equipmentBranch.name().get());
IdfObject pipe(IddObjectType::Pipe_Adiabatic);
pipe.setName(plantLoop.name().get() + " Demand Bypass Pipe");
m_idfObjects.push_back(pipe);
std::string inletNodeName = pipe.name().get() + " Inlet Node";
std::string outletNodeName = pipe.name().get() + " Outlet Node";
pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName);
pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName);
IdfExtensibleGroup eg = _equipmentBranch.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name());
eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get());
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName);
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName);
}
// Populate demand outlet branch
IdfObject _demandOutletBranch(IddObjectType::Branch);
_demandOutletBranch.setName(plantLoop.name().get() + " Demand Outlet Branch");
_demandOutletBranch.clearExtensibleGroups();
eg = _demandBranchList.pushExtensibleGroup();
eg.setString(BranchListExtensibleFields::BranchName, _demandOutletBranch.name().get());
_demandMixer.setString(Connector_MixerFields::OutletBranchName, _demandOutletBranch.name().get());
m_idfObjects.push_back(_demandOutletBranch);
std::vector<ModelObject> demandOutletModelObjects;
demandOutletModelObjects = plantLoop.demandComponents(demandMixer, demandOutletNode);
OS_ASSERT(demandOutletModelObjects.size() >= 2u);
if (demandOutletModelObjects.size() > 2u) {
populateBranch(_demandOutletBranch, demandOutletModelObjects, plantLoop, false);
} else {
IdfObject pipe(IddObjectType::Pipe_Adiabatic);
pipe.setName(plantLoop.name().get() + " Demand Outlet Pipe");
m_idfObjects.push_back(pipe);
std::string inletNodeName = plantLoop.name().get() + " Demand Outlet Pipe Node";
std::string outletNodeName = plantLoop.demandOutletNode().name().get();
pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName);
pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName);
IdfExtensibleGroup eg = _demandOutletBranch.pushExtensibleGroup();
eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name());
eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get());
eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName);
eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName);
}
// Operation Scheme
// auto opSchemeStart = m_idfObjects.end();
const auto& operationSchemes = translatePlantEquipmentOperationSchemes(plantLoop);
OS_ASSERT(operationSchemes);
idfObject.setString(PlantLoopFields::PlantEquipmentOperationSchemeName, operationSchemes->name().get());
// auto opSchemeEnd = m_idfObjects.end();
//std::vector<IdfObject> opSchemeObjects(opSchemeStart,opSchemeEnd);
//m_idfObjects.erase(opSchemeStart,opSchemeEnd);
//m_idfObjects.insert(m_idfObjects.begin() + operationSchemeLocation,opSchemeObjects.begin(),opSchemeObjects.end());
return boost::optional<IdfObject>(idfObject);
}
} // namespace energyplus
} // namespace openstudio
| 52.597665 | 182 | 0.71306 | muehleisen |
c1b1b4df493e9cec2f39abd06ab30bd1b5f951d8 | 1,146 | cpp | C++ | codeground/8. 블럭 없애기.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | null | null | null | codeground/8. 블럭 없애기.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | null | null | null | codeground/8. 블럭 없애기.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | null | null | null |
/*
* codeground - Practice - 연습문제 - 8. 블럭 없애기
* 문제 : https://www.codeground.org/practice/practiceProblemList
* 시간복잡도 : O(N)
* 알고리즘 : DP
*/
#include <iostream>
#include <vector>
#include <algorithm>
#define inf 1e9
using namespace std;
int solve()
{
int n;
cin >> n;
vector<int> arr(n + 2, 0);
for (int i = 1; i <= n; i++)
scanf("%d", &arr[i]);
vector<int> d(n + 2, inf);//d[i] = i번째가 없어질 때까지 걸리는 시간
d[0] = d[n + 1] = 0;
//없어질 때까지 걸리는 시간은 양쪽의 영향을 받지만 한 번에 이를 탐색하긴 어려우므로
//왼쪽과 자신, 자신과 오른쪽을 탐색 두 번으로 각각 구해서 d배열을 채운다.
for (int i = 1; i <= n; i++)//(왼쪽, 자신) 비교
d[i] = min(d[i - 1] + 1, arr[i]);//d[i] = min(왼쪽이 없어지는데 걸리는 시간 + 1, 높이가 없어지는데 걸리는 시간)
for (int i = n; i >= 1; i--) //(자신, 오른쪽) 비교
d[i] = min(d[i], min(d[i + 1] + 1, arr[i]));
int ans = 0; //d배열의 최대값
for (int i = 1; i <= n; i++)
ans = max(ans, d[i]);
return ans;
}
int main(int argc, char** argv)
{
int T, test_case;
int Answer;
cin >> T;
for (test_case = 0; test_case < T; test_case++)
{
Answer = solve();
cout << "Case #" << test_case + 1 << endl;
cout << Answer << endl;
}
return 0;//Your program should return 0 on normal termination.
}
| 21.222222 | 87 | 0.557592 | Jeongseo21 |
c1b2d9c78cc8681e372856b32e7984e8cbae57e7 | 3,268 | cpp | C++ | mitsuba-af602c6fd98a/src/bsdfs/null.cpp | NTForked-ML/pbrs | 0b405d92c12d257e2581366542762c9f0c3facce | [
"MIT"
] | 139 | 2017-04-21T00:22:34.000Z | 2022-02-16T20:33:10.000Z | mitsuba-af602c6fd98a/src/bsdfs/null.cpp | NTForked-ML/pbrs | 0b405d92c12d257e2581366542762c9f0c3facce | [
"MIT"
] | 11 | 2017-08-15T18:22:59.000Z | 2019-07-01T05:44:41.000Z | mitsuba-af602c6fd98a/src/bsdfs/null.cpp | NTForked-ML/pbrs | 0b405d92c12d257e2581366542762c9f0c3facce | [
"MIT"
] | 30 | 2017-07-21T03:56:45.000Z | 2022-03-11T06:55:34.000Z | /*
This file is part of Mitsuba, a physically based rendering system.
Copyright (c) 2007-2014 by Wenzel Jakob and others.
Mitsuba is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License Version 3
as published by the Free Software Foundation.
Mitsuba is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <mitsuba/render/bsdf.h>
#include <mitsuba/hw/basicshader.h>
MTS_NAMESPACE_BEGIN
class Null : public BSDF {
public:
Null(const Properties &props)
: BSDF(props) { }
Null(Stream *stream, InstanceManager *manager)
: BSDF(stream, manager) {
configure();
}
void serialize(Stream *stream, InstanceManager *manager) const {
BSDF::serialize(stream, manager);
}
void configure() {
m_components.clear();
m_components.push_back(ENull | EFrontSide | EBackSide);
m_usesRayDifferentials = false;
BSDF::configure();
}
Spectrum eval(const BSDFSamplingRecord &bRec, EMeasure measure) const {
return Spectrum(((bRec.typeMask & ENull) && measure == EDiscrete) ? 1.0f : 0.0f);
}
Float pdf(const BSDFSamplingRecord &bRec, EMeasure measure) const {
return ((bRec.typeMask & ENull) && measure == EDiscrete) ? 1.0f : 0.0f;
}
Spectrum sample(BSDFSamplingRecord &bRec, const Point2 &_sample) const {
if (bRec.typeMask & ENull) {
bRec.wo = -bRec.wi;
bRec.sampledComponent = 0;
bRec.sampledType = ENull;
bRec.eta = 1.0f;
return Spectrum(1.0f);
} else {
return Spectrum(0.0f);
}
}
Spectrum sample(BSDFSamplingRecord &bRec, Float &pdf, const Point2 &_sample) const {
if (bRec.typeMask & ENull) {
bRec.wo = -bRec.wi;
bRec.sampledComponent = 0;
bRec.sampledType = ENull;
bRec.eta = 1.0f;
pdf = 1;
return Spectrum(1.0f);
} else {
return Spectrum(0.0f);
}
}
Float getRoughness(const Intersection &its, int component) const {
return 0.0f;
}
std::string toString() const {
return "Null[]";
}
Shader *createShader(Renderer *renderer) const;
MTS_DECLARE_CLASS()
};
// ================ Hardware shader implementation ================
/* Null shader-- render as a 'black box' */
class NullShader : public Shader {
public:
NullShader(Renderer *renderer) :
Shader(renderer, EBSDFShader) {
m_flags = ETransparent;
}
void generateCode(std::ostringstream &oss,
const std::string &evalName,
const std::vector<std::string> &depNames) const {
oss << "vec3 " << evalName << "(vec2 uv, vec3 wi, vec3 wo) {" << endl
<< " return vec3(0.0);" << endl
<< "}" << endl;
oss << "vec3 " << evalName << "_diffuse(vec2 uv, vec3 wi, vec3 wo) {" << endl
<< " return vec3(0.0);" << endl
<< "}" << endl;
}
MTS_DECLARE_CLASS()
};
Shader *Null::createShader(Renderer *renderer) const {
return new NullShader(renderer);
}
MTS_IMPLEMENT_CLASS(NullShader, false, Shader)
MTS_IMPLEMENT_CLASS_S(Null, false, BSDF)
MTS_EXPORT_PLUGIN(Null, "Null BSDF");
MTS_NAMESPACE_END
| 26.786885 | 85 | 0.680845 | NTForked-ML |
c1b2dda506c35560662cdca065997345243ec9c0 | 39,587 | cc | C++ | google/cloud/vision/v1/geometry.pb.cc | allquixotic/kynnaugh-cc | 8b4d0cdb7e6e3cae76aba43507bb56cee225c36f | [
"Apache-2.0"
] | 3 | 2017-01-09T10:45:00.000Z | 2018-12-18T19:57:13.000Z | google/cloud/vision/v1/geometry.pb.cc | allquixotic/kynnaugh-cc | 8b4d0cdb7e6e3cae76aba43507bb56cee225c36f | [
"Apache-2.0"
] | null | null | null | google/cloud/vision/v1/geometry.pb.cc | allquixotic/kynnaugh-cc | 8b4d0cdb7e6e3cae76aba43507bb56cee225c36f | [
"Apache-2.0"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/vision/v1/geometry.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "google/cloud/vision/v1/geometry.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace google {
namespace cloud {
namespace vision {
namespace v1 {
namespace {
const ::google::protobuf::Descriptor* Vertex_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
Vertex_reflection_ = NULL;
const ::google::protobuf::Descriptor* BoundingPoly_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
BoundingPoly_reflection_ = NULL;
const ::google::protobuf::Descriptor* Position_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
Position_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AssignDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto() {
protobuf_AddDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"google/cloud/vision/v1/geometry.proto");
GOOGLE_CHECK(file != NULL);
Vertex_descriptor_ = file->message_type(0);
static const int Vertex_offsets_[2] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Vertex, x_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Vertex, y_),
};
Vertex_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Vertex_descriptor_,
Vertex::internal_default_instance(),
Vertex_offsets_,
-1,
-1,
-1,
sizeof(Vertex),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Vertex, _internal_metadata_));
BoundingPoly_descriptor_ = file->message_type(1);
static const int BoundingPoly_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoundingPoly, vertices_),
};
BoundingPoly_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
BoundingPoly_descriptor_,
BoundingPoly::internal_default_instance(),
BoundingPoly_offsets_,
-1,
-1,
-1,
sizeof(BoundingPoly),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(BoundingPoly, _internal_metadata_));
Position_descriptor_ = file->message_type(2);
static const int Position_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Position, x_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Position, y_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Position, z_),
};
Position_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Position_descriptor_,
Position::internal_default_instance(),
Position_offsets_,
-1,
-1,
-1,
sizeof(Position),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Position, _internal_metadata_));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
Vertex_descriptor_, Vertex::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
BoundingPoly_descriptor_, BoundingPoly::internal_default_instance());
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
Position_descriptor_, Position::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto() {
Vertex_default_instance_.Shutdown();
delete Vertex_reflection_;
BoundingPoly_default_instance_.Shutdown();
delete BoundingPoly_reflection_;
Position_default_instance_.Shutdown();
delete Position_reflection_;
}
void protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
Vertex_default_instance_.DefaultConstruct();
BoundingPoly_default_instance_.DefaultConstruct();
Position_default_instance_.DefaultConstruct();
Vertex_default_instance_.get_mutable()->InitAsDefaultInstance();
BoundingPoly_default_instance_.get_mutable()->InitAsDefaultInstance();
Position_default_instance_.get_mutable()->InitAsDefaultInstance();
}
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_once_);
void protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto() {
::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_once_,
&protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_impl);
}
void protobuf_AddDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n%google/cloud/vision/v1/geometry.proto\022"
"\026google.cloud.vision.v1\"\036\n\006Vertex\022\t\n\001x\030\001"
" \001(\005\022\t\n\001y\030\002 \001(\005\"@\n\014BoundingPoly\0220\n\010verti"
"ces\030\001 \003(\0132\036.google.cloud.vision.v1.Verte"
"x\"+\n\010Position\022\t\n\001x\030\001 \001(\002\022\t\n\001y\030\002 \001(\002\022\t\n\001z"
"\030\003 \001(\002Bn\n\032com.google.cloud.vision.v1B\rGe"
"ometryProtoP\001Z<google.golang.org/genprot"
"o/googleapis/cloud/vision/v1;vision\370\001\001b\006"
"proto3", 326);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/cloud/vision/v1/geometry.proto", &protobuf_RegisterTypes);
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto);
}
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_once_);
void protobuf_AddDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto() {
::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_once_,
&protobuf_AddDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_impl);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto {
StaticDescriptorInitializer_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto() {
protobuf_AddDesc_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
}
} static_descriptor_initializer_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto_;
namespace {
static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
static void MergeFromFail(int line) {
::google::protobuf::internal::MergeFromFail(__FILE__, line);
}
} // namespace
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Vertex::kXFieldNumber;
const int Vertex::kYFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Vertex::Vertex()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.cloud.vision.v1.Vertex)
}
Vertex::Vertex(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.cloud.vision.v1.Vertex)
}
void Vertex::InitAsDefaultInstance() {
}
Vertex::Vertex(const Vertex& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.cloud.vision.v1.Vertex)
}
void Vertex::SharedCtor() {
::memset(&x_, 0, reinterpret_cast<char*>(&y_) -
reinterpret_cast<char*>(&x_) + sizeof(y_));
_cached_size_ = 0;
}
Vertex::~Vertex() {
// @@protoc_insertion_point(destructor:google.cloud.vision.v1.Vertex)
SharedDtor();
}
void Vertex::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void Vertex::ArenaDtor(void* object) {
Vertex* _this = reinterpret_cast< Vertex* >(object);
(void)_this;
}
void Vertex::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void Vertex::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Vertex::descriptor() {
protobuf_AssignDescriptorsOnce();
return Vertex_descriptor_;
}
const Vertex& Vertex::default_instance() {
protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<Vertex> Vertex_default_instance_;
Vertex* Vertex::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<Vertex>(arena);
}
void Vertex::Clear() {
// @@protoc_insertion_point(message_clear_start:google.cloud.vision.v1.Vertex)
#if defined(__clang__)
#define ZR_HELPER_(f) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
__builtin_offsetof(Vertex, f) \
_Pragma("clang diagnostic pop")
#else
#define ZR_HELPER_(f) reinterpret_cast<char*>(\
&reinterpret_cast<Vertex*>(16)->f)
#endif
#define ZR_(first, last) do {\
::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
ZR_(x_, y_);
#undef ZR_HELPER_
#undef ZR_
}
bool Vertex::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.cloud.vision.v1.Vertex)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 x = 1;
case 1: {
if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &x_)));
} else {
goto handle_unusual;
}
if (input->ExpectTag(16)) goto parse_y;
break;
}
// optional int32 y = 2;
case 2: {
if (tag == 16) {
parse_y:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &y_)));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.cloud.vision.v1.Vertex)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.cloud.vision.v1.Vertex)
return false;
#undef DO_
}
void Vertex::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.cloud.vision.v1.Vertex)
// optional int32 x = 1;
if (this->x() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->x(), output);
}
// optional int32 y = 2;
if (this->y() != 0) {
::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->y(), output);
}
// @@protoc_insertion_point(serialize_end:google.cloud.vision.v1.Vertex)
}
::google::protobuf::uint8* Vertex::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.cloud.vision.v1.Vertex)
// optional int32 x = 1;
if (this->x() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->x(), target);
}
// optional int32 y = 2;
if (this->y() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->y(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.cloud.vision.v1.Vertex)
return target;
}
size_t Vertex::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.cloud.vision.v1.Vertex)
size_t total_size = 0;
// optional int32 x = 1;
if (this->x() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->x());
}
// optional int32 y = 2;
if (this->y() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->y());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Vertex::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.cloud.vision.v1.Vertex)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const Vertex* source =
::google::protobuf::internal::DynamicCastToGenerated<const Vertex>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.cloud.vision.v1.Vertex)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.cloud.vision.v1.Vertex)
UnsafeMergeFrom(*source);
}
}
void Vertex::MergeFrom(const Vertex& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.cloud.vision.v1.Vertex)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void Vertex::UnsafeMergeFrom(const Vertex& from) {
GOOGLE_DCHECK(&from != this);
if (from.x() != 0) {
set_x(from.x());
}
if (from.y() != 0) {
set_y(from.y());
}
}
void Vertex::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.cloud.vision.v1.Vertex)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Vertex::CopyFrom(const Vertex& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.cloud.vision.v1.Vertex)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool Vertex::IsInitialized() const {
return true;
}
void Vertex::Swap(Vertex* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
Vertex temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void Vertex::UnsafeArenaSwap(Vertex* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Vertex::InternalSwap(Vertex* other) {
std::swap(x_, other->x_);
std::swap(y_, other->y_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Vertex::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = Vertex_descriptor_;
metadata.reflection = Vertex_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Vertex
// optional int32 x = 1;
void Vertex::clear_x() {
x_ = 0;
}
::google::protobuf::int32 Vertex::x() const {
// @@protoc_insertion_point(field_get:google.cloud.vision.v1.Vertex.x)
return x_;
}
void Vertex::set_x(::google::protobuf::int32 value) {
x_ = value;
// @@protoc_insertion_point(field_set:google.cloud.vision.v1.Vertex.x)
}
// optional int32 y = 2;
void Vertex::clear_y() {
y_ = 0;
}
::google::protobuf::int32 Vertex::y() const {
// @@protoc_insertion_point(field_get:google.cloud.vision.v1.Vertex.y)
return y_;
}
void Vertex::set_y(::google::protobuf::int32 value) {
y_ = value;
// @@protoc_insertion_point(field_set:google.cloud.vision.v1.Vertex.y)
}
inline const Vertex* Vertex::internal_default_instance() {
return &Vertex_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int BoundingPoly::kVerticesFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
BoundingPoly::BoundingPoly()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.cloud.vision.v1.BoundingPoly)
}
BoundingPoly::BoundingPoly(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena),
vertices_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.cloud.vision.v1.BoundingPoly)
}
void BoundingPoly::InitAsDefaultInstance() {
}
BoundingPoly::BoundingPoly(const BoundingPoly& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.cloud.vision.v1.BoundingPoly)
}
void BoundingPoly::SharedCtor() {
_cached_size_ = 0;
}
BoundingPoly::~BoundingPoly() {
// @@protoc_insertion_point(destructor:google.cloud.vision.v1.BoundingPoly)
SharedDtor();
}
void BoundingPoly::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void BoundingPoly::ArenaDtor(void* object) {
BoundingPoly* _this = reinterpret_cast< BoundingPoly* >(object);
(void)_this;
}
void BoundingPoly::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void BoundingPoly::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* BoundingPoly::descriptor() {
protobuf_AssignDescriptorsOnce();
return BoundingPoly_descriptor_;
}
const BoundingPoly& BoundingPoly::default_instance() {
protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<BoundingPoly> BoundingPoly_default_instance_;
BoundingPoly* BoundingPoly::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<BoundingPoly>(arena);
}
void BoundingPoly::Clear() {
// @@protoc_insertion_point(message_clear_start:google.cloud.vision.v1.BoundingPoly)
vertices_.Clear();
}
bool BoundingPoly::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.cloud.vision.v1.BoundingPoly)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .google.cloud.vision.v1.Vertex vertices = 1;
case 1: {
if (tag == 10) {
DO_(input->IncrementRecursionDepth());
parse_loop_vertices:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth(
input, add_vertices()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(10)) goto parse_loop_vertices;
input->UnsafeDecrementRecursionDepth();
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.cloud.vision.v1.BoundingPoly)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.cloud.vision.v1.BoundingPoly)
return false;
#undef DO_
}
void BoundingPoly::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.cloud.vision.v1.BoundingPoly)
// repeated .google.cloud.vision.v1.Vertex vertices = 1;
for (unsigned int i = 0, n = this->vertices_size(); i < n; i++) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
1, this->vertices(i), output);
}
// @@protoc_insertion_point(serialize_end:google.cloud.vision.v1.BoundingPoly)
}
::google::protobuf::uint8* BoundingPoly::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.cloud.vision.v1.BoundingPoly)
// repeated .google.cloud.vision.v1.Vertex vertices = 1;
for (unsigned int i = 0, n = this->vertices_size(); i < n; i++) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
1, this->vertices(i), false, target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.cloud.vision.v1.BoundingPoly)
return target;
}
size_t BoundingPoly::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.cloud.vision.v1.BoundingPoly)
size_t total_size = 0;
// repeated .google.cloud.vision.v1.Vertex vertices = 1;
{
unsigned int count = this->vertices_size();
total_size += 1UL * count;
for (unsigned int i = 0; i < count; i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->vertices(i));
}
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void BoundingPoly::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.cloud.vision.v1.BoundingPoly)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const BoundingPoly* source =
::google::protobuf::internal::DynamicCastToGenerated<const BoundingPoly>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.cloud.vision.v1.BoundingPoly)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.cloud.vision.v1.BoundingPoly)
UnsafeMergeFrom(*source);
}
}
void BoundingPoly::MergeFrom(const BoundingPoly& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.cloud.vision.v1.BoundingPoly)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void BoundingPoly::UnsafeMergeFrom(const BoundingPoly& from) {
GOOGLE_DCHECK(&from != this);
vertices_.MergeFrom(from.vertices_);
}
void BoundingPoly::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.cloud.vision.v1.BoundingPoly)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void BoundingPoly::CopyFrom(const BoundingPoly& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.cloud.vision.v1.BoundingPoly)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool BoundingPoly::IsInitialized() const {
return true;
}
void BoundingPoly::Swap(BoundingPoly* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
BoundingPoly temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void BoundingPoly::UnsafeArenaSwap(BoundingPoly* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void BoundingPoly::InternalSwap(BoundingPoly* other) {
vertices_.UnsafeArenaSwap(&other->vertices_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata BoundingPoly::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = BoundingPoly_descriptor_;
metadata.reflection = BoundingPoly_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// BoundingPoly
// repeated .google.cloud.vision.v1.Vertex vertices = 1;
int BoundingPoly::vertices_size() const {
return vertices_.size();
}
void BoundingPoly::clear_vertices() {
vertices_.Clear();
}
const ::google::cloud::vision::v1::Vertex& BoundingPoly::vertices(int index) const {
// @@protoc_insertion_point(field_get:google.cloud.vision.v1.BoundingPoly.vertices)
return vertices_.Get(index);
}
::google::cloud::vision::v1::Vertex* BoundingPoly::mutable_vertices(int index) {
// @@protoc_insertion_point(field_mutable:google.cloud.vision.v1.BoundingPoly.vertices)
return vertices_.Mutable(index);
}
::google::cloud::vision::v1::Vertex* BoundingPoly::add_vertices() {
// @@protoc_insertion_point(field_add:google.cloud.vision.v1.BoundingPoly.vertices)
return vertices_.Add();
}
::google::protobuf::RepeatedPtrField< ::google::cloud::vision::v1::Vertex >*
BoundingPoly::mutable_vertices() {
// @@protoc_insertion_point(field_mutable_list:google.cloud.vision.v1.BoundingPoly.vertices)
return &vertices_;
}
const ::google::protobuf::RepeatedPtrField< ::google::cloud::vision::v1::Vertex >&
BoundingPoly::vertices() const {
// @@protoc_insertion_point(field_list:google.cloud.vision.v1.BoundingPoly.vertices)
return vertices_;
}
inline const BoundingPoly* BoundingPoly::internal_default_instance() {
return &BoundingPoly_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Position::kXFieldNumber;
const int Position::kYFieldNumber;
const int Position::kZFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Position::Position()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.cloud.vision.v1.Position)
}
Position::Position(::google::protobuf::Arena* arena)
: ::google::protobuf::Message(),
_internal_metadata_(arena) {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
#endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
SharedCtor();
RegisterArenaDtor(arena);
// @@protoc_insertion_point(arena_constructor:google.cloud.vision.v1.Position)
}
void Position::InitAsDefaultInstance() {
}
Position::Position(const Position& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.cloud.vision.v1.Position)
}
void Position::SharedCtor() {
::memset(&x_, 0, reinterpret_cast<char*>(&z_) -
reinterpret_cast<char*>(&x_) + sizeof(z_));
_cached_size_ = 0;
}
Position::~Position() {
// @@protoc_insertion_point(destructor:google.cloud.vision.v1.Position)
SharedDtor();
}
void Position::SharedDtor() {
::google::protobuf::Arena* arena = GetArenaNoVirtual();
if (arena != NULL) {
return;
}
}
void Position::ArenaDtor(void* object) {
Position* _this = reinterpret_cast< Position* >(object);
(void)_this;
}
void Position::RegisterArenaDtor(::google::protobuf::Arena* arena) {
}
void Position::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Position::descriptor() {
protobuf_AssignDescriptorsOnce();
return Position_descriptor_;
}
const Position& Position::default_instance() {
protobuf_InitDefaults_google_2fcloud_2fvision_2fv1_2fgeometry_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<Position> Position_default_instance_;
Position* Position::New(::google::protobuf::Arena* arena) const {
return ::google::protobuf::Arena::CreateMessage<Position>(arena);
}
void Position::Clear() {
// @@protoc_insertion_point(message_clear_start:google.cloud.vision.v1.Position)
#if defined(__clang__)
#define ZR_HELPER_(f) \
_Pragma("clang diagnostic push") \
_Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \
__builtin_offsetof(Position, f) \
_Pragma("clang diagnostic pop")
#else
#define ZR_HELPER_(f) reinterpret_cast<char*>(\
&reinterpret_cast<Position*>(16)->f)
#endif
#define ZR_(first, last) do {\
::memset(&(first), 0,\
ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\
} while (0)
ZR_(x_, z_);
#undef ZR_HELPER_
#undef ZR_
}
bool Position::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.cloud.vision.v1.Position)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional float x = 1;
case 1: {
if (tag == 13) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, &x_)));
} else {
goto handle_unusual;
}
if (input->ExpectTag(21)) goto parse_y;
break;
}
// optional float y = 2;
case 2: {
if (tag == 21) {
parse_y:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, &y_)));
} else {
goto handle_unusual;
}
if (input->ExpectTag(29)) goto parse_z;
break;
}
// optional float z = 3;
case 3: {
if (tag == 29) {
parse_z:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, &z_)));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.cloud.vision.v1.Position)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.cloud.vision.v1.Position)
return false;
#undef DO_
}
void Position::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.cloud.vision.v1.Position)
// optional float x = 1;
if (this->x() != 0) {
::google::protobuf::internal::WireFormatLite::WriteFloat(1, this->x(), output);
}
// optional float y = 2;
if (this->y() != 0) {
::google::protobuf::internal::WireFormatLite::WriteFloat(2, this->y(), output);
}
// optional float z = 3;
if (this->z() != 0) {
::google::protobuf::internal::WireFormatLite::WriteFloat(3, this->z(), output);
}
// @@protoc_insertion_point(serialize_end:google.cloud.vision.v1.Position)
}
::google::protobuf::uint8* Position::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.cloud.vision.v1.Position)
// optional float x = 1;
if (this->x() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(1, this->x(), target);
}
// optional float y = 2;
if (this->y() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(2, this->y(), target);
}
// optional float z = 3;
if (this->z() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteFloatToArray(3, this->z(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.cloud.vision.v1.Position)
return target;
}
size_t Position::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.cloud.vision.v1.Position)
size_t total_size = 0;
// optional float x = 1;
if (this->x() != 0) {
total_size += 1 + 4;
}
// optional float y = 2;
if (this->y() != 0) {
total_size += 1 + 4;
}
// optional float z = 3;
if (this->z() != 0) {
total_size += 1 + 4;
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Position::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.cloud.vision.v1.Position)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const Position* source =
::google::protobuf::internal::DynamicCastToGenerated<const Position>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.cloud.vision.v1.Position)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.cloud.vision.v1.Position)
UnsafeMergeFrom(*source);
}
}
void Position::MergeFrom(const Position& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.cloud.vision.v1.Position)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void Position::UnsafeMergeFrom(const Position& from) {
GOOGLE_DCHECK(&from != this);
if (from.x() != 0) {
set_x(from.x());
}
if (from.y() != 0) {
set_y(from.y());
}
if (from.z() != 0) {
set_z(from.z());
}
}
void Position::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.cloud.vision.v1.Position)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Position::CopyFrom(const Position& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.cloud.vision.v1.Position)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool Position::IsInitialized() const {
return true;
}
void Position::Swap(Position* other) {
if (other == this) return;
if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) {
InternalSwap(other);
} else {
Position temp;
temp.UnsafeMergeFrom(*this);
CopyFrom(*other);
other->CopyFrom(temp);
}
}
void Position::UnsafeArenaSwap(Position* other) {
if (other == this) return;
GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual());
InternalSwap(other);
}
void Position::InternalSwap(Position* other) {
std::swap(x_, other->x_);
std::swap(y_, other->y_);
std::swap(z_, other->z_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Position::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = Position_descriptor_;
metadata.reflection = Position_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Position
// optional float x = 1;
void Position::clear_x() {
x_ = 0;
}
float Position::x() const {
// @@protoc_insertion_point(field_get:google.cloud.vision.v1.Position.x)
return x_;
}
void Position::set_x(float value) {
x_ = value;
// @@protoc_insertion_point(field_set:google.cloud.vision.v1.Position.x)
}
// optional float y = 2;
void Position::clear_y() {
y_ = 0;
}
float Position::y() const {
// @@protoc_insertion_point(field_get:google.cloud.vision.v1.Position.y)
return y_;
}
void Position::set_y(float value) {
y_ = value;
// @@protoc_insertion_point(field_set:google.cloud.vision.v1.Position.y)
}
// optional float z = 3;
void Position::clear_z() {
z_ = 0;
}
float Position::z() const {
// @@protoc_insertion_point(field_get:google.cloud.vision.v1.Position.z)
return z_;
}
void Position::set_z(float value) {
z_ = value;
// @@protoc_insertion_point(field_set:google.cloud.vision.v1.Position.z)
}
inline const Position* Position::internal_default_instance() {
return &Position_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace v1
} // namespace vision
} // namespace cloud
} // namespace google
// @@protoc_insertion_point(global_scope)
| 32.448361 | 115 | 0.717508 | allquixotic |
c1b7f7dd34eb8411c40fb30e8c598d2f394af34f | 16,940 | cpp | C++ | LibUIDK/WLText.cpp | swjsky/sktminest | 42fa47d9ffb0f50a5727e42811e949fff920bec9 | [
"MIT"
] | 3 | 2019-12-03T09:04:04.000Z | 2021-01-29T02:03:30.000Z | LibUIDK/WLText.cpp | dushulife/LibUIDK | 04e79e64eaadfaa29641c24e9cddd9abde544aac | [
"MIT"
] | null | null | null | LibUIDK/WLText.cpp | dushulife/LibUIDK | 04e79e64eaadfaa29641c24e9cddd9abde544aac | [
"MIT"
] | 2 | 2019-09-12T07:49:42.000Z | 2019-12-24T22:28:49.000Z | // WLText.cpp : implementation file
//
#include "stdafx.h"
#include "ResourceMgr.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
struct WLTXTMEMBER
{
WLTXTMEMBER()
{
int i = 0;
for (i = 0; i < 2; ++i)
{
m_himgBk[i] = NULL;
}
m_ptBkImageResize.x = m_ptBkImageResize.y = 3;
for (i = 0; i < 2; ++i)
{
m_himgFg[i] = NULL;
}
m_ptFkImageResize.x = m_ptFkImageResize.y = 3;
m_eForegroundAlignHor = FAH_LEFT;
m_eForegroundAlignVer = FAV_CENTER;
m_rcForegroundMargin.SetRect(0, 0, 0, 0);
m_crForegroundMask = RGB(255, 0, 255);
for (i = 0; i < 2; ++i)
{
m_eHorAlignMode[i] = TAH_LEFT;
m_eVerAlignMode[i] = TAV_CENTER;
}
m_uTextFormat = DT_WORDBREAK;
m_rcPadding4Text.SetRect(0, 0, 0, 0);
// for font and color
for (i = 0; i < 2; ++i)
{
m_hIUIFont[i] = NULL;
m_cr[i] = RGB(0, 0, 0);
}
// for shadow text
m_bShadowText = FALSE;
m_crTextShadow = RGB(192, 192, 192);
m_ptTextShadowOffset = CPoint(1, 1);
}
int Release()
{
int i = 0;
for (i = 0; i < 2; ++i)
{
ReleaseIUIImage(m_himgBk[i]);
m_himgBk[i] = NULL;
}
m_ptBkImageResize.x = m_ptBkImageResize.y = 3;
for (i = 0; i < 2; ++i)
{
ReleaseIUIImage(m_himgFg[i]);
m_himgFg[i] = NULL;
}
m_ptFkImageResize.x = m_ptFkImageResize.y = 3;
m_eForegroundAlignHor = FAH_LEFT;
m_eForegroundAlignVer = FAV_CENTER;
m_rcForegroundMargin.SetRect(0, 0, 0, 0);
m_crForegroundMask = RGB(255, 0, 255);
for (i = 0; i < 2; ++i)
{
m_eHorAlignMode[i] = TAH_LEFT;
m_eVerAlignMode[i] = TAV_CENTER;
}
m_uTextFormat = DT_WORDBREAK;
m_rcPadding4Text.SetRect(0, 0, 0, 0);
// for font and color
for (i = 0; i < 2; ++i)
{
ReleaseIUIFontInternal(m_hIUIFont[i]);
m_hIUIFont[i] = NULL;
m_cr[i] = RGB(0, 0, 0);
}
// for shadow text
m_bShadowText = FALSE;
m_crTextShadow = RGB(192, 192, 192);
m_ptTextShadowOffset = CPoint(1, 1);
return 0;
}
HIUIIMAGE m_himgBk[2];
CPoint m_ptBkImageResize;
HIUIIMAGE m_himgFg[2];
CPoint m_ptFkImageResize;
FOREGROUND_ALIGN_HOR m_eForegroundAlignHor;
FOREGROUND_ALIGN_VER m_eForegroundAlignVer;
CRect m_rcForegroundMargin;
COLORREF m_crForegroundMask;
TEXT_ALIGN_HOR m_eHorAlignMode[2];
TEXT_ALIGN_VER m_eVerAlignMode[2];
UINT m_uTextFormat;
CRect m_rcPadding4Text;
// for font
HIUIFONT m_hIUIFont[2];
// for color
COLORREF m_cr[2];
CToolTipCtrl m_wndToolTip;
// for shadow text
BOOL m_bShadowText;
COLORREF m_crTextShadow;
CPoint m_ptTextShadowOffset;
};
//////////////////////////////////////////////////////////////////////////
// CWLText
CWLText::CWLText()
{
m_pMember = new WLTXTMEMBER;
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
}
CWLText::~CWLText()
{
if (m_pMember != NULL)
{
delete (WLTXTMEMBER *)m_pMember;
m_pMember = NULL;
}
}
BOOL CWLText::Create(LPCTSTR lpszControlName, DWORD dwStyle, const RECT &rect,
CWnd *pParentWnd, UINT nID, CWLWnd *pVirtualParent)
{
BOOL bRet = CRectCtrl::Create(lpszControlName, dwStyle, rect, pParentWnd, nID, pVirtualParent);
if (!bRet)
{
return FALSE;
}
return TRUE;
}
int CWLText::BindStyle(LPCTSTR lpszStyleID)
{
if (!IsCreated())
{
ASSERT(FALSE);
return -1;
}
if (lpszStyleID == NULL)
{
return -2;
}
CTRLPROPERTIES *pCtrlProp = CUIMgr::GetStyleItem(STYLET_STATIC, lpszStyleID);
return BindStyle(pCtrlProp);
}
int CWLText::BindStyle(const CTRLPROPERTIES *pCtrlProp)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (!IsCreated())
{
ASSERT(FALSE);
return -1;
}
if (pCtrlProp == NULL)
{
return -2;
}
CONTROL_TYPE ect = (CONTROL_TYPE)pCtrlProp->m_eControlType;
if (ect != CT_STYLE_STATIC && ect != CT_WL_TEXT)
{
return -3;
}
TXTPROPERTIES *pWLTxtProp = (TXTPROPERTIES *)pCtrlProp;
bool bSpecifyBackgroundImages = pCtrlProp->m_bSpecifyBackgroundImages;
if (bSpecifyBackgroundImages)
{
CString strImageName[1 + COMBINEIMAGESIZE2];
BOOL bCombineImage = TRUE;
CTRLPROPERTIES::IUIGetBackground2(pCtrlProp, &bCombineImage, strImageName);
if (bCombineImage)
{
SetBkCombineImage(strImageName[0]);
}
else
{
SetBitmap(CONTROL_STATE_UNCHECKED_ND, strImageName[1], strImageName[2]);
}
for (int i = 0; i < 1 + COMBINEIMAGESIZE2; ++i)
{
ReleaseIUIImage(strImageName[i]);
}
SetBkImageResizeMode(pCtrlProp->m_eBkImageResizeMode);
SetBkImageResizePoint(pCtrlProp->m_ptImageResize);
}
// Set foreground
if (pWLTxtProp->m_bSpecifyForegroundImages)
{
CString strImageName[1 + COMBINEIMAGESIZE2];
BOOL bCombineImage = TRUE;
CTRLPROPERTIES::IUIGetStaticForeground2(pWLTxtProp, &bCombineImage, strImageName);
if (bCombineImage)
{
SetFgCombineImage(strImageName[0]);
}
else
SetForegroundBitmap(CONTROL_STATE_CHECKED_NORMAL | CONTROL_STATE_CHECKED_DISABLED,
strImageName[1], strImageName[2],
pWLTxtProp->m_rcPadding4Foreground,
pWLTxtProp->m_eForegroundHorAlignMode,
pWLTxtProp->m_eForegroundVerAlignMode);
}
SetTextMultiline(!(bool)pWLTxtProp->m_bNoWrap);
SetPathEllipsis(pWLTxtProp->m_bPathEllipsis);
SetEndEllipsis(pWLTxtProp->m_bEndEllipsis);
SetTextAlignHor(pWLTxtProp->m_eTextHorAlignMode, pWLTxtProp->m_eTextHorAlignMode);
SetTextAlignVer(pWLTxtProp->m_eTextVerAlignMode, pWLTxtProp->m_eTextVerAlignMode);
COLORREF crN, crD;
CTRLPROPERTIES::IUIGetControlColor4(pWLTxtProp, &crN, NULL, NULL, &crD);
SetTextColor(crN, crD);
// font
CString strResFontID[2];
CTRLPROPERTIES::IUIGetControlFont2(pCtrlProp, strResFontID);
SetTextFont(CONTROL_STATE_NORMAL | CONTROL_STATE_DISABLED, strResFontID[0], strResFontID[1]);
// Use tool tip
if (pWLTxtProp->m_bUseToolTip)
{
SetToolTips(pWLTxtProp->m_strToolTip);
}
RECT rcMargin = pWLTxtProp->m_rcPadding4Text;
SetTextMargin(&rcMargin);
// Shadow text
if (pWLTxtProp->m_bShadowText)
{
ShadowText(TRUE);
SetTextShadowColor(pWLTxtProp->m_crTextShadow);
POINT ptOffset = pWLTxtProp->m_ptTextShadowOffset;
SetTextShadowOffset(&ptOffset);
}
return 0;
}
int CWLText::ReleaseObject()
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
for (int i = 0; i < 2; ++i)
{
ReleaseIUIFontInternal(pMember->m_hIUIFont[i]);
pMember->m_hIUIFont[i] = NULL;
ReleaseIUIImage(pMember->m_himgBk[i]);
pMember->m_himgBk[i] = NULL;
}
return CControlBase::ReleaseObject();
}
//////////////////////////////////////////////////////////////////////////
// virtual
int CWLText::OnDraw(CDC *pMemDCParent)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (!IsWindowVisible())
{
return 1;
}
if (pMemDCParent == NULL)
{
return -1;
}
CRect rcWin;
GetWindowRect(rcWin);
GetParent()->ScreenToClient(rcWin);
POINT ptDrawOffset = {0};
GetDrawOffset(&ptDrawOffset);
rcWin.OffsetRect(ptDrawOffset);
// Don't draw this control if it's out of the parent
CRect rcParent;
GetParent()->GetClientRect(rcParent);
CRect rcIntersect;
rcIntersect.IntersectRect(rcWin, rcParent);
if (rcIntersect.IsRectEmpty())
{
return 0;
}
BOOL bEnabled = IsWindowEnabled();
int nImageState = 0;
if (!bEnabled)
{
nImageState = 1;
}
// Draw background image.
if (m_bBkCombine)
{
if (m_eBkImageResizeMode == IRM_9GRID)
{
IUIPartNineGridBlt(pMemDCParent->GetSafeHdc(), rcWin, m_himgCombineBk,
m_ptBkImageResize, m_lBkImageRepeatX, m_lBkImageRepeatY,
2, nImageState);
}
else if (m_eBkImageResizeMode == IRM_STRETCH
|| m_eBkImageResizeMode == IRM_STRETCH_HIGH_QUALITY)
{
IUIPartStretchBlt(pMemDCParent->GetSafeHdc(), rcWin, m_himgCombineBk, 2, nImageState,
m_eBkImageResizeMode);
}
}
else
{
IUIDrawImage(pMemDCParent->GetSafeHdc(), rcWin, pMember->m_himgBk[nImageState],
m_eBkImageResizeMode, m_ptBkImageResize, m_lBkImageRepeatX, m_lBkImageRepeatY);
}
// Draw foreground image.
IUIDrawForeground(pMemDCParent->GetSafeHdc(), rcWin, pMember->m_rcForegroundMargin,
pMember->m_himgFg[nImageState],
pMember->m_eForegroundAlignHor, pMember->m_eForegroundAlignVer,
pMember->m_crForegroundMask, 255);
// Draw window's text to background DC.
pMemDCParent->SetBkMode(TRANSPARENT);
CString strText;
GetWindowText(strText);
pMember->m_hIUIFont[nImageState]->SafeLoadSavedFont();
DrawFormatText(pMemDCParent->GetSafeHdc(), strText, strText.GetLength(),
rcWin, pMember->m_rcPadding4Text,
pMember->m_eHorAlignMode[nImageState], pMember->m_eVerAlignMode[nImageState],
pMember->m_uTextFormat, pMember->m_hIUIFont[nImageState]->GetSafeHFont(),
pMember->m_cr[nImageState],
CT_WL_TEXT);
return 0;
}
//////////////////////////////////////////////////////////////////////////
// public
int CWLText::SetBitmap(UINT uMask,
LPCTSTR lpszImageNameN, LPCTSTR lpszImageNameD, BOOL bRedraw/* = TRUE*/)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
m_bBkCombine = false;
IUISetControlImage2(uMask, pMember->m_himgBk, lpszImageNameN, lpszImageNameD);
if (bRedraw)
{
Invalidate();
}
return 0;
}
int CWLText::GetBitmap(UINT uMask,
BOOL *pbCombineImage,
CString *pstrCombineImageName,
CString *pstrImageNameN, CString *pstrImageNameD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (pstrImageNameN != NULL)
{
GetImageFileName(pMember->m_himgBk[0], pstrImageNameN);
}
if (pstrImageNameD != NULL)
{
GetImageFileName(pMember->m_himgBk[1], pstrImageNameD);
}
return 0;
}
void CWLText::SetForegroundBitmap(UINT uMask,
LPCTSTR lpszImageNameForegroundN, LPCTSTR lpszImageNameForegroundD,
const CRect &rcForegroundMargin,
FOREGROUND_ALIGN_HOR eAlignModeHor/* = FAH_LEFT*/,
FOREGROUND_ALIGN_VER eAlignModeVer/* = FAV_CENTER*/,
COLORREF crMask/* = RGB(255, 0, 255)*/, BOOL bReDraw/* = TRUE*/)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
IUISetControlImage2(uMask, pMember->m_himgFg,
lpszImageNameForegroundN, lpszImageNameForegroundD);
pMember->m_rcForegroundMargin = rcForegroundMargin;
pMember->m_eForegroundAlignHor = eAlignModeHor;
pMember->m_eForegroundAlignVer = eAlignModeVer;
pMember->m_crForegroundMask = crMask;
if (bReDraw)
{
Invalidate();
}
}
void CWLText::GetForegroundBitmap(UINT uMask,
BOOL *pbCombineImage,
CString *pstrCombineImageName,
CString *pstrImageNameN, CString *pstrImageNameD,
LPRECT lprcForegroundMargin,
int *pnAlignModeHor, int *pnAlignModeVer, COLORREF *pcrMask)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (pstrImageNameN != NULL)
{
GetImageFileName(pMember->m_himgFg[0], pstrImageNameN);
}
if (pstrImageNameD != NULL)
{
GetImageFileName(pMember->m_himgFg[1], pstrImageNameD);
}
if (lprcForegroundMargin != NULL)
{
*lprcForegroundMargin = pMember->m_rcForegroundMargin;
}
if (pnAlignModeHor != NULL)
{
*pnAlignModeHor = pMember->m_eForegroundAlignHor;
}
if (pnAlignModeVer != NULL)
{
*pnAlignModeVer = pMember->m_eForegroundAlignVer;
}
if (pcrMask != NULL)
{
*pcrMask = pMember->m_crForegroundMask;
}
}
int CWLText::SetTextMultiline(BOOL bMultiline)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (bMultiline)
{
pMember->m_uTextFormat &= ~DT_SINGLELINE;
pMember->m_uTextFormat |= DT_WORDBREAK;
}
else
{
pMember->m_uTextFormat &= ~DT_WORDBREAK;
pMember->m_uTextFormat |= DT_SINGLELINE;
}
return 0;
}
BOOL CWLText::IsTextMultiline()
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
return IsIncludeFlag(pMember->m_uTextFormat, DT_WORDBREAK);
}
int CWLText::SetPathEllipsis(BOOL bPathEllipsis)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (bPathEllipsis)
{
pMember->m_uTextFormat |= DT_PATH_ELLIPSIS;
}
else
{
pMember->m_uTextFormat &= ~DT_PATH_ELLIPSIS;
}
return 0;
}
BOOL CWLText::IsPathEllipsis() const
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
return IsIncludeFlag(pMember->m_uTextFormat, DT_PATH_ELLIPSIS);
}
int CWLText::SetEndEllipsis(BOOL bEndEllipsis)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (bEndEllipsis)
{
pMember->m_uTextFormat |= DT_END_ELLIPSIS;
}
else
{
pMember->m_uTextFormat &= ~DT_END_ELLIPSIS;
}
return 0;
}
BOOL CWLText::IsEndEllipsis() const
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
return IsIncludeFlag(pMember->m_uTextFormat, DT_END_ELLIPSIS);
}
int CWLText::SetTextAlignHor(TEXT_ALIGN_HOR eHorAlignModeN, TEXT_ALIGN_HOR eHorAlignModeD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
pMember->m_eHorAlignMode[0] = eHorAlignModeN;
pMember->m_eHorAlignMode[1] = eHorAlignModeD;
return 0;
}
int CWLText::GetTextAlignHor(TEXT_ALIGN_HOR *peHorAlignModeN, TEXT_ALIGN_HOR *peHorAlignModeD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (peHorAlignModeN != NULL)
{
*peHorAlignModeN = pMember->m_eHorAlignMode[0];
}
if (peHorAlignModeD != NULL)
{
*peHorAlignModeD = pMember->m_eHorAlignMode[1];
}
return 0;
}
int CWLText::SetTextAlignVer(TEXT_ALIGN_VER eVerAlignModeN, TEXT_ALIGN_VER eVerAlignModeD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
pMember->m_eVerAlignMode[0] = eVerAlignModeN;
pMember->m_eVerAlignMode[1] = eVerAlignModeD;
return 0;
}
int CWLText::GetTextAlignVer(TEXT_ALIGN_VER *peVerAlignModeN, TEXT_ALIGN_VER *peVerAlignModeD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (peVerAlignModeN != NULL)
{
*peVerAlignModeN = pMember->m_eVerAlignMode[0];
}
if (peVerAlignModeD != NULL)
{
*peVerAlignModeD = pMember->m_eVerAlignMode[1];
}
return 0;
}
int CWLText::SetTextColor(COLORREF crN, COLORREF crD, BOOL bRedraw/* = TRUE*/)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
pMember->m_cr[0] = crN;
pMember->m_cr[1] = crD;
if (bRedraw)
{
Invalidate();
}
return 0;
}
int CWLText::GetTextColor(COLORREF *pcrN, COLORREF *pcrD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (pcrN != NULL)
{
*pcrN = pMember->m_cr[0];
}
if (pcrD != NULL)
{
*pcrD = pMember->m_cr[1];
}
return 0;
}
int CWLText::SetTextFont(UINT uMask, LPCTSTR lpszFontIDN, LPCTSTR lpszFontIDD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
IUISetControlFont2(uMask, pMember->m_hIUIFont, lpszFontIDN, lpszFontIDD);
return 0;
}
int CWLText::GetTextFont(UINT uMask, CString *pstrFontIDN, CString *pstrFontIDD)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (pstrFontIDN != NULL)
{
GetFontResID(pMember->m_hIUIFont[0], pstrFontIDN);
}
if (pstrFontIDD != NULL)
{
GetFontResID(pMember->m_hIUIFont[1], pstrFontIDD);
}
return 0;
}
int CWLText::SetToolTips(LPCTSTR lpszToolTips)
{
return 0;
}
CToolTipCtrl *CWLText::GetToolTipCtrl()
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
return &pMember->m_wndToolTip;
}
int CWLText::SetTextFont(const LOGFONT *lf)
{
return 0;
}
int CWLText::GetTextFont(LOGFONT *lf) const
{
return 0;
}
int CWLText::SetTextMargin(LPCRECT lpRect)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (lpRect == NULL)
{
return -1;
}
pMember->m_rcPadding4Text = *lpRect;
return 0;
}
int CWLText::GetTextMargin(LPRECT lpRect) const
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
if (lpRect == NULL)
{
return -1;
}
*lpRect = pMember->m_rcPadding4Text;
return 0;
}
int CWLText::ShadowText(BOOL bShadow)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
pMember->m_bShadowText = bShadow;
return 0;
}
BOOL CWLText::IsShadowText() const
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
return pMember->m_bShadowText;
}
int CWLText::SetTextShadowColor(COLORREF crShadow)
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
pMember->m_crTextShadow = crShadow;
return 0;
}
COLORREF CWLText::GetTextShadowColor() const
{
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
return pMember->m_crTextShadow;
}
int CWLText::SetTextShadowOffset(LPPOINT lpptOffset)
{
if (lpptOffset == NULL)
{
return -1;
}
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
pMember->m_ptTextShadowOffset = *lpptOffset;
return 0;
}
int CWLText::GetTextShadowOffset(LPPOINT lpptOffset) const
{
if (lpptOffset == NULL)
{
return -1;
}
WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember;
*lpptOffset = pMember->m_ptTextShadowOffset;
return 0;
}
LRESULT CWLText::WLWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_WLDESTROY)
{
ReleaseObject();
}
return CRectCtrl::WLWindowProc(message, wParam, lParam);
}
| 21.690141 | 97 | 0.683353 | swjsky |
c1bc3217157f05a7f5c6b4d616af269158d13564 | 71,185 | cpp | C++ | examples/client_test.cpp | svn2github/libtorrent-rasterbar-RC_0_16 | c2c8dc24c82816c336d7c45c3ae7a3ab3821077a | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | examples/client_test.cpp | svn2github/libtorrent-rasterbar-RC_0_16 | c2c8dc24c82816c336d7c45c3ae7a3ab3821077a | [
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2019-02-03T09:54:54.000Z | 2019-02-03T09:54:54.000Z | examples/client_test.cpp | svn2github/libtorrent-rasterbar-RC_0_16 | c2c8dc24c82816c336d7c45c3ae7a3ab3821077a | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iterator>
#include "libtorrent/config.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/bind.hpp>
#include <boost/unordered_set.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
#include "libtorrent/extensions/smart_ban.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/identify_client.hpp"
#include "libtorrent/alert_types.hpp"
#include "libtorrent/ip_filter.hpp"
#include "libtorrent/magnet_uri.hpp"
#include "libtorrent/bitfield.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/socket_io.hpp" // print_address
#include "libtorrent/time.hpp"
#include "libtorrent/create_torrent.hpp"
using boost::bind;
#ifdef _WIN32
#if defined(_MSC_VER)
# define for if (false) {} else for
#endif
#include <windows.h>
#include <conio.h>
bool sleep_and_input(int* c, int sleep)
{
for (int i = 0; i < 2; ++i)
{
if (_kbhit())
{
*c = _getch();
return true;
}
Sleep(sleep / 2);
}
return false;
};
void clear_home()
{
CONSOLE_SCREEN_BUFFER_INFO si;
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(h, &si);
COORD c = {0, 0};
DWORD n;
FillConsoleOutputCharacter(h, ' ', si.dwSize.X * si.dwSize.Y, c, &n);
SetConsoleCursorPosition(h, c);
}
#else
#include <stdlib.h>
#include <stdio.h>
#include <termios.h>
#include <string.h>
#include <sys/ioctl.h>
#define ANSI_TERMINAL_COLORS
struct set_keypress
{
set_keypress()
{
termios new_settings;
tcgetattr(0,&stored_settings);
new_settings = stored_settings;
// Disable canonical mode, and set buffer size to 1 byte
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr(0,TCSANOW,&new_settings);
}
~set_keypress() { tcsetattr(0,TCSANOW,&stored_settings); }
termios stored_settings;
};
bool sleep_and_input(int* c, int sleep)
{
// sets the terminal to single-character mode
// and resets when destructed
set_keypress s;
libtorrent::ptime start = libtorrent::time_now_hires();
int ret = 0;
retry:
fd_set set;
FD_ZERO(&set);
FD_SET(0, &set);
timeval tv = {sleep/ 1000, (sleep % 1000) * 1000 };
ret = select(1, &set, 0, 0, &tv);
if (ret > 0)
{
*c = getc(stdin);
return true;
}
if (errno == EINTR)
{
if (total_milliseconds(libtorrent::time_now_hires() - start) < sleep)
goto retry;
return false;
}
if (ret < 0 && errno != 0 && errno != ETIMEDOUT)
{
fprintf(stderr, "select failed: %s\n", strerror(errno));
libtorrent::sleep(500);
}
return false;
}
void clear_home()
{
puts("\033[2J\033[0;0H");
}
#endif
bool print_trackers = false;
bool print_peers = false;
bool print_log = false;
bool print_downloads = false;
bool print_piece_bar = false;
bool print_file_progress = false;
bool show_pad_files = false;
bool show_dht_status = false;
bool sequential_download = false;
bool print_utp_stats = false;
bool print_ip = true;
bool print_as = false;
bool print_timers = false;
bool print_block = false;
bool print_peer_rate = false;
bool print_fails = false;
bool print_send_bufs = true;
// the number of times we've asked to save resume data
// without having received a response (successful or failure)
int num_outstanding_resume_data = 0;
enum {
torrents_all,
torrents_downloading,
torrents_not_paused,
torrents_seeding,
torrents_queued,
torrents_stopped,
torrents_checking,
torrents_feeds,
torrents_max
};
int torrent_filter = torrents_not_paused;
struct torrent_entry
{
torrent_entry(libtorrent::torrent_handle h) : handle(h) {}
libtorrent::torrent_handle handle;
libtorrent::torrent_status status;
};
// maps filenames to torrent_handles
typedef std::multimap<std::string, libtorrent::torrent_handle> handles_t;
using libtorrent::torrent_status;
bool show_torrent(libtorrent::torrent_status const& st, int torrent_filter, int* counters)
{
++counters[torrents_all];
if (!st.paused
&& st.state != torrent_status::seeding
&& st.state != torrent_status::finished)
{
++counters[torrents_downloading];
}
if (!st.paused) ++counters[torrents_not_paused];
if (!st.paused
&& (st.state == torrent_status::seeding
|| st.state == torrent_status::finished))
{
++counters[torrents_seeding];
}
if (st.paused && st.auto_managed)
{
++counters[torrents_queued];
}
if (st.paused && !st.auto_managed)
{
++counters[torrents_stopped];
}
if (st.state == torrent_status::checking_files
|| st.state == torrent_status::queued_for_checking)
{
++counters[torrents_checking];
}
switch (torrent_filter)
{
case torrents_all: return true;
case torrents_downloading:
return !st.paused
&& st.state != torrent_status::seeding
&& st.state != torrent_status::finished;
case torrents_not_paused: return !st.paused;
case torrents_seeding:
return !st.paused
&& (st.state == torrent_status::seeding
|| st.state == torrent_status::finished);
case torrents_queued: return st.paused && st.auto_managed;
case torrents_stopped: return st.paused && !st.auto_managed;
case torrents_checking: return st.state == torrent_status::checking_files
|| st.state == torrent_status::queued_for_checking;
case torrents_feeds: return false;
}
return true;
}
bool yes(libtorrent::torrent_status const&)
{ return true; }
FILE* g_log_file = 0;
int active_torrent = 0;
bool compare_torrent(torrent_status const* lhs, torrent_status const* rhs)
{
if (lhs->queue_position != -1 && rhs->queue_position != -1)
{
// both are downloading, sort by queue pos
return lhs->queue_position < rhs->queue_position;
}
else if (lhs->queue_position == -1 && rhs->queue_position == -1)
{
// both are seeding, sort by seed-rank
if (lhs->seed_rank != rhs->seed_rank)
return lhs->seed_rank > rhs->seed_rank;
return lhs->info_hash < rhs->info_hash;
}
return (lhs->queue_position == -1) < (rhs->queue_position == -1);
}
void update_filtered_torrents(boost::unordered_set<torrent_status>& all_handles
, std::vector<torrent_status const*>& filtered_handles, int* counters)
{
filtered_handles.clear();
memset(counters, 0, sizeof(int) * torrents_max);
for (boost::unordered_set<torrent_status>::iterator i = all_handles.begin()
, end(all_handles.end()); i != end; ++i)
{
if (!show_torrent(*i, torrent_filter, counters)) continue;
filtered_handles.push_back(&*i);
}
if (active_torrent >= int(filtered_handles.size())) active_torrent = filtered_handles.size() - 1;
else if (active_torrent == -1 && !filtered_handles.empty()) active_torrent = 0;
std::sort(filtered_handles.begin(), filtered_handles.end(), &compare_torrent);
}
char const* esc(char const* code)
{
#ifdef ANSI_TERMINAL_COLORS
// this is a silly optimization
// to avoid copying of strings
enum { num_strings = 200 };
static char buf[num_strings][20];
static int round_robin = 0;
char* ret = buf[round_robin];
++round_robin;
if (round_robin >= num_strings) round_robin = 0;
ret[0] = '\033';
ret[1] = '[';
int i = 2;
int j = 0;
while (code[j]) ret[i++] = code[j++];
ret[i++] = 'm';
ret[i++] = 0;
return ret;
#else
return "";
#endif
}
std::string to_string(int v, int width)
{
char buf[100];
snprintf(buf, sizeof(buf), "%*d", width, v);
return buf;
}
std::string& to_string(float v, int width, int precision = 3)
{
// this is a silly optimization
// to avoid copying of strings
enum { num_strings = 20 };
static std::string buf[num_strings];
static int round_robin = 0;
std::string& ret = buf[round_robin];
++round_robin;
if (round_robin >= num_strings) round_robin = 0;
ret.resize(20);
int size = snprintf(&ret[0], 20, "%*.*f", width, precision, v);
ret.resize((std::min)(size, width));
return ret;
}
std::string add_suffix(float val, char const* suffix = 0)
{
std::string ret;
if (val == 0)
{
ret.resize(4 + 2, ' ');
if (suffix) ret.resize(4 + 2 + strlen(suffix), ' ');
return ret;
}
const char* prefix[] = {"kB", "MB", "GB", "TB"};
const int num_prefix = sizeof(prefix) / sizeof(const char*);
for (int i = 0; i < num_prefix; ++i)
{
val /= 1000.f;
if (std::fabs(val) < 1000.f)
{
ret = to_string(val, 4);
ret += prefix[i];
if (suffix) ret += suffix;
return ret;
}
}
ret = to_string(val, 4);
ret += "PB";
if (suffix) ret += suffix;
return ret;
}
std::string const& piece_bar(libtorrent::bitfield const& p, int width)
{
#ifdef ANSI_TERMINAL_COLORS
static const char* lookup[] =
{
// black, blue, cyan, white
"40", "44", "46", "47"
};
const int table_size = sizeof(lookup) / sizeof(lookup[0]);
#else
static const char char_lookup[] =
{ ' ', '.', ':', '-', '+', '*', '#'};
const int table_size = sizeof(char_lookup) / sizeof(char_lookup[0]);
#endif
double piece_per_char = p.size() / double(width);
static std::string bar;
bar.clear();
bar.reserve(width * 6);
bar += "[";
if (p.size() == 0)
{
for (int i = 0; i < width; ++i) bar += ' ';
bar += "]";
return bar;
}
// the [piece, piece + pieces_per_char) range is the pieces that are represented by each character
double piece = 0;
for (int i = 0; i < width; ++i, piece += piece_per_char)
{
int num_pieces = 0;
int num_have = 0;
int end = (std::max)(int(piece + piece_per_char), int(piece) + 1);
for (int k = int(piece); k < end; ++k, ++num_pieces)
if (p[k]) ++num_have;
int color = int(std::ceil(num_have / float(num_pieces) * (table_size - 1)));
#ifdef ANSI_TERMINAL_COLORS
bar += esc(lookup[color]);
bar += " ";
#else
bar += char_lookup[color];
#endif
}
#ifdef ANSI_TERMINAL_COLORS
bar += esc("0");
#endif
bar += "]";
return bar;
}
std::string const& progress_bar(int progress, int width, char const* code = "33")
{
static std::string bar;
bar.clear();
bar.reserve(width + 10);
int progress_chars = (progress * width + 500) / 1000;
bar = esc(code);
std::fill_n(std::back_inserter(bar), progress_chars, '#');
std::fill_n(std::back_inserter(bar), width - progress_chars, '-');
bar += esc("0");
return bar;
}
int peer_index(libtorrent::tcp::endpoint addr, std::vector<libtorrent::peer_info> const& peers)
{
using namespace libtorrent;
std::vector<peer_info>::const_iterator i = std::find_if(peers.begin()
, peers.end(), boost::bind(&peer_info::ip, _1) == addr);
if (i == peers.end()) return -1;
return i - peers.begin();
}
void print_peer_info(std::string& out, std::vector<libtorrent::peer_info> const& peers)
{
using namespace libtorrent;
if (print_ip) out += "IP ";
#ifndef TORRENT_DISABLE_GEO_IP
if (print_as) out += "AS ";
#endif
out += "down (total | peak ) up (total | peak ) sent-req tmo bsy rcv flags source ";
if (print_fails) out += "fail hshf ";
if (print_send_bufs) out += "rq sndb quota rcvb q-bytes ";
if (print_timers) out += "inactive wait timeout q-time ";
out += "disk rtt ";
if (print_block) out += "block-progress ";
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
out += "country ";
#endif
if (print_peer_rate) out += "peer-rate est.rec.rate ";
out += "client \n";
char str[500];
for (std::vector<peer_info>::const_iterator i = peers.begin();
i != peers.end(); ++i)
{
if (i->flags & (peer_info::handshake | peer_info::connecting | peer_info::queued))
continue;
if (print_ip)
{
snprintf(str, sizeof(str), "%-30s %-22s", (print_endpoint(i->ip) +
(i->flags & peer_info::utp_socket ? " [uTP]" : "") +
(i->flags & peer_info::i2p_socket ? " [i2p]" : "")
).c_str()
, print_endpoint(i->local_endpoint).c_str());
out += str;
}
#ifndef TORRENT_DISABLE_GEO_IP
if (print_as)
{
error_code ec;
snprintf(str, sizeof(str), "%-42s ", i->inet_as_name.c_str());
out += str;
}
#endif
char temp[10];
snprintf(temp, sizeof(temp), "%d/%d"
, i->download_queue_length
, i->target_dl_queue_length);
temp[7] = 0;
snprintf(str, sizeof(str)
, "%s%s (%s|%s) %s%s (%s|%s) %s%7s %4d%4d%4d %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c %c%c%c%c%c%c "
, esc("32"), add_suffix(i->down_speed, "/s").c_str()
, add_suffix(i->total_download).c_str(), add_suffix(i->download_rate_peak, "/s").c_str()
, esc("31"), add_suffix(i->up_speed, "/s").c_str(), add_suffix(i->total_upload).c_str()
, add_suffix(i->upload_rate_peak, "/s").c_str(), esc("0")
, temp // sent requests and target number of outstanding reqs.
, i->timed_out_requests
, i->busy_requests
, i->upload_queue_length
, (i->flags & peer_info::interesting)?'I':'.'
, (i->flags & peer_info::choked)?'C':'.'
, (i->flags & peer_info::remote_interested)?'i':'.'
, (i->flags & peer_info::remote_choked)?'c':'.'
, (i->flags & peer_info::supports_extensions)?'e':'.'
, (i->flags & peer_info::local_connection)?'l':'r'
, (i->flags & peer_info::seed)?'s':'.'
, (i->flags & peer_info::on_parole)?'p':'.'
, (i->flags & peer_info::optimistic_unchoke)?'O':'.'
, (i->read_state == peer_info::bw_limit)?'r':
(i->read_state == peer_info::bw_network)?'R':
(i->read_state == peer_info::bw_disk)?'D':'.'
, (i->write_state == peer_info::bw_limit)?'w':
(i->write_state == peer_info::bw_network)?'W':
(i->write_state == peer_info::bw_disk)?'D':'.'
, (i->flags & peer_info::snubbed)?'S':'.'
, (i->flags & peer_info::upload_only)?'U':'D'
, (i->flags & peer_info::endgame_mode)?'-':'.'
#ifndef TORRENT_DISABLE_ENCRYPTION
, (i->flags & peer_info::rc4_encrypted)?'E':
(i->flags & peer_info::plaintext_encrypted)?'e':'.'
#else
, '.'
#endif
, (i->flags & peer_info::holepunched)?'h':'.'
, (i->source & peer_info::tracker)?'T':'_'
, (i->source & peer_info::pex)?'P':'_'
, (i->source & peer_info::dht)?'D':'_'
, (i->source & peer_info::lsd)?'L':'_'
, (i->source & peer_info::resume_data)?'R':'_'
, (i->source & peer_info::incoming)?'I':'_');
out += str;
if (print_fails)
{
snprintf(str, sizeof(str), "%3d %3d "
, i->failcount, i->num_hashfails);
out += str;
}
if (print_send_bufs)
{
snprintf(str, sizeof(str), "%2d %6d (%s) %5d %6d (%s) %6d "
, i->requests_in_buffer, i->used_send_buffer, add_suffix(i->send_buffer_size).c_str()
, i->send_quota, i->used_receive_buffer, add_suffix(i->receive_buffer_size).c_str()
, i->queue_bytes);
out += str;
}
if (print_timers)
{
snprintf(str, sizeof(str), "%8d %4d %7d %6d "
, total_seconds(i->last_active)
, total_seconds(i->last_request)
, i->request_timeout
, total_seconds(i->download_queue_time));
out += str;
}
snprintf(str, sizeof(str), "%s %4d "
, add_suffix(i->pending_disk_bytes).c_str()
, i->rtt);
out += str;
if (print_block)
{
if (i->downloading_piece_index >= 0)
{
out += progress_bar(
i->downloading_progress * 1000 / i->downloading_total, 14);
}
else
{
out += progress_bar(0, 14);
}
}
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
if (i->country[0] == 0)
{
out += " ..";
}
else
{
snprintf(str, sizeof(str), " %c%c", i->country[0], i->country[1]);
out += str;
}
#endif
if (print_peer_rate)
{
bool unchoked = (i->flags & peer_info::choked) == 0;
snprintf(str, sizeof(str), " %s %s"
, add_suffix(i->remote_dl_rate, "/s").c_str()
, unchoked ? add_suffix(i->estimated_reciprocation_rate, "/s").c_str() : " ");
out += str;
}
out += " ";
if (i->flags & peer_info::handshake)
{
out += esc("31");
out += " waiting for handshake";
out += esc("0");
out += "\n";
}
else if (i->flags & peer_info::connecting)
{
out += esc("31");
out += " connecting to peer";
out += esc("0");
out += "\n";
}
else if (i->flags & peer_info::queued)
{
out += esc("33");
out += " queued";
out += esc("0");
out += "\n";
}
else
{
out += " ";
out += i->client;
out += "\n";
}
}
}
int listen_port = 6881;
int allocation_mode = libtorrent::storage_mode_sparse;
std::string save_path(".");
int torrent_upload_limit = 0;
int torrent_download_limit = 0;
std::string monitor_dir;
std::string bind_to_interface = "";
std::string outgoing_interface = "";
int poll_interval = 5;
int max_connections_per_torrent = 50;
bool seed_mode = false;
bool share_mode = false;
bool disable_storage = false;
// if non-empty, a peer that will be added to all torrents
std::string peer;
using boost::bind;
// monitored_dir is true if this torrent is added because
// it was found in the directory that is monitored. If it
// is, it should be remembered so that it can be removed
// if it's no longer in that directory.
void add_torrent(libtorrent::session& ses
, handles_t& files
, std::set<libtorrent::torrent_handle>& non_files
, std::string const& torrent
, int allocation_mode
, std::string const& save_path
, bool monitored_dir
, int torrent_upload_limit
, int torrent_download_limit)
{
using namespace libtorrent;
boost::intrusive_ptr<torrent_info> t;
error_code ec;
t = new torrent_info(torrent.c_str(), ec);
if (ec)
{
fprintf(stderr, "%s: %s\n", torrent.c_str(), ec.message().c_str());
return;
}
printf("%s\n", t->name().c_str());
add_torrent_params p;
if (seed_mode) p.flags |= add_torrent_params::flag_seed_mode;
if (disable_storage) p.storage = disabled_storage_constructor;
if (share_mode) p.flags |= add_torrent_params::flag_share_mode;
lazy_entry resume_data;
std::string filename = combine_path(save_path, combine_path(".resume", to_hex(t->info_hash().to_string()) + ".resume"));
std::vector<char> buf;
if (load_file(filename.c_str(), buf, ec) == 0)
p.resume_data = &buf;
p.ti = t;
p.save_path = save_path;
p.storage_mode = (storage_mode_t)allocation_mode;
p.flags |= add_torrent_params::flag_paused;
p.flags &= ~add_torrent_params::flag_duplicate_is_error;
p.flags |= add_torrent_params::flag_auto_managed;
p.userdata = (void*)strdup(torrent.c_str());
ses.async_add_torrent(p);
}
void scan_dir(std::string const& dir_path
, libtorrent::session& ses
, handles_t& files
, std::set<libtorrent::torrent_handle>& non_files
, int allocation_mode
, std::string const& save_path
, int torrent_upload_limit
, int torrent_download_limit)
{
std::set<std::string> valid;
using namespace libtorrent;
error_code ec;
for (directory i(dir_path, ec); !i.done(); i.next(ec))
{
std::string file = combine_path(dir_path, i.file());
if (extension(file) != ".torrent") continue;
handles_t::iterator k = files.find(file);
if (k != files.end())
{
valid.insert(file);
continue;
}
// the file has been added to the dir, start
// downloading it.
add_torrent(ses, files, non_files, file, allocation_mode
, save_path, true, torrent_upload_limit, torrent_download_limit);
valid.insert(file);
}
// remove the torrents that are no longer in the directory
for (handles_t::iterator i = files.begin(); !files.empty() && i != files.end();)
{
if (i->first.empty() || valid.find(i->first) != valid.end())
{
++i;
continue;
}
torrent_handle& h = i->second;
if (!h.is_valid())
{
files.erase(i++);
continue;
}
h.auto_managed(false);
h.pause();
// the alert handler for save_resume_data_alert
// will save it to disk
if (h.need_save_resume_data())
{
h.save_resume_data();
++num_outstanding_resume_data;
}
files.erase(i++);
}
}
torrent_status const& get_active_torrent(std::vector<torrent_status const*> const& filtered_handles)
{
if (active_torrent >= int(filtered_handles.size())
|| active_torrent < 0) active_torrent = 0;
return *filtered_handles[active_torrent];
}
void print_alert(libtorrent::alert const* a, std::string& str)
{
using namespace libtorrent;
#ifdef ANSI_TERMINAL_COLORS
if (a->category() & alert::error_notification)
{
str += esc("31");
}
else if (a->category() & (alert::peer_notification | alert::storage_notification))
{
str += esc("33");
}
#endif
str += "[";
str += time_now_string();
str += "] ";
str += a->message();
#ifdef ANSI_TERMINAL_COLORS
str += esc("0");
#endif
if (g_log_file)
fprintf(g_log_file, "[%s] %s\n", time_now_string(), a->message().c_str());
}
int save_file(std::string const& filename, std::vector<char>& v)
{
using namespace libtorrent;
file f;
error_code ec;
if (!f.open(filename, file::write_only, ec)) return -1;
if (ec) return -1;
file::iovec_t b = {&v[0], v.size()};
size_type written = f.writev(0, &b, 1, ec);
if (written != int(v.size())) return -3;
if (ec) return -3;
return 0;
}
// returns true if the alert was handled (and should not be printed to the log)
// returns false if the alert was not handled
bool handle_alert(libtorrent::session& ses, libtorrent::alert* a
, handles_t& files, std::set<libtorrent::torrent_handle>& non_files
, int* counters, boost::unordered_set<torrent_status>& all_handles
, std::vector<torrent_status const*>& filtered_handles
, bool& need_resort)
{
using namespace libtorrent;
#ifdef TORRENT_USE_OPENSSL
if (torrent_need_cert_alert* p = alert_cast<torrent_need_cert_alert>(a))
{
torrent_handle h = p->handle;
error_code ec;
file_status st;
std::string cert = combine_path("certificates", to_hex(h.info_hash().to_string())) + ".pem";
std::string priv = combine_path("certificates", to_hex(h.info_hash().to_string())) + "_key.pem";
stat_file(cert, &st, ec);
if (ec)
{
char msg[256];
snprintf(msg, sizeof(msg), "ERROR. could not load certificate %s: %s\n", cert.c_str(), ec.message().c_str());
if (g_log_file) fprintf(g_log_file, "[%s] %s\n", time_now_string(), msg);
return true;
}
stat_file(priv, &st, ec);
if (ec)
{
char msg[256];
snprintf(msg, sizeof(msg), "ERROR. could not load private key %s: %s\n", priv.c_str(), ec.message().c_str());
if (g_log_file) fprintf(g_log_file, "[%s] %s\n", time_now_string(), msg);
return true;
}
char msg[256];
snprintf(msg, sizeof(msg), "loaded certificate %s and key %s\n", cert.c_str(), priv.c_str());
if (g_log_file) fprintf(g_log_file, "[%s] %s\n", time_now_string(), msg);
h.set_ssl_certificate(cert, priv, "certificates/dhparams.pem", "1234");
h.resume();
}
#endif
if (metadata_received_alert* p = alert_cast<metadata_received_alert>(a))
{
// if we have a monitor dir, save the .torrent file we just received in it
// also, add it to the files map, and remove it from the non_files list
// to keep the scan dir logic in sync so it's not removed, or added twice
torrent_handle h = p->handle;
if (h.is_valid()) {
torrent_info const& ti = h.get_torrent_info();
create_torrent ct(ti);
entry te = ct.generate();
std::vector<char> buffer;
bencode(std::back_inserter(buffer), te);
std::string filename = ti.name() + "." + to_hex(ti.info_hash().to_string()) + ".torrent";
filename = combine_path(monitor_dir, filename);
save_file(filename, buffer);
files.insert(std::pair<std::string, libtorrent::torrent_handle>(filename, h));
non_files.erase(h);
}
}
else if (add_torrent_alert* p = alert_cast<add_torrent_alert>(a))
{
std::string filename;
if (p->params.userdata)
{
filename = (char*)p->params.userdata;
free(p->params.userdata);
}
if (p->error)
{
fprintf(stderr, "failed to add torrent: %s %s\n", filename.c_str(), p->error.message().c_str());
}
else
{
torrent_handle h = p->handle;
if (!filename.empty())
files.insert(std::pair<const std::string, torrent_handle>(filename, h));
else
non_files.insert(h);
h.set_max_connections(max_connections_per_torrent);
h.set_max_uploads(-1);
h.set_upload_limit(torrent_upload_limit);
h.set_download_limit(torrent_download_limit);
h.use_interface(outgoing_interface.c_str());
#ifndef TORRENT_DISABLE_RESOLVE_COUNTRIES
h.resolve_countries(true);
#endif
// if we have a peer specified, connect to it
if (!peer.empty())
{
char* port = (char*) strrchr((char*)peer.c_str(), ':');
if (port > 0)
{
*port++ = 0;
char const* ip = peer.c_str();
int peer_port = atoi(port);
error_code ec;
if (peer_port > 0)
h.connect_peer(tcp::endpoint(address::from_string(ip, ec), peer_port));
}
}
boost::unordered_set<torrent_status>::iterator j
= all_handles.insert(h.status()).first;
if (show_torrent(*j, torrent_filter, counters))
{
filtered_handles.push_back(&*j);
need_resort = true;
}
}
}
else if (torrent_finished_alert* p = alert_cast<torrent_finished_alert>(a))
{
p->handle.set_max_connections(max_connections_per_torrent / 2);
// write resume data for the finished torrent
// the alert handler for save_resume_data_alert
// will save it to disk
torrent_handle h = p->handle;
h.save_resume_data();
++num_outstanding_resume_data;
}
else if (save_resume_data_alert* p = alert_cast<save_resume_data_alert>(a))
{
--num_outstanding_resume_data;
torrent_handle h = p->handle;
TORRENT_ASSERT(p->resume_data);
if (p->resume_data)
{
std::vector<char> out;
bencode(std::back_inserter(out), *p->resume_data);
save_file(combine_path(h.save_path(), combine_path(".resume", to_hex(h.info_hash().to_string()) + ".resume")), out);
if (h.is_valid()
&& non_files.find(h) == non_files.end()
&& std::find_if(files.begin(), files.end()
, boost::bind(&handles_t::value_type::second, _1) == h) == files.end())
ses.remove_torrent(h);
}
}
else if (save_resume_data_failed_alert* p = alert_cast<save_resume_data_failed_alert>(a))
{
--num_outstanding_resume_data;
torrent_handle h = p->handle;
if (h.is_valid()
&& non_files.find(h) == non_files.end()
&& std::find_if(files.begin(), files.end()
, boost::bind(&handles_t::value_type::second, _1) == h) == files.end())
ses.remove_torrent(h);
}
else if (torrent_paused_alert* p = alert_cast<torrent_paused_alert>(a))
{
// write resume data for the finished torrent
// the alert handler for save_resume_data_alert
// will save it to disk
torrent_handle h = p->handle;
h.save_resume_data();
++num_outstanding_resume_data;
}
else if (state_update_alert* p = alert_cast<state_update_alert>(a))
{
bool need_filter_update = false;
for (std::vector<torrent_status>::iterator i = p->status.begin();
i != p->status.end(); ++i)
{
boost::unordered_set<torrent_status>::iterator j = all_handles.find(*i);
// don't add new entries here, that's done in the handler
// for add_torrent_alert
if (j == all_handles.end()) continue;
if (j->state != i->state
|| j->paused != i->paused
|| j->auto_managed != i->auto_managed)
need_filter_update = true;
((torrent_status&)*j) = *i;
}
if (need_filter_update)
update_filtered_torrents(all_handles, filtered_handles, counters);
return true;
}
return false;
}
void print_piece(libtorrent::partial_piece_info* pp
, libtorrent::cached_piece_info* cs
, std::vector<libtorrent::peer_info> const& peers
, std::string& out)
{
using namespace libtorrent;
char str[1024];
assert(pp == 0 || cs == 0 || cs->piece == pp->piece_index);
int piece = pp ? pp->piece_index : cs->piece;
int num_blocks = pp ? pp->blocks_in_piece : cs->blocks.size();
snprintf(str, sizeof(str), "%5d: [", piece);
out += str;
char const* last_color = 0;
for (int j = 0; j < num_blocks; ++j)
{
int index = pp ? peer_index(pp->blocks[j].peer(), peers) % 36 : -1;
char chr = '+';
if (index >= 0)
chr = (index < 10)?'0' + index:'A' + index - 10;
char const* color = "";
if (pp == 0)
{
color = cs->blocks[j] ? esc("34;7") : esc("0");
chr = ' ';
}
else
{
#ifdef ANSI_TERMINAL_COLORS
if (cs && cs->blocks[j]) color = esc("36;7");
else if (pp->blocks[j].bytes_progress > 0
&& pp->blocks[j].state == block_info::requested)
{
if (pp->blocks[j].num_peers > 1) color = esc("1;7");
else color = esc("33;7");
chr = '0' + (pp->blocks[j].bytes_progress * 10 / pp->blocks[j].block_size);
}
else if (pp->blocks[j].state == block_info::finished) color = esc("32;7");
else if (pp->blocks[j].state == block_info::writing) color = esc("36;7");
else if (pp->blocks[j].state == block_info::requested) color = esc("0");
else { color = esc("0"); chr = ' '; }
#else
if (cs && cs->blocks[j]) chr = 'c';
else if (pp->blocks[j].state == block_info::finished) chr = '#';
else if (pp->blocks[j].state == block_info::writing) chr = '+';
else if (pp->blocks[j].state == block_info::requested) chr = '-';
else chr = ' ';
#endif
}
if (last_color == 0 || strcmp(last_color, color) != 0)
snprintf(str, sizeof(str), "%s%c", color, chr);
else
out += chr;
out += str;
}
#ifdef ANSI_TERMINAL_COLORS
out += esc("0");
#endif
char const* piece_state[4] = {"", " slow", " medium", " fast"};
snprintf(str, sizeof(str), "] %3d cache age: %-.1f %s\n"
, cs ? cs->next_to_hash : 0
, cs ? (total_milliseconds(time_now() - cs->last_use) / 1000.f) : 0.f
, pp ? piece_state[pp->piece_state] : "");
out += str;
}
static char const* state_str[] =
{"checking (q)", "checking", "dl metadata"
, "downloading", "finished", "seeding", "allocating", "checking (r)"};
int main(int argc, char* argv[])
{
if (argc == 1)
{
fprintf(stderr, "usage: client_test [OPTIONS] [TORRENT|MAGNETURL|URL]\n\n"
"OPTIONS:\n"
"\n CLIENT OPTIONS\n"
" -f <log file> logs all events to the given file\n"
" -s <path> sets the save path for downloads\n"
" -m <path> sets the .torrent monitor directory\n"
" -t <seconds> sets the scan interval of the monitor dir\n"
" -F <milliseconds> sets the UI refresh rate. This is the number of\n"
" milliseconds between screen refreshes.\n"
" -q <num loops> automatically quit the client after <num loops> of refreshes\n"
" this is useful for scripting tests\n"
" -k enable high performance settings. This overwrites any other\n"
" previous command line options, so be sure to specify this first\n"
" -G Add torrents in seed-mode (i.e. assume all pieces\n"
" are present and check hashes on-demand)\n"
"\n BITTORRENT OPTIONS\n"
" -c <limit> sets the max number of connections\n"
" -T <limit> sets the max number of connections per torrent\n"
" -U <rate> sets per-torrent upload rate\n"
" -D <rate> sets per-torrent download rate\n"
" -d <rate> limits the download rate\n"
" -u <rate> limits the upload rate\n"
" -S <limit> limits the upload slots\n"
" -A <num pieces> allowed pieces set size\n"
" -H Don't start DHT\n"
" -X Don't start local peer discovery\n"
" -n announce to trackers in all tiers\n"
" -W <num peers> Set the max number of peers to keep in the peer list\n"
" -B <seconds> sets the peer timeout\n"
" -Q enables share mode. Share mode attempts to maximize\n"
" share ratio rather than downloading\n"
" -r <IP:port> connect to specified peer\n"
#ifndef TORRENT_DISABLE_ENCRYPTION
" -e force encrypted bittorrent connections\n"
#endif
"\n QUEING OPTIONS\n"
" -v <limit> Set the max number of active downloads\n"
" -^ <limit> Set the max number of active seeds\n"
"\n NETWORK OPTIONS\n"
" -p <port> sets the listen port\n"
" -o <limit> limits the number of simultaneous\n"
" half-open TCP connections to the\n"
" given number.\n"
" -w <seconds> sets the retry time for failed web seeds\n"
" -x <file> loads an emule IP-filter file\n"
" -P <host:port> Use the specified SOCKS5 proxy\n"
" -L <user:passwd> Use the specified username and password for the\n"
" proxy specified by -P\n"
" -h allow multiple connections from the same IP\n"
" -M Disable TCP/uTP bandwidth balancing\n"
" -N Do not attempt to use UPnP and NAT-PMP to forward ports\n"
" -Y Rate limit local peers\n"
" -y Disable TCP connections (disable outgoing TCP and reject\n"
" incoming TCP connections)\n"
" -b <IP> sets IP of the interface to bind the\n"
" listen socket to\n"
" -I <IP> sets the IP of the interface to bind\n"
" outgoing peer connections to\n"
#if TORRENT_USE_I2P
" -i <i2p-host> the hostname to an I2P SAM bridge to use\n"
#endif
" -l <limit> sets the listen socket queue size\n"
"\n DISK OPTIONS\n"
" -a <mode> sets the allocation mode. [sparse|allocate]\n"
" -R <num blocks> number of blocks per read cache line\n"
" -C <limit> sets the max cache size. Specified in 16kB blocks\n"
" -O Disallow disk job reordering\n"
" -j disable disk read-ahead\n"
" -z disable piece hash checks (used for benchmarking)\n"
" -0 disable disk I/O, read garbage and don't flush to disk\n"
"\n\n"
"TORRENT is a path to a .torrent file\n"
"MAGNETURL is a magnet link\n"
"URL is a url to a torrent file\n"
"\n"
"Example for running benchmark:\n\n"
" client_test -k -z -N -h -H -M -l 2000 -S 1000 -T 1000 -c 1000 test.torrent\n");
;
return 0;
}
using namespace libtorrent;
session_settings settings;
proxy_settings ps;
int refresh_delay = 1000;
bool start_dht = true;
bool start_upnp = true;
bool start_lsd = true;
int loop_limit = 0;
std::deque<std::string> events;
ptime next_dir_scan = time_now();
// the string is the filename of the .torrent file, but only if
// it was added through the directory monitor. It is used to
// be able to remove torrents that were added via the directory
// monitor when they're not in the directory anymore.
boost::unordered_set<torrent_status> all_handles;
std::vector<torrent_status const*> filtered_handles;
handles_t files;
// torrents that were not added via the monitor dir
std::set<torrent_handle> non_files;
int counters[torrents_max];
memset(counters, 0, sizeof(counters));
session ses(fingerprint("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0)
, session::add_default_plugins
, alert::all_categories
& ~(alert::dht_notification
+ alert::progress_notification
+ alert::debug_notification
+ alert::stats_notification));
std::vector<char> in;
error_code ec;
if (load_file(".ses_state", in, ec) == 0)
{
lazy_entry e;
if (lazy_bdecode(&in[0], &in[0] + in.size(), e, ec) == 0)
ses.load_state(e);
}
#ifndef TORRENT_DISABLE_GEO_IP
ses.load_asnum_db("GeoIPASNum.dat");
ses.load_country_db("GeoIP.dat");
#endif
// load the torrents given on the commandline
std::vector<add_torrent_params> magnet_links;
std::vector<std::string> torrents;
for (int i = 1; i < argc; ++i)
{
if (argv[i][0] != '-')
{
// match it against the <hash>@<tracker> format
if (strlen(argv[i]) > 45
&& is_hex(argv[i], 40)
&& (strncmp(argv[i] + 40, "@http://", 8) == 0
|| strncmp(argv[i] + 40, "@udp://", 7) == 0))
{
sha1_hash info_hash;
from_hex(argv[i], 40, (char*)&info_hash[0]);
add_torrent_params p;
if (seed_mode) p.flags |= add_torrent_params::flag_seed_mode;
if (disable_storage) p.storage = disabled_storage_constructor;
if (share_mode) p.flags |= add_torrent_params::flag_share_mode;
p.trackers.push_back(argv[i] + 41);
p.info_hash = info_hash;
p.save_path = save_path;
p.storage_mode = (storage_mode_t)allocation_mode;
p.flags |= add_torrent_params::flag_paused;
p.flags &= ~add_torrent_params::flag_duplicate_is_error;
p.flags |= add_torrent_params::flag_auto_managed;
magnet_links.push_back(p);
continue;
}
torrents.push_back(argv[i]);
continue;
}
// if there's a flag but no argument following, ignore it
if (argc == i) continue;
char const* arg = argv[i+1];
if (arg == NULL) arg = "";
switch (argv[i][1])
{
case 'f': g_log_file = fopen(arg, "w+"); break;
case 'o': settings.half_open_limit = atoi(arg); break;
case 'h': settings.allow_multiple_connections_per_ip = true; --i; break;
case 'p': listen_port = atoi(arg); break;
case 'k': settings = high_performance_seed(); --i; break;
case 'j': settings.use_disk_read_ahead = false; --i; break;
case 'z': settings.disable_hash_checks = true; --i; break;
case 'B': settings.peer_timeout = atoi(arg); break;
case 'n': settings.announce_to_all_tiers = true; --i; break;
case 'G': seed_mode = true; --i; break;
case 'd': settings.download_rate_limit = atoi(arg) * 1000; break;
case 'u': settings.upload_rate_limit = atoi(arg) * 1000; break;
case 'S': settings.unchoke_slots_limit = atoi(arg); break;
case 'a':
if (strcmp(arg, "allocate") == 0) allocation_mode = storage_mode_allocate;
else if (strcmp(arg, "full") == 0) allocation_mode = storage_mode_allocate;
else if (strcmp(arg, "sparse") == 0) allocation_mode = storage_mode_sparse;
break;
case 's': save_path = arg; break;
case 'U': torrent_upload_limit = atoi(arg) * 1000; break;
case 'D': torrent_download_limit = atoi(arg) * 1000; break;
case 'm': monitor_dir = arg; break;
case 'Q': share_mode = true; --i; break;
case 'b': bind_to_interface = arg; break;
case 'w': settings.urlseed_wait_retry = atoi(arg); break;
case 't': poll_interval = atoi(arg); break;
case 'F': refresh_delay = atoi(arg); break;
case 'H': start_dht = false; --i; break;
case 'l': settings.listen_queue_size = atoi(arg); break;
#ifndef TORRENT_DISABLE_ENCRYPTION
case 'e':
{
pe_settings s;
s.out_enc_policy = libtorrent::pe_settings::forced;
s.in_enc_policy = libtorrent::pe_settings::forced;
s.allowed_enc_level = pe_settings::rc4;
s.prefer_rc4 = true;
ses.set_pe_settings(s);
--i;
break;
}
#endif
case 'W':
settings.max_peerlist_size = atoi(arg);
settings.max_paused_peerlist_size = atoi(arg) / 2;
break;
case 'x':
{
FILE* filter = fopen(arg, "r");
if (filter)
{
ip_filter fil;
unsigned int a,b,c,d,e,f,g,h, flags;
while (fscanf(filter, "%u.%u.%u.%u - %u.%u.%u.%u %u\n", &a, &b, &c, &d, &e, &f, &g, &h, &flags) == 9)
{
address_v4 start((a << 24) + (b << 16) + (c << 8) + d);
address_v4 last((e << 24) + (f << 16) + (g << 8) + h);
if (flags <= 127) flags = ip_filter::blocked;
else flags = 0;
fil.add_rule(start, last, flags);
}
ses.set_ip_filter(fil);
fclose(filter);
}
}
break;
case 'c': settings.connections_limit = atoi(arg); break;
case 'T': max_connections_per_torrent = atoi(arg); break;
#if TORRENT_USE_I2P
case 'i':
{
proxy_settings ps;
ps.hostname = arg;
ps.port = 7656; // default SAM port
ps.type = proxy_settings::i2p_proxy;
ses.set_i2p_proxy(ps);
break;
}
#endif // TORRENT_USE_I2P
case 'C':
settings.cache_size = atoi(arg);
settings.use_read_cache = settings.cache_size > 0;
settings.cache_buffer_chunk_size = settings.cache_size / 100;
break;
case 'A': settings.allowed_fast_set_size = atoi(arg); break;
case 'R': settings.read_cache_line_size = atoi(arg); break;
case 'O': settings.allow_reordered_disk_operations = false; --i; break;
case 'M': settings.mixed_mode_algorithm = session_settings::prefer_tcp; --i; break;
case 'y': settings.enable_outgoing_tcp = false; settings.enable_incoming_tcp = false; --i; break;
case 'r': peer = arg; break;
case 'P':
{
char* port = (char*) strrchr(arg, ':');
if (port == 0)
{
fprintf(stderr, "invalid proxy hostname, no port found\n");
break;
}
*port++ = 0;
ps.hostname = arg;
ps.port = atoi(port);
if (ps.port == 0) {
fprintf(stderr, "invalid proxy port\n");
break;
}
if (ps.type == proxy_settings::none)
ps.type = proxy_settings::socks5;
}
break;
case 'L':
{
char* pw = (char*) strchr(arg, ':');
if (pw == 0)
{
fprintf(stderr, "invalid proxy username and password specified\n");
break;
}
*pw++ = 0;
ps.username = arg;
ps.password = pw;
ps.type = proxy_settings::socks5_pw;
}
break;
case 'I': outgoing_interface = arg; break;
case 'N': start_upnp = false; --i; break;
case 'X': start_lsd = false; --i; break;
case 'Y': settings.ignore_limits_on_local_network = false; --i; break;
case 'v': settings.active_downloads = atoi(arg);
settings.active_limit = (std::max)(atoi(arg) * 2, settings.active_limit);
break;
case '^':
settings.active_seeds = atoi(arg);
settings.active_limit = (std::max)(atoi(arg) * 2, settings.active_limit);
break;
case 'q': loop_limit = atoi(arg); break;
case '0': disable_storage = true; --i;
}
++i; // skip the argument
}
// create directory for resume files
create_directory(combine_path(save_path, ".resume"), ec);
if (ec)
fprintf(stderr, "failed to create resume file directory: %s\n", ec.message().c_str());
if (start_lsd)
ses.start_lsd();
if (start_upnp)
{
ses.start_upnp();
ses.start_natpmp();
}
ses.set_proxy(ps);
ses.listen_on(std::make_pair(listen_port, listen_port)
, ec, bind_to_interface.c_str());
if (ec)
{
fprintf(stderr, "failed to listen%s%s on ports %d-%d: %s\n"
, bind_to_interface.empty() ? "" : " on ", bind_to_interface.c_str()
, listen_port, listen_port+1, ec.message().c_str());
}
#ifndef TORRENT_DISABLE_DHT
if (start_dht)
{
settings.use_dht_as_fallback = false;
ses.add_dht_router(std::make_pair(
std::string("router.bittorrent.com"), 6881));
ses.add_dht_router(std::make_pair(
std::string("router.utorrent.com"), 6881));
ses.add_dht_router(std::make_pair(
std::string("router.bitcomet.com"), 6881));
ses.start_dht();
}
#endif
settings.user_agent = "client_test/" LIBTORRENT_VERSION;
settings.choking_algorithm = session_settings::auto_expand_choker;
settings.disk_cache_algorithm = session_settings::avoid_readback;
settings.volatile_read_cache = false;
ses.set_settings(settings);
for (std::vector<add_torrent_params>::iterator i = magnet_links.begin()
, end(magnet_links.end()); i != end; ++i)
{
ses.async_add_torrent(*i);
}
for (std::vector<std::string>::iterator i = torrents.begin()
, end(torrents.end()); i != end; ++i)
{
if (std::strstr(i->c_str(), "http://") == i->c_str()
|| std::strstr(i->c_str(), "https://") == i->c_str()
|| std::strstr(i->c_str(), "magnet:") == i->c_str())
{
add_torrent_params p;
if (seed_mode) p.flags |= add_torrent_params::flag_seed_mode;
if (disable_storage) p.storage = disabled_storage_constructor;
if (share_mode) p.flags |= add_torrent_params::flag_share_mode;
p.save_path = save_path;
p.storage_mode = (storage_mode_t)allocation_mode;
p.url = *i;
std::vector<char> buf;
if (std::strstr(i->c_str(), "magnet:") == i->c_str())
{
add_torrent_params tmp;
ec.clear();
parse_magnet_uri(*i, tmp, ec);
if (ec) continue;
std::string filename = combine_path(save_path, combine_path(".resume"
, to_hex(tmp.info_hash.to_string()) + ".resume"));
if (load_file(filename.c_str(), buf, ec) == 0)
p.resume_data = &buf;
}
printf("adding URL: %s\n", i->c_str());
ses.async_add_torrent(p);
continue;
}
// if it's a torrent file, open it as usual
add_torrent(ses, files, non_files, i->c_str()
, allocation_mode, save_path, false
, torrent_upload_limit, torrent_download_limit);
}
// main loop
std::vector<peer_info> peers;
std::vector<partial_piece_info> queue;
int tick = 0;
while (loop_limit > 1 || loop_limit == 0)
{
++tick;
ses.post_torrent_updates();
if (active_torrent >= int(filtered_handles.size())) active_torrent = filtered_handles.size() - 1;
if (active_torrent >= 0)
{
// ask for distributed copies for the selected torrent. Since this
// is a somewhat expensive operation, don't do it by default for
// all torrents
torrent_status const& h = *filtered_handles[active_torrent];
h.handle.status(
torrent_handle::query_distributed_copies
| torrent_handle::query_pieces
| torrent_handle::query_verified_pieces);
}
std::vector<feed_handle> feeds;
ses.get_feeds(feeds);
counters[torrents_feeds] = feeds.size();
std::sort(filtered_handles.begin(), filtered_handles.end(), &compare_torrent);
if (loop_limit > 1) --loop_limit;
int c = 0;
while (sleep_and_input(&c, refresh_delay))
{
if (c == EOF) { break; }
if (c == 27)
{
// escape code, read another character
#ifdef _WIN32
c = _getch();
#else
int c = getc(stdin);
#endif
if (c == EOF) { break; }
if (c != '[') continue;
#ifdef _WIN32
c = _getch();
#else
c = getc(stdin);
#endif
if (c == EOF) break;
if (c == 68)
{
// arrow left
if (torrent_filter > 0)
{
--torrent_filter;
update_filtered_torrents(all_handles, filtered_handles, counters);
}
}
else if (c == 67)
{
// arrow right
if (torrent_filter < torrents_max - 1)
{
++torrent_filter;
update_filtered_torrents(all_handles, filtered_handles, counters);
}
}
else if (c == 65)
{
// arrow up
--active_torrent;
if (active_torrent < 0) active_torrent = 0;
}
else if (c == 66)
{
// arrow down
++active_torrent;
if (active_torrent >= int(filtered_handles.size()))
active_torrent = filtered_handles.size() - 1;
}
}
if (c == ' ')
{
if (ses.is_paused()) ses.resume();
else ses.pause();
}
// add magnet link
if (c == 'm')
{
char url[4096];
puts("Enter magnet link:\n");
scanf("%4096s", url);
add_torrent_params p;
if (seed_mode) p.flags |= add_torrent_params::flag_seed_mode;
if (disable_storage) p.storage = disabled_storage_constructor;
if (share_mode) p.flags |= add_torrent_params::flag_share_mode;
p.save_path = save_path;
p.storage_mode = (storage_mode_t)allocation_mode;
p.url = url;
std::vector<char> buf;
if (std::strstr(url, "magnet:") == url)
{
add_torrent_params tmp;
parse_magnet_uri(url, tmp, ec);
if (ec) continue;
std::string filename = combine_path(save_path, combine_path(".resume"
, to_hex(tmp.info_hash.to_string()) + ".resume"));
if (load_file(filename.c_str(), buf, ec) == 0)
p.resume_data = &buf;
}
printf("adding URL: %s\n", url);
ses.async_add_torrent(p);
}
if (c == 'M')
{
printf("saving peers for torrents\n");
std::vector<peer_list_entry> peers;
std::vector<torrent_handle> torrents = ses.get_torrents();
for (std::vector<torrent_handle>::iterator i = torrents.begin();
i != torrents.end(); ++i)
{
i->get_full_peer_list(peers);
FILE* f = fopen(("peers_" + i->name()).c_str(), "w+");
if (!f) break;
for (std::vector<peer_list_entry>::iterator k = peers.begin()
, end(peers.end()); k != end; ++k)
{
fprintf(f, "%s\t%d\n", print_address(k->ip.address()).c_str()
#ifndef TORRENT_DISABLE_GEO_IP
, ses.as_for_ip(k->ip.address())
#else
, 0
#endif
);
}
}
}
if (c == 'q') break;
if (c == 'D')
{
torrent_handle h = get_active_torrent(filtered_handles).handle;
if (h.is_valid())
{
printf("\n\nARE YOU SURE YOU WANT TO DELETE THE FILES FOR '%s'. THIS OPERATION CANNOT BE UNDONE. (y/N)"
, h.name().c_str());
char response = 'n';
scanf("%c", &response);
if (response == 'y')
{
// also delete the .torrent file from the torrent directory
handles_t::iterator i = std::find_if(files.begin(), files.end()
, boost::bind(&handles_t::value_type::second, _1) == h);
if (i != files.end())
{
error_code ec;
remove(combine_path(monitor_dir, i->first), ec);
if (ec) printf("failed to delete .torrent file: %s\n", ec.message().c_str());
files.erase(i);
}
if (h.is_valid())
ses.remove_torrent(h, session::delete_files);
}
}
}
if (c == 'j' && !filtered_handles.empty())
{
get_active_torrent(filtered_handles).handle.force_recheck();
}
if (c == 'r' && !filtered_handles.empty())
{
get_active_torrent(filtered_handles).handle.force_reannounce();
}
if (c == 's' && !filtered_handles.empty())
{
torrent_status const& ts = get_active_torrent(filtered_handles);
ts.handle.set_sequential_download(!ts.sequential_download);
}
if (c == 'R')
{
// save resume data for all torrents
for (std::vector<torrent_status const*>::iterator i = filtered_handles.begin()
, end(filtered_handles.end()); i != end; ++i)
{
if ((*i)->need_save_resume)
{
(*i)->handle.save_resume_data();
++num_outstanding_resume_data;
}
}
}
if (c == 'o' && !filtered_handles.empty())
{
torrent_status const& ts = get_active_torrent(filtered_handles);
int num_pieces = ts.num_pieces;
if (num_pieces > 300) num_pieces = 300;
for (int i = 0; i < num_pieces; ++i)
{
ts.handle.set_piece_deadline(i, (i+5) * 1000, torrent_handle::alert_when_available);
}
}
if (c == 'v' && !filtered_handles.empty())
{
torrent_status const& ts = get_active_torrent(filtered_handles);
ts.handle.scrape_tracker();
}
if (c == 'p' && !filtered_handles.empty())
{
torrent_status const& ts = get_active_torrent(filtered_handles);
if (!ts.auto_managed && ts.paused)
{
ts.handle.auto_managed(true);
}
else
{
ts.handle.auto_managed(false);
ts.handle.pause(torrent_handle::graceful_pause);
}
}
// toggle force-start
if (c == 'k' && !filtered_handles.empty())
{
torrent_status const& ts = get_active_torrent(filtered_handles);
ts.handle.auto_managed(!ts.auto_managed);
if (ts.auto_managed && ts.paused) ts.handle.resume();
}
if (c == 'c' && !filtered_handles.empty())
{
torrent_status const& ts = get_active_torrent(filtered_handles);
ts.handle.clear_error();
}
// toggle displays
if (c == 't') print_trackers = !print_trackers;
if (c == 'i') print_peers = !print_peers;
if (c == 'l') print_log = !print_log;
if (c == 'd') print_downloads = !print_downloads;
if (c == 'f') print_file_progress = !print_file_progress;
if (c == 'h') show_pad_files = !show_pad_files;
if (c == 'a') print_piece_bar = !print_piece_bar;
if (c == 'g') show_dht_status = !show_dht_status;
if (c == 'u') print_utp_stats = !print_utp_stats;
// toggle columns
if (c == '1') print_ip = !print_ip;
if (c == '2') print_as = !print_as;
if (c == '3') print_timers = !print_timers;
if (c == '4') print_block = !print_block;
if (c == '5') print_peer_rate = !print_peer_rate;
if (c == '6') print_fails = !print_fails;
if (c == '7') print_send_bufs = !print_send_bufs;
if (c == 'y')
{
char url[2048];
puts("Enter RSS feed URL:\n");
scanf("%2048s", url);
feed_settings set;
set.url = url;
set.add_args.save_path = save_path;
feed_handle h = ses.add_feed(set);
h.update_feed();
}
}
if (c == 'q') break;
int terminal_width = 80;
int terminal_height = 50;
#ifndef _WIN32
{
winsize size;
int ret = ioctl(STDOUT_FILENO, TIOCGWINSZ, (char*)&size);
if (ret == 0)
{
terminal_width = size.ws_col;
terminal_height = size.ws_row;
if (terminal_width < 64)
terminal_width = 64;
if (terminal_height < 25)
terminal_height = 25;
}
else
{
terminal_width = 190;
terminal_height = 100;
}
}
#endif
// loop through the alert queue to see if anything has happened.
std::deque<alert*> alerts;
ses.pop_alerts(&alerts);
std::string now = time_now_string();
for (std::deque<alert*>::iterator i = alerts.begin()
, end(alerts.end()); i != end; ++i)
{
bool need_resort = false;
TORRENT_TRY
{
if (!::handle_alert(ses, *i, files, non_files, counters
, all_handles, filtered_handles, need_resort))
{
// if we didn't handle the alert, print it to the log
std::string event_string;
print_alert(*i, event_string);
events.push_back(event_string);
if (events.size() >= 20) events.pop_front();
}
} TORRENT_CATCH(std::exception& e) {}
if (need_resort)
{
std::sort(filtered_handles.begin(), filtered_handles.end()
, &compare_torrent);
}
delete *i;
}
alerts.clear();
session_status sess_stat = ses.status();
// in test mode, also quit when we loose the last peer
if (loop_limit > 1 && sess_stat.num_peers == 0 && tick > 30) break;
std::string out;
out = "[q] quit [i] toggle peers [d] toggle downloading pieces [p] toggle paused "
"[a] toggle piece bar [s] toggle download sequential [f] toggle files [m] add magnet"
"[j] force recheck [space] toggle session pause [c] clear error [v] scrape [g] show DHT\n"
"[1] toggle IP [2] toggle AS [3] toggle timers [4] toggle block progress "
"[5] toggle peer rate [6] toggle failures [7] toggle send buffers [R] save resume data\n";
char const* filter_names[] = { "all", "downloading", "non-paused", "seeding", "queued", "stopped", "checking", "RSS"};
for (int i = 0; i < int(sizeof(filter_names)/sizeof(filter_names[0])); ++i)
{
char filter[200];
snprintf(filter, sizeof(filter), "%s[%s (%d)]%s", torrent_filter == i?esc("7"):""
, filter_names[i], counters[i], torrent_filter == i?esc("0"):"");
out += filter;
}
out += '\n';
char str[500];
int torrent_index = 0;
int lines_printed = 3;
if (torrent_filter == torrents_feeds)
{
for (std::vector<feed_handle>::iterator i = feeds.begin()
, end(feeds.end()); i != end; ++i)
{
if (lines_printed >= terminal_height - 15)
{
out += "...\n";
break;
}
feed_status st = i->get_feed_status();
if (st.url.size() > 70) st.url.resize(70);
char update_timer[20];
snprintf(update_timer, sizeof(update_timer), "%d", st.next_update);
snprintf(str, sizeof(str), "%-70s %s (%2d) %s\n", st.url.c_str()
, st.updating ? "updating" : update_timer
, int(st.items.size())
, st.error ? st.error.message().c_str() : "");
out += str;
++lines_printed;
}
}
for (std::vector<torrent_status const*>::iterator i = filtered_handles.begin();
i != filtered_handles.end(); ++torrent_index)
{
if (lines_printed >= terminal_height - 15)
{
out += "...\n";
break;
}
torrent_status const& s = **i;
if (!s.handle.is_valid())
{
i = filtered_handles.erase(i);
continue;
}
else
{
++i;
}
#ifdef ANSI_TERMINAL_COLORS
char const* term = "\x1b[0m";
#else
char const* term = "";
#endif
if (active_torrent == torrent_index)
{
#ifdef ANSI_TERMINAL_COLORS
term = "\x1b[0m\x1b[7m";
out += esc("7");
#endif
out += "*";
}
else
{
out += " ";
}
int queue_pos = s.queue_position;
if (queue_pos == -1) out += "- ";
else
{
snprintf(str, sizeof(str), "%-3d", queue_pos);
out += str;
}
if (s.paused) out += esc("34");
else out += esc("37");
std::string name = s.handle.name();
if (name.size() > 40) name.resize(40);
snprintf(str, sizeof(str), "%-40s %s ", name.c_str(), term);
out += str;
if (!s.error.empty())
{
out += esc("31");
out += "error ";
out += s.error;
out += esc("0");
out += "\n";
++lines_printed;
continue;
}
int seeds = 0;
int downloaders = 0;
if (s.num_complete >= 0) seeds = s.num_complete;
else seeds = s.list_seeds;
if (s.num_incomplete >= 0) downloaders = s.num_incomplete;
else downloaders = s.list_peers - s.list_seeds;
snprintf(str, sizeof(str), "%s%-13s down: (%s%s%s) up: %s%s%s (%s%s%s) swarm: %4d:%4d"
" bw queue: (%d|%d) all-time (Rx: %s%s%s Tx: %s%s%s) seed rank: %x %c%s\n"
, (!s.paused && !s.auto_managed)?"[F] ":""
, (s.paused && !s.auto_managed)?"paused":
(s.paused && s.auto_managed)?"queued":
state_str[s.state]
, esc("32"), add_suffix(s.total_download).c_str(), term
, esc("31"), add_suffix(s.upload_rate, "/s").c_str(), term
, esc("31"), add_suffix(s.total_upload).c_str(), term
, downloaders, seeds
, s.up_bandwidth_queue, s.down_bandwidth_queue
, esc("32"), add_suffix(s.all_time_download).c_str(), term
, esc("31"), add_suffix(s.all_time_upload).c_str(), term
, s.seed_rank, s.need_save_resume?'S':' ', esc("0"));
out += str;
++lines_printed;
if (torrent_index != active_torrent && s.state == torrent_status::seeding) continue;
char const* progress_bar_color = "33"; // yellow
if (s.state == torrent_status::downloading_metadata)
{
progress_bar_color = "35"; // magenta
}
else if (s.current_tracker.empty())
{
progress_bar_color = "31"; // red
}
else if (sess_stat.has_incoming_connections)
{
progress_bar_color = "32"; // green
}
snprintf(str, sizeof(str), " %-10s: %s%-11" PRId64 "%s Bytes %6.2f%% %s\n"
, s.sequential_download?"sequential":"progress"
, esc("32"), s.total_done, esc("0")
, s.progress_ppm / 10000.f
, progress_bar(s.progress_ppm / 1000, terminal_width - 43, progress_bar_color).c_str());
out += str;
++lines_printed;
if (print_piece_bar && (s.state != torrent_status::seeding || s.seed_mode))
{
out += " ";
out += piece_bar(s.pieces, terminal_width - 7);
out += "\n";
++lines_printed;
if (s.seed_mode)
{
out += " ";
out += piece_bar(s.verified_pieces, terminal_width - 7);
out += "\n";
++lines_printed;
}
}
if (s.state != torrent_status::queued_for_checking && s.state != torrent_status::checking_files)
{
boost::posix_time::time_duration t = s.next_announce;
snprintf(str, sizeof(str)
, " peers: %s%d%s (%s%d%s) seeds: %s%d%s distributed copies: %s%4.2f%s "
"sparse regions: %d download: %s%s%s next announce: %s%02d:%02d:%02d%s "
"tracker: %s%s%s\n"
, esc("37"), s.num_peers, esc("0")
, esc("37"), s.connect_candidates, esc("0")
, esc("37"), s.num_seeds, esc("0")
, esc("37"), s.distributed_copies, esc("0")
, s.sparse_regions
, esc("32"), add_suffix(s.download_rate, "/s").c_str(), esc("0")
, esc("37"), int(t.hours()), int(t.minutes()), int(t.seconds()), esc("0")
, esc("36"), s.current_tracker.c_str(), esc("0"));
out += str;
++lines_printed;
}
}
cache_status cs = ses.get_cache_status();
if (cs.blocks_read < 1) cs.blocks_read = 1;
if (cs.blocks_written < 1) cs.blocks_written = 1;
snprintf(str, sizeof(str), "==== conns: %d down: %s%s%s (%s%s%s) up: %s%s%s (%s%s%s) "
"tcp/ip: %s%s%s %s%s%s DHT: %s%s%s %s%s%s tracker: %s%s%s %s%s%s ====\n"
, sess_stat.num_peers
, esc("32"), add_suffix(sess_stat.download_rate, "/s").c_str(), esc("0")
, esc("32"), add_suffix(sess_stat.total_download).c_str(), esc("0")
, esc("31"), add_suffix(sess_stat.upload_rate, "/s").c_str(), esc("0")
, esc("31"), add_suffix(sess_stat.total_upload).c_str(), esc("0")
, esc("32"), add_suffix(sess_stat.ip_overhead_download_rate, "/s").c_str(), esc("0")
, esc("31"), add_suffix(sess_stat.ip_overhead_upload_rate, "/s").c_str(), esc("0")
, esc("32"), add_suffix(sess_stat.dht_download_rate, "/s").c_str(), esc("0")
, esc("31"), add_suffix(sess_stat.dht_upload_rate, "/s").c_str(), esc("0")
, esc("32"), add_suffix(sess_stat.tracker_download_rate, "/s").c_str(), esc("0")
, esc("31"), add_suffix(sess_stat.tracker_upload_rate, "/s").c_str(), esc("0"));
out += str;
snprintf(str, sizeof(str), "==== waste: %s fail: %s unchoked: %d / %d "
"bw queues: %8d (%d) | %8d (%d) disk queues: %d | %d cache: w: %" PRId64 "%% r: %" PRId64 "%% "
"size: %s (%s) / %s dq: %" PRId64 " ===\n"
, add_suffix(sess_stat.total_redundant_bytes).c_str()
, add_suffix(sess_stat.total_failed_bytes).c_str()
, sess_stat.num_unchoked, sess_stat.allowed_upload_slots
, sess_stat.up_bandwidth_bytes_queue
, sess_stat.up_bandwidth_queue
, sess_stat.down_bandwidth_bytes_queue
, sess_stat.down_bandwidth_queue
, sess_stat.disk_write_queue
, sess_stat.disk_read_queue
, (cs.blocks_written - cs.writes) * 100 / cs.blocks_written
, cs.blocks_read_hit * 100 / cs.blocks_read
, add_suffix(boost::int64_t(cs.cache_size) * 16 * 1024).c_str()
, add_suffix(boost::int64_t(cs.read_cache_size) * 16 * 1024).c_str()
, add_suffix(boost::int64_t(cs.total_used_buffers) * 16 * 1024).c_str()
, cs.queued_bytes);
out += str;
snprintf(str, sizeof(str), "==== optimistic unchoke: %d unchoke counter: %d peerlist: %d ====\n"
, sess_stat.optimistic_unchoke_counter, sess_stat.unchoke_counter, sess_stat.peerlist_size);
out += str;
#ifndef TORRENT_DISABLE_DHT
if (show_dht_status)
{
snprintf(str, sizeof(str), "DHT nodes: %d DHT cached nodes: %d "
"total DHT size: %" PRId64 " total observers: %d\n"
, sess_stat.dht_nodes, sess_stat.dht_node_cache, sess_stat.dht_global_nodes
, sess_stat.dht_total_allocations);
out += str;
int bucket = 0;
for (std::vector<dht_routing_bucket>::iterator i = sess_stat.dht_routing_table.begin()
, end(sess_stat.dht_routing_table.end()); i != end; ++i, ++bucket)
{
snprintf(str, sizeof(str)
, "%3d [%2d, %2d] active: %d\n"
, bucket, i->num_nodes, i->num_replacements, i->last_active);
out += str;
}
for (std::vector<dht_lookup>::iterator i = sess_stat.active_requests.begin()
, end(sess_stat.active_requests.end()); i != end; ++i)
{
snprintf(str, sizeof(str)
, " %10s [limit: %2d] "
"in-flight: %-2d "
"left: %-3d "
"1st-timeout: %-2d "
"timeouts: %-2d "
"responses: %-2d "
"last_sent: %-2d\n"
, i->type
, i->branch_factor
, i->outstanding_requests
, i->nodes_left
, i->first_timeout
, i->timeouts
, i->responses
, i->last_sent);
out += str;
}
}
#endif
if (print_utp_stats)
{
snprintf(str, sizeof(str), "uTP idle: %d syn: %d est: %d fin: %d wait: %d\n"
, sess_stat.utp_stats.num_idle, sess_stat.utp_stats.num_syn_sent
, sess_stat.utp_stats.num_connected, sess_stat.utp_stats.num_fin_sent
, sess_stat.utp_stats.num_close_wait);
out += str;
}
torrent_status const* st = 0;
if (!filtered_handles.empty()) st = &get_active_torrent(filtered_handles);
if (st && st->handle.is_valid())
{
torrent_handle h = st->handle;
torrent_status const& s = *st;
if ((print_downloads && s.state != torrent_status::seeding)
|| print_peers)
h.get_peer_info(peers);
out += "====== ";
out += h.name();
out += " ======\n";
if (print_peers && !peers.empty())
print_peer_info(out, peers);
if (print_trackers)
{
std::vector<announce_entry> tr = h.trackers();
ptime now = time_now();
for (std::vector<announce_entry>::iterator i = tr.begin()
, end(tr.end()); i != end; ++i)
{
snprintf(str, sizeof(str), "%2d %-55s fails: %-3d (%-3d) %s %s %5d \"%s\" %s\n"
, i->tier, i->url.c_str(), i->fails, i->fail_limit, i->verified?"OK ":"- "
, i->updating?"updating"
:!i->will_announce(now)?""
:to_string(total_seconds(i->next_announce - now), 8).c_str()
, i->min_announce > now ? total_seconds(i->min_announce - now) : 0
, i->last_error ? i->last_error.message().c_str() : ""
, i->message.c_str());
out += str;
}
}
if (print_downloads)
{
std::vector<cached_piece_info> pieces;
ses.get_cache_info(h.info_hash(), pieces);
h.get_download_queue(queue);
std::sort(queue.begin(), queue.end(), boost::bind(&partial_piece_info::piece_index, _1)
< boost::bind(&partial_piece_info::piece_index, _2));
std::sort(pieces.begin(), pieces.end(), boost::bind(&cached_piece_info::last_use, _1)
> boost::bind(&cached_piece_info::last_use, _2));
for (std::vector<cached_piece_info>::iterator i = pieces.begin();
i != pieces.end(); ++i)
{
partial_piece_info* pp = 0;
partial_piece_info tmp;
tmp.piece_index = i->piece;
std::vector<partial_piece_info>::iterator ppi
= std::lower_bound(queue.begin(), queue.end(), tmp
, boost::bind(&partial_piece_info::piece_index, _1)
< boost::bind(&partial_piece_info::piece_index, _2));
if (ppi != queue.end() && ppi->piece_index == i->piece) pp = &*ppi;
print_piece(pp, &*i, peers, out);
if (pp) queue.erase(ppi);
}
for (std::vector<partial_piece_info>::iterator i = queue.begin()
, end(queue.end()); i != end; ++i)
{
print_piece(&*i, 0, peers, out);
}
snprintf(str, sizeof(str), "%s %s: read cache %s %s: downloading %s %s: cached %s %s: flushed\n"
, esc("34;7"), esc("0") // read cache
, esc("33;7"), esc("0") // downloading
, esc("36;7"), esc("0") // cached
, esc("32;7"), esc("0")); // flushed
out += str;
out += "___________________________________\n";
}
if (print_file_progress
&& s.state != torrent_status::seeding
&& s.has_metadata)
{
std::vector<size_type> file_progress;
h.file_progress(file_progress);
torrent_info const& info = h.get_torrent_info();
for (int i = 0; i < info.num_files(); ++i)
{
bool pad_file = info.file_at(i).pad_file;
if (!show_pad_files && pad_file) continue;
int progress = info.file_at(i).size > 0
?file_progress[i] * 1000 / info.file_at(i).size:1000;
char const* color = (file_progress[i] == info.file_at(i).size)
?"32":"33";
snprintf(str, sizeof(str), "%s %s %-5.2f%% %s %s%s\n",
progress_bar(progress, 100, color).c_str()
, pad_file?esc("34"):""
, progress / 10.f
, add_suffix(file_progress[i]).c_str()
, filename(info.files().file_path(info.file_at(i))).c_str()
, pad_file?esc("0"):"");
out += str;
}
out += "___________________________________\n";
}
}
if (print_log)
{
for (std::deque<std::string>::iterator i = events.begin();
i != events.end(); ++i)
{
out += "\n";
out += *i;
}
}
clear_home();
puts(out.c_str());
fflush(stdout);
if (!monitor_dir.empty()
&& next_dir_scan < time_now())
{
scan_dir(monitor_dir, ses, files, non_files
, allocation_mode, save_path, torrent_upload_limit
, torrent_download_limit);
next_dir_scan = time_now() + seconds(poll_interval);
}
}
// keep track of the number of resume data
// alerts to wait for
int num_paused = 0;
int num_failed = 0;
ses.pause();
printf("saving resume data\n");
std::vector<torrent_status> temp;
ses.get_torrent_status(&temp, &yes, 0);
for (std::vector<torrent_status>::iterator i = temp.begin();
i != temp.end(); ++i)
{
torrent_status& st = *i;
if (!st.handle.is_valid())
{
printf(" skipping, invalid handle\n");
continue;
}
if (!st.has_metadata)
{
printf(" skipping %s, no metadata\n", st.handle.name().c_str());
continue;
}
if (!st.need_save_resume)
{
printf(" skipping %s, resume file up-to-date\n", st.handle.name().c_str());
continue;
}
// save_resume_data will generate an alert when it's done
st.handle.save_resume_data();
++num_outstanding_resume_data;
printf("\r%d ", num_outstanding_resume_data);
}
printf("\nwaiting for resume data [%d]\n", num_outstanding_resume_data);
while (num_outstanding_resume_data > 0)
{
alert const* a = ses.wait_for_alert(seconds(10));
if (a == 0) continue;
std::deque<alert*> alerts;
ses.pop_alerts(&alerts);
std::string now = time_now_string();
for (std::deque<alert*>::iterator i = alerts.begin()
, end(alerts.end()); i != end; ++i)
{
// make sure to delete each alert
std::auto_ptr<alert> a(*i);
torrent_paused_alert const* tp = alert_cast<torrent_paused_alert>(*i);
if (tp)
{
++num_paused;
printf("\rleft: %d failed: %d pause: %d "
, num_outstanding_resume_data, num_failed, num_paused);
continue;
}
if (alert_cast<save_resume_data_failed_alert>(*i))
{
++num_failed;
--num_outstanding_resume_data;
printf("\rleft: %d failed: %d pause: %d "
, num_outstanding_resume_data, num_failed, num_paused);
continue;
}
save_resume_data_alert const* rd = alert_cast<save_resume_data_alert>(*i);
if (!rd) continue;
--num_outstanding_resume_data;
printf("\rleft: %d failed: %d pause: %d "
, num_outstanding_resume_data, num_failed, num_paused);
if (!rd->resume_data) continue;
torrent_handle h = rd->handle;
std::vector<char> out;
bencode(std::back_inserter(out), *rd->resume_data);
save_file(combine_path(h.save_path(), combine_path(".resume", to_hex(h.info_hash().to_string()) + ".resume")), out);
}
}
if (g_log_file) fclose(g_log_file);
printf("\nsaving session state\n");
{
entry session_state;
ses.save_state(session_state);
std::vector<char> out;
bencode(std::back_inserter(out), session_state);
save_file(".ses_state", out);
}
printf("closing session");
return 0;
}
| 29.660417 | 121 | 0.633617 | svn2github |
c1bc9d29f4115276986b581e6476527298fa8249 | 25,939 | hpp | C++ | src/cppad.git/include/cppad/example/eigen_mat_mul.hpp | yinzixuan126/my_udacity | cada1bc047cd21282b008a0eb85a1df52fd94034 | [
"MIT"
] | 1 | 2019-11-05T02:23:47.000Z | 2019-11-05T02:23:47.000Z | src/cppad.git/include/cppad/example/eigen_mat_mul.hpp | yinzixuan126/my_udacity | cada1bc047cd21282b008a0eb85a1df52fd94034 | [
"MIT"
] | null | null | null | src/cppad.git/include/cppad/example/eigen_mat_mul.hpp | yinzixuan126/my_udacity | cada1bc047cd21282b008a0eb85a1df52fd94034 | [
"MIT"
] | 1 | 2019-11-05T02:23:51.000Z | 2019-11-05T02:23:51.000Z | # ifndef CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP
# define CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-18 Bradley M. Bell
CppAD is distributed under the terms of the
Eclipse Public License Version 2.0.
This Source Code may also be made available under the following
Secondary License when the conditions for such availability set forth
in the Eclipse Public License, Version 2.0 are satisfied:
GNU General Public License, Version 2.0 or later.
---------------------------------------------------------------------------- */
/*
$begin atomic_eigen_mat_mul.hpp$$
$spell
Eigen
Taylor
nr
nc
$$
$section Atomic Eigen Matrix Multiply Class$$
$head See Also$$
$cref atomic_mat_mul.hpp$$
$head Purpose$$
Construct an atomic operation that computes the matrix product,
$latex R = A \times \B{R}$$
for any positive integers $latex r$$, $latex m$$, $latex c$$,
and any $latex A \in \B{R}^{r \times m}$$,
$latex B \in \B{R}^{m \times c}$$.
$head Matrix Dimensions$$
This example puts the matrix dimensions in the atomic function arguments,
instead of the $cref/constructor/atomic_ctor/$$, so that they can
be different for different calls to the atomic function.
These dimensions are:
$table
$icode nr_left$$
$cnext number of rows in the left matrix; i.e, $latex r$$ $rend
$icode n_middle$$
$cnext rows in the left matrix and columns in right; i.e, $latex m$$ $rend
$icode nc_right$$
$cnext number of columns in the right matrix; i.e., $latex c$$
$tend
$head Theory$$
$subhead Forward$$
For $latex k = 0 , \ldots $$, the $th k$$ order Taylor coefficient
$latex R_k$$ is given by
$latex \[
R_k = \sum_{\ell = 0}^{k} A_\ell B_{k-\ell}
\] $$
$subhead Product of Two Matrices$$
Suppose $latex \bar{E}$$ is the derivative of the
scalar value function $latex s(E)$$ with respect to $latex E$$; i.e.,
$latex \[
\bar{E}_{i,j} = \frac{ \partial s } { \partial E_{i,j} }
\] $$
Also suppose that $latex t$$ is a scalar valued argument and
$latex \[
E(t) = C(t) D(t)
\] $$
It follows that
$latex \[
E'(t) = C'(t) D(t) + C(t) D'(t)
\] $$
$latex \[
(s \circ E)'(t)
=
\R{tr} [ \bar{E}^\R{T} E'(t) ]
\] $$
$latex \[
=
\R{tr} [ \bar{E}^\R{T} C'(t) D(t) ] +
\R{tr} [ \bar{E}^\R{T} C(t) D'(t) ]
\] $$
$latex \[
=
\R{tr} [ D(t) \bar{E}^\R{T} C'(t) ] +
\R{tr} [ \bar{E}^\R{T} C(t) D'(t) ]
\] $$
$latex \[
\bar{C} = \bar{E} D^\R{T} \W{,}
\bar{D} = C^\R{T} \bar{E}
\] $$
$subhead Reverse$$
Reverse mode eliminates $latex R_k$$ as follows:
for $latex \ell = 0, \ldots , k-1$$,
$latex \[
\bar{A}_\ell = \bar{A}_\ell + \bar{R}_k B_{k-\ell}^\R{T}
\] $$
$latex \[
\bar{B}_{k-\ell} = \bar{B}_{k-\ell} + A_\ell^\R{T} \bar{R}_k
\] $$
$nospell
$head Start Class Definition$$
$srccode%cpp% */
# include <cppad/cppad.hpp>
# include <Eigen/Core>
/* %$$
$head Public$$
$subhead Types$$
$srccode%cpp% */
namespace { // BEGIN_EMPTY_NAMESPACE
template <class Base>
class atomic_eigen_mat_mul : public CppAD::atomic_base<Base> {
public:
// -----------------------------------------------------------
// type of elements during calculation of derivatives
typedef Base scalar;
// type of elements during taping
typedef CppAD::AD<scalar> ad_scalar;
// type of matrix during calculation of derivatives
typedef Eigen::Matrix<
scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix;
// type of matrix during taping
typedef Eigen::Matrix<
ad_scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > ad_matrix;
/* %$$
$subhead Constructor$$
$srccode%cpp% */
// constructor
atomic_eigen_mat_mul(void) : CppAD::atomic_base<Base>(
"atom_eigen_mat_mul" ,
CppAD::atomic_base<Base>::set_sparsity_enum
)
{ }
/* %$$
$subhead op$$
$srccode%cpp% */
// use atomic operation to multiply two AD matrices
ad_matrix op(
const ad_matrix& left ,
const ad_matrix& right )
{ size_t nr_left = size_t( left.rows() );
size_t n_middle = size_t( left.cols() );
size_t nc_right = size_t( right.cols() );
assert( n_middle == size_t( right.rows() ) );
size_t nx = 3 + (nr_left + nc_right) * n_middle;
size_t ny = nr_left * nc_right;
size_t n_left = nr_left * n_middle;
size_t n_right = n_middle * nc_right;
size_t n_result = nr_left * nc_right;
//
assert( 3 + n_left + n_right == nx );
assert( n_result == ny );
// -----------------------------------------------------------------
// packed version of left and right
CPPAD_TESTVECTOR(ad_scalar) packed_arg(nx);
//
packed_arg[0] = ad_scalar( nr_left );
packed_arg[1] = ad_scalar( n_middle );
packed_arg[2] = ad_scalar( nc_right );
for(size_t i = 0; i < n_left; i++)
packed_arg[3 + i] = left.data()[i];
for(size_t i = 0; i < n_right; i++)
packed_arg[ 3 + n_left + i ] = right.data()[i];
// ------------------------------------------------------------------
// Packed version of result = left * right.
// This as an atomic_base funciton call that CppAD uses
// to store the atomic operation on the tape.
CPPAD_TESTVECTOR(ad_scalar) packed_result(ny);
(*this)(packed_arg, packed_result);
// ------------------------------------------------------------------
// unpack result matrix
ad_matrix result(nr_left, nc_right);
for(size_t i = 0; i < n_result; i++)
result.data()[i] = packed_result[ i ];
//
return result;
}
/* %$$
$head Private$$
$subhead Variables$$
$srccode%cpp% */
private:
// -------------------------------------------------------------
// one forward mode vector of matrices for left, right, and result
CppAD::vector<matrix> f_left_, f_right_, f_result_;
// one reverse mode vector of matrices for left, right, and result
CppAD::vector<matrix> r_left_, r_right_, r_result_;
// -------------------------------------------------------------
/* %$$
$subhead forward$$
$srccode%cpp% */
// forward mode routine called by CppAD
virtual bool forward(
// lowest order Taylor coefficient we are evaluating
size_t p ,
// highest order Taylor coefficient we are evaluating
size_t q ,
// which components of x are variables
const CppAD::vector<bool>& vx ,
// which components of y are variables
CppAD::vector<bool>& vy ,
// tx [ 3 + j * (q+1) + k ] is x_j^k
const CppAD::vector<scalar>& tx ,
// ty [ i * (q+1) + k ] is y_i^k
CppAD::vector<scalar>& ty
)
{ size_t n_order = q + 1;
size_t nr_left = size_t( CppAD::Integer( tx[ 0 * n_order + 0 ] ) );
size_t n_middle = size_t( CppAD::Integer( tx[ 1 * n_order + 0 ] ) );
size_t nc_right = size_t( CppAD::Integer( tx[ 2 * n_order + 0 ] ) );
# ifndef NDEBUG
size_t nx = 3 + (nr_left + nc_right) * n_middle;
size_t ny = nr_left * nc_right;
# endif
//
assert( vx.size() == 0 || nx == vx.size() );
assert( vx.size() == 0 || ny == vy.size() );
assert( nx * n_order == tx.size() );
assert( ny * n_order == ty.size() );
//
size_t n_left = nr_left * n_middle;
size_t n_right = n_middle * nc_right;
size_t n_result = nr_left * nc_right;
assert( 3 + n_left + n_right == nx );
assert( n_result == ny );
//
// -------------------------------------------------------------------
// make sure f_left_, f_right_, and f_result_ are large enough
assert( f_left_.size() == f_right_.size() );
assert( f_left_.size() == f_result_.size() );
if( f_left_.size() < n_order )
{ f_left_.resize(n_order);
f_right_.resize(n_order);
f_result_.resize(n_order);
//
for(size_t k = 0; k < n_order; k++)
{ f_left_[k].resize( long(nr_left), long(n_middle) );
f_right_[k].resize( long(n_middle), long(nc_right) );
f_result_[k].resize( long(nr_left), long(nc_right) );
}
}
// -------------------------------------------------------------------
// unpack tx into f_left and f_right
for(size_t k = 0; k < n_order; k++)
{ // unpack left values for this order
for(size_t i = 0; i < n_left; i++)
f_left_[k].data()[i] = tx[ (3 + i) * n_order + k ];
//
// unpack right values for this order
for(size_t i = 0; i < n_right; i++)
f_right_[k].data()[i] = tx[ ( 3 + n_left + i) * n_order + k ];
}
// -------------------------------------------------------------------
// result for each order
// (we could avoid recalculting f_result_[k] for k=0,...,p-1)
for(size_t k = 0; k < n_order; k++)
{ // result[k] = sum_ell left[ell] * right[k-ell]
f_result_[k] = matrix::Zero( long(nr_left), long(nc_right) );
for(size_t ell = 0; ell <= k; ell++)
f_result_[k] += f_left_[ell] * f_right_[k-ell];
}
// -------------------------------------------------------------------
// pack result_ into ty
for(size_t k = 0; k < n_order; k++)
{ for(size_t i = 0; i < n_result; i++)
ty[ i * n_order + k ] = f_result_[k].data()[i];
}
// ------------------------------------------------------------------
// check if we are computing vy
if( vx.size() == 0 )
return true;
// ------------------------------------------------------------------
// compute variable information for y; i.e., vy
// (note that the constant zero times a variable is a constant)
scalar zero(0.0);
assert( n_order == 1 );
for(size_t i = 0; i < nr_left; i++)
{ for(size_t j = 0; j < nc_right; j++)
{ bool var = false;
for(size_t ell = 0; ell < n_middle; ell++)
{ // left information
size_t index = 3 + i * n_middle + ell;
bool var_left = vx[index];
bool nz_left = var_left |
(f_left_[0]( long(i), long(ell) ) != zero);
// right information
index = 3 + n_left + ell * nc_right + j;
bool var_right = vx[index];
bool nz_right = var_right |
(f_right_[0]( long(ell), long(j) ) != zero);
// effect of result
var |= var_left & nz_right;
var |= nz_left & var_right;
}
size_t index = i * nc_right + j;
vy[index] = var;
}
}
return true;
}
/* %$$
$subhead reverse$$
$srccode%cpp% */
// reverse mode routine called by CppAD
virtual bool reverse(
// highest order Taylor coefficient that we are computing derivative of
size_t q ,
// forward mode Taylor coefficients for x variables
const CppAD::vector<double>& tx ,
// forward mode Taylor coefficients for y variables
const CppAD::vector<double>& ty ,
// upon return, derivative of G[ F[ {x_j^k} ] ] w.r.t {x_j^k}
CppAD::vector<double>& px ,
// derivative of G[ {y_i^k} ] w.r.t. {y_i^k}
const CppAD::vector<double>& py
)
{ size_t n_order = q + 1;
size_t nr_left = size_t( CppAD::Integer( tx[ 0 * n_order + 0 ] ) );
size_t n_middle = size_t( CppAD::Integer( tx[ 1 * n_order + 0 ] ) );
size_t nc_right = size_t( CppAD::Integer( tx[ 2 * n_order + 0 ] ) );
# ifndef NDEBUG
size_t nx = 3 + (nr_left + nc_right) * n_middle;
size_t ny = nr_left * nc_right;
# endif
//
assert( nx * n_order == tx.size() );
assert( ny * n_order == ty.size() );
assert( px.size() == tx.size() );
assert( py.size() == ty.size() );
//
size_t n_left = nr_left * n_middle;
size_t n_right = n_middle * nc_right;
size_t n_result = nr_left * nc_right;
assert( 3 + n_left + n_right == nx );
assert( n_result == ny );
// -------------------------------------------------------------------
// make sure f_left_, f_right_ are large enough
assert( f_left_.size() == f_right_.size() );
assert( f_left_.size() == f_result_.size() );
// must have previous run forward with order >= n_order
assert( f_left_.size() >= n_order );
// -------------------------------------------------------------------
// make sure r_left_, r_right_, and r_result_ are large enough
assert( r_left_.size() == r_right_.size() );
assert( r_left_.size() == r_result_.size() );
if( r_left_.size() < n_order )
{ r_left_.resize(n_order);
r_right_.resize(n_order);
r_result_.resize(n_order);
//
for(size_t k = 0; k < n_order; k++)
{ r_left_[k].resize( long(nr_left), long(n_middle) );
r_right_[k].resize( long(n_middle), long(nc_right) );
r_result_[k].resize( long(nr_left), long(nc_right) );
}
}
// -------------------------------------------------------------------
// unpack tx into f_left and f_right
for(size_t k = 0; k < n_order; k++)
{ // unpack left values for this order
for(size_t i = 0; i < n_left; i++)
f_left_[k].data()[i] = tx[ (3 + i) * n_order + k ];
//
// unpack right values for this order
for(size_t i = 0; i < n_right; i++)
f_right_[k].data()[i] = tx[ (3 + n_left + i) * n_order + k ];
}
// -------------------------------------------------------------------
// unpack py into r_result_
for(size_t k = 0; k < n_order; k++)
{ for(size_t i = 0; i < n_result; i++)
r_result_[k].data()[i] = py[ i * n_order + k ];
}
// -------------------------------------------------------------------
// initialize r_left_ and r_right_ as zero
for(size_t k = 0; k < n_order; k++)
{ r_left_[k] = matrix::Zero( long(nr_left), long(n_middle) );
r_right_[k] = matrix::Zero( long(n_middle), long(nc_right) );
}
// -------------------------------------------------------------------
// matrix reverse mode calculation
for(size_t k1 = n_order; k1 > 0; k1--)
{ size_t k = k1 - 1;
for(size_t ell = 0; ell <= k; ell++)
{ // nr x nm = nr x nc * nc * nm
r_left_[ell] += r_result_[k] * f_right_[k-ell].transpose();
// nm x nc = nm x nr * nr * nc
r_right_[k-ell] += f_left_[ell].transpose() * r_result_[k];
}
}
// -------------------------------------------------------------------
// pack r_left and r_right int px
for(size_t k = 0; k < n_order; k++)
{ // dimensions are integer constants
px[ 0 * n_order + k ] = 0.0;
px[ 1 * n_order + k ] = 0.0;
px[ 2 * n_order + k ] = 0.0;
//
// pack left values for this order
for(size_t i = 0; i < n_left; i++)
px[ (3 + i) * n_order + k ] = r_left_[k].data()[i];
//
// pack right values for this order
for(size_t i = 0; i < n_right; i++)
px[ (3 + i + n_left) * n_order + k] = r_right_[k].data()[i];
}
//
return true;
}
/* %$$
$subhead for_sparse_jac$$
$srccode%cpp% */
// forward Jacobian sparsity routine called by CppAD
virtual bool for_sparse_jac(
// number of columns in the matrix R
size_t q ,
// sparsity pattern for the matrix R
const CppAD::vector< std::set<size_t> >& r ,
// sparsity pattern for the matrix S = f'(x) * R
CppAD::vector< std::set<size_t> >& s ,
const CppAD::vector<Base>& x )
{
size_t nr_left = size_t( CppAD::Integer( x[0] ) );
size_t n_middle = size_t( CppAD::Integer( x[1] ) );
size_t nc_right = size_t( CppAD::Integer( x[2] ) );
# ifndef NDEBUG
size_t nx = 3 + (nr_left + nc_right) * n_middle;
size_t ny = nr_left * nc_right;
# endif
//
assert( nx == r.size() );
assert( ny == s.size() );
//
size_t n_left = nr_left * n_middle;
for(size_t i = 0; i < nr_left; i++)
{ for(size_t j = 0; j < nc_right; j++)
{ // pack index for entry (i, j) in result
size_t i_result = i * nc_right + j;
s[i_result].clear();
for(size_t ell = 0; ell < n_middle; ell++)
{ // pack index for entry (i, ell) in left
size_t i_left = 3 + i * n_middle + ell;
// pack index for entry (ell, j) in right
size_t i_right = 3 + n_left + ell * nc_right + j;
// check if result of for this product is alwasy zero
// note that x is nan for commponents that are variables
bool zero = x[i_left] == Base(0.0) || x[i_right] == Base(0);
if( ! zero )
{ s[i_result] =
CppAD::set_union(s[i_result], r[i_left] );
s[i_result] =
CppAD::set_union(s[i_result], r[i_right] );
}
}
}
}
return true;
}
/* %$$
$subhead rev_sparse_jac$$
$srccode%cpp% */
// reverse Jacobian sparsity routine called by CppAD
virtual bool rev_sparse_jac(
// number of columns in the matrix R^T
size_t q ,
// sparsity pattern for the matrix R^T
const CppAD::vector< std::set<size_t> >& rt ,
// sparsoity pattern for the matrix S^T = f'(x)^T * R^T
CppAD::vector< std::set<size_t> >& st ,
const CppAD::vector<Base>& x )
{
size_t nr_left = size_t( CppAD::Integer( x[0] ) );
size_t n_middle = size_t( CppAD::Integer( x[1] ) );
size_t nc_right = size_t( CppAD::Integer( x[2] ) );
size_t nx = 3 + (nr_left + nc_right) * n_middle;
# ifndef NDEBUG
size_t ny = nr_left * nc_right;
# endif
//
assert( nx == st.size() );
assert( ny == rt.size() );
//
// initialize S^T as empty
for(size_t i = 0; i < nx; i++)
st[i].clear();
// sparsity for S(x)^T = f'(x)^T * R^T
size_t n_left = nr_left * n_middle;
for(size_t i = 0; i < nr_left; i++)
{ for(size_t j = 0; j < nc_right; j++)
{ // pack index for entry (i, j) in result
size_t i_result = i * nc_right + j;
st[i_result].clear();
for(size_t ell = 0; ell < n_middle; ell++)
{ // pack index for entry (i, ell) in left
size_t i_left = 3 + i * n_middle + ell;
// pack index for entry (ell, j) in right
size_t i_right = 3 + n_left + ell * nc_right + j;
//
st[i_left] = CppAD::set_union(st[i_left], rt[i_result]);
st[i_right] = CppAD::set_union(st[i_right], rt[i_result]);
}
}
}
return true;
}
/* %$$
$subhead for_sparse_hes$$
$srccode%cpp% */
virtual bool for_sparse_hes(
// which components of x are variables for this call
const CppAD::vector<bool>& vx,
// sparsity pattern for the diagonal of R
const CppAD::vector<bool>& r ,
// sparsity pattern for the vector S
const CppAD::vector<bool>& s ,
// sparsity patternfor the Hessian H(x)
CppAD::vector< std::set<size_t> >& h ,
const CppAD::vector<Base>& x )
{
size_t nr_left = size_t( CppAD::Integer( x[0] ) );
size_t n_middle = size_t( CppAD::Integer( x[1] ) );
size_t nc_right = size_t( CppAD::Integer( x[2] ) );
size_t nx = 3 + (nr_left + nc_right) * n_middle;
# ifndef NDEBUG
size_t ny = nr_left * nc_right;
# endif
//
assert( vx.size() == nx );
assert( r.size() == nx );
assert( s.size() == ny );
assert( h.size() == nx );
//
// initilize h as empty
for(size_t i = 0; i < nx; i++)
h[i].clear();
//
size_t n_left = nr_left * n_middle;
for(size_t i = 0; i < nr_left; i++)
{ for(size_t j = 0; j < nc_right; j++)
{ // pack index for entry (i, j) in result
size_t i_result = i * nc_right + j;
if( s[i_result] )
{ for(size_t ell = 0; ell < n_middle; ell++)
{ // pack index for entry (i, ell) in left
size_t i_left = 3 + i * n_middle + ell;
// pack index for entry (ell, j) in right
size_t i_right = 3 + n_left + ell * nc_right + j;
if( r[i_left] & r[i_right] )
{ h[i_left].insert(i_right);
h[i_right].insert(i_left);
}
}
}
}
}
return true;
}
/* %$$
$subhead rev_sparse_hes$$
$srccode%cpp% */
// reverse Hessian sparsity routine called by CppAD
virtual bool rev_sparse_hes(
// which components of x are variables for this call
const CppAD::vector<bool>& vx,
// sparsity pattern for S(x) = g'[f(x)]
const CppAD::vector<bool>& s ,
// sparsity pattern for d/dx g[f(x)] = S(x) * f'(x)
CppAD::vector<bool>& t ,
// number of columns in R, U(x), and V(x)
size_t q ,
// sparsity pattern for R
const CppAD::vector< std::set<size_t> >& r ,
// sparsity pattern for U(x) = g^{(2)} [ f(x) ] * f'(x) * R
const CppAD::vector< std::set<size_t> >& u ,
// sparsity pattern for
// V(x) = f'(x)^T * U(x) + sum_{i=0}^{m-1} S_i(x) f_i^{(2)} (x) * R
CppAD::vector< std::set<size_t> >& v ,
// parameters as integers
const CppAD::vector<Base>& x )
{
size_t nr_left = size_t( CppAD::Integer( x[0] ) );
size_t n_middle = size_t( CppAD::Integer( x[1] ) );
size_t nc_right = size_t( CppAD::Integer( x[2] ) );
size_t nx = 3 + (nr_left + nc_right) * n_middle;
# ifndef NDEBUG
size_t ny = nr_left * nc_right;
# endif
//
assert( vx.size() == nx );
assert( s.size() == ny );
assert( t.size() == nx );
assert( r.size() == nx );
assert( v.size() == nx );
//
// initilaize return sparsity patterns as false
for(size_t j = 0; j < nx; j++)
{ t[j] = false;
v[j].clear();
}
//
size_t n_left = nr_left * n_middle;
for(size_t i = 0; i < nr_left; i++)
{ for(size_t j = 0; j < nc_right; j++)
{ // pack index for entry (i, j) in result
size_t i_result = i * nc_right + j;
for(size_t ell = 0; ell < n_middle; ell++)
{ // pack index for entry (i, ell) in left
size_t i_left = 3 + i * n_middle + ell;
// pack index for entry (ell, j) in right
size_t i_right = 3 + n_left + ell * nc_right + j;
//
// back propagate T(x) = S(x) * f'(x).
t[i_left] |= bool( s[i_result] );
t[i_right] |= bool( s[i_result] );
//
// V(x) = f'(x)^T * U(x) + sum_i S_i(x) * f_i''(x) * R
// U(x) = g''[ f(x) ] * f'(x) * R
// S_i(x) = g_i'[ f(x) ]
//
// back propagate f'(x)^T * U(x)
v[i_left] = CppAD::set_union(v[i_left], u[i_result] );
v[i_right] = CppAD::set_union(v[i_right], u[i_result] );
//
// back propagate S_i(x) * f_i''(x) * R
// (here is where we use vx to check for cross terms)
if( s[i_result] & vx[i_left] & vx[i_right] )
{ v[i_left] = CppAD::set_union(v[i_left], r[i_right] );
v[i_right] = CppAD::set_union(v[i_right], r[i_left] );
}
}
}
}
return true;
}
/* %$$
$head End Class Definition$$
$srccode%cpp% */
}; // End of atomic_eigen_mat_mul class
} // END_EMPTY_NAMESPACE
/* %$$
$$ $comment end nospell$$
$end
*/
# endif
| 39.361153 | 80 | 0.463549 | yinzixuan126 |
c1bdd76957f2369247d910ebf23fcf05b6a932ee | 29,247 | cpp | C++ | Plugins/Raytracing/Raytracing.cpp | cryptobuks1/Stratum | 3ecf56c0ce9010e6e95248c0d63edc41eeb13910 | [
"MIT"
] | null | null | null | Plugins/Raytracing/Raytracing.cpp | cryptobuks1/Stratum | 3ecf56c0ce9010e6e95248c0d63edc41eeb13910 | [
"MIT"
] | null | null | null | Plugins/Raytracing/Raytracing.cpp | cryptobuks1/Stratum | 3ecf56c0ce9010e6e95248c0d63edc41eeb13910 | [
"MIT"
] | null | null | null | #include <Core/EnginePlugin.hpp>
#include <Scene/Camera.hpp>
#include <Scene/MeshRenderer.hpp>
#include <Scene/Scene.hpp>
#include <Util/Profiler.hpp>
#include <assimp/pbrmaterial.h>
using namespace std;
#ifdef GetObject
#undef GetObject
#endif
#define PASS_RAYTRACE (1u << 23)
#pragma pack(push)
#pragma pack(1)
struct GpuBvhNode {
float3 Min;
uint32_t StartIndex;
float3 Max;
uint32_t PrimitiveCount;
uint32_t RightOffset; // 1st child is at node[index + 1], 2nd child is at node[index + mRightOffset]
uint32_t pad[3];
};
struct GpuLeafNode {
float4x4 NodeToWorld;
float4x4 WorldToNode;
uint32_t RootIndex;
uint32_t MaterialIndex;
uint32_t pad[2];
};
struct DisneyMaterial {
float3 BaseColor;
float Metallic;
float3 Emission;
float Specular;
float Anisotropy;
float Roughness;
float SpecularTint;
float SheenTint;
float Sheen;
float ClearcoatGloss;
float Clearcoat;
float Subsurface;
float Transmission;
uint32_t pad[3];
};
#pragma pack(pop)
class Raytracing : public EnginePlugin {
private:
vector<Object*> mObjects;
Scene* mScene;
uint32_t mFrameIndex;
struct FrameData {
float4x4 mViewProjection;
float4x4 mInvViewProjection;
float3 mCameraPosition;
Texture* mPrimary;
Texture* mSecondary;
Texture* mMeta;
Texture* mResolveTmp;
Texture* mResolve;
Buffer* mNodes;
Buffer* mLeafNodes;
Buffer* mVertices;
Buffer* mTriangles;
Buffer* mLights;
Buffer* mMaterials;
uint32_t mBvhBase;
uint32_t mLightCount;
uint64_t mLastBuild;
unordered_map<Mesh*, uint32_t> mMeshes; // Mesh, RootIndex
};
FrameData* mFrameData;
void Build(CommandBuffer* commandBuffer, FrameData& fd) {
PROFILER_BEGIN("Copy BVH");
ObjectBvh2* sceneBvh = mScene->BVH();
fd.mMeshes.clear();
vector<GpuBvhNode> nodes;
vector<GpuLeafNode> leafNodes;
vector<DisneyMaterial> materials;
vector<uint3> triangles;
vector<uint4> lights;
uint32_t nodeBaseIndex = 0;
uint32_t vertexCount = 0;
unordered_map<Mesh*, uint2> triangleRanges;
unordered_map<Buffer*, vector<VkBufferCopy>> vertexCopies;
PROFILER_BEGIN("Copy meshes");
// Copy mesh BVHs
for (uint32_t sni = 0; sni < sceneBvh->Nodes().size(); sni++){
const ObjectBvh2::Node& sn = sceneBvh->Nodes()[sni];
if (sn.mRightOffset == 0) {
for (uint32_t i = 0; i < sn.mCount; i++) {
MeshRenderer* mr = dynamic_cast<MeshRenderer*>(sceneBvh->GetObject(sn.mStartIndex + i));
if (mr && mr->Visible()) {
leafNodes.push_back({});
Mesh* m = mr->Mesh();
if (!fd.mMeshes.count(m)) {
fd.mMeshes.emplace(m, nodeBaseIndex);
TriangleBvh2* bvh = m->BVH();
nodes.resize(nodeBaseIndex + bvh->Nodes().size());
uint32_t baseTri = triangles.size();
for (uint32_t ni = 0; ni < bvh->Nodes().size(); ni++) {
const TriangleBvh2::Node& n = bvh->Nodes()[ni];
GpuBvhNode& gn = nodes[nodeBaseIndex + ni];
gn.RightOffset = n.mRightOffset;
gn.Min = n.mBounds.mMin;
gn.Max = n.mBounds.mMax;
gn.StartIndex = triangles.size();
gn.PrimitiveCount = n.mCount;
if (n.mRightOffset == 0)
for (uint32_t i = 0; i < n.mCount; i++)
triangles.push_back(vertexCount + bvh->GetTriangle(n.mStartIndex + i));
}
triangleRanges.emplace(m, uint2(baseTri, triangles.size()));
auto& cpy = vertexCopies[m->VertexBuffer().get()];
VkBufferCopy rgn = {};
rgn.srcOffset = m->BaseVertex() * sizeof(StdVertex);
rgn.dstOffset = vertexCount * sizeof(StdVertex);
rgn.size = m->VertexCount() * sizeof(StdVertex);
cpy.push_back(rgn);
nodeBaseIndex += bvh->Nodes().size();
vertexCount += m->VertexCount();
}
}
}
}
}
PROFILER_END;
// Copy scene BVH
PROFILER_BEGIN("Copy scene");
fd.mBvhBase = (uint32_t)nodes.size();
nodes.resize(nodes.size() + sceneBvh->Nodes().size());
uint32_t leafNodeIndex = 0;
for (uint32_t ni = 0; ni < sceneBvh->Nodes().size(); ni++){
const ObjectBvh2::Node& n = sceneBvh->Nodes()[ni];
GpuBvhNode& gn = nodes[fd.mBvhBase + ni];
gn.RightOffset = n.mRightOffset;
gn.Min = n.mBounds.mMin;
gn.Max = n.mBounds.mMax;
gn.StartIndex = leafNodeIndex;
gn.PrimitiveCount = 0;
if (n.mRightOffset == 0) {
for (uint32_t i = 0; i < n.mCount; i++) {
MeshRenderer* mr = dynamic_cast<MeshRenderer*>(sceneBvh->GetObject(n.mStartIndex + i));
if (mr && mr->Visible()) {
leafNodes[leafNodeIndex].NodeToWorld = mr->ObjectToWorld();
leafNodes[leafNodeIndex].WorldToNode = mr->WorldToObject();
leafNodes[leafNodeIndex].RootIndex = fd.mMeshes.at(mr->Mesh());
leafNodes[leafNodeIndex].MaterialIndex = materials.size();
DisneyMaterial mat = {};
mat.BaseColor = mr->PushConstant("Color").float4Value.rgb;
mat.Emission = mr->PushConstant("Emission").float3Value;
mat.Roughness = mr->PushConstant("Roughness").floatValue;
mat.Metallic = mr->PushConstant("Metallic").floatValue;
mat.ClearcoatGloss = 1;
mat.Specular = .5f;
mat.Transmission = 1 - mr->PushConstant("Color").float4Value.a;
if (mat.Emission.r + mat.Emission.g + mat.Emission.b > 0) {
uint2 r = triangleRanges.at(mr->Mesh());
for (uint32_t j = r.x; j < r.y; j++)
lights.push_back(uint4(j, materials.size(), leafNodeIndex, 0));
}
if (mr->mName == "SuzanneSuzanne") {
mat.Subsurface = 1;
}
if (mr->mName == "ClearcoatClearcoat") {
mat.Clearcoat = 1;
}
materials.push_back(mat);
leafNodeIndex++;
gn.PrimitiveCount++;
}
}
}
}
fd.mLightCount = lights.size();
PROFILER_END;
PROFILER_BEGIN("Upload data");
if (fd.mNodes && fd.mNodes->Size() < sizeof(GpuBvhNode) * nodes.size())
safe_delete(fd.mNodes);
if (!fd.mNodes) fd.mNodes = new Buffer("SceneBvh", mScene->Instance()->Device(), sizeof(GpuBvhNode) * nodes.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
if (fd.mLeafNodes && fd.mLeafNodes->Size() < sizeof(GpuLeafNode) * leafNodes.size())
safe_delete(fd.mLeafNodes);
if (!fd.mLeafNodes) fd.mLeafNodes = new Buffer("LeafNodes", mScene->Instance()->Device(), sizeof(GpuLeafNode) * leafNodes.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
if (fd.mTriangles && fd.mTriangles->Size() < sizeof(uint3) * triangles.size())
safe_delete(fd.mTriangles);
if (!fd.mTriangles) fd.mTriangles = new Buffer("Triangles", mScene->Instance()->Device(), sizeof(uint3) * triangles.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
if (fd.mLights && fd.mLights->Size() < sizeof(uint4) * lights.size())
safe_delete(fd.mLights);
if (!fd.mLights) fd.mLights = new Buffer("Lights", mScene->Instance()->Device(), sizeof(uint4) * lights.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
if (fd.mMaterials && fd.mMaterials->Size() < sizeof(DisneyMaterial) * materials.size())
safe_delete(fd.mMaterials);
if (!fd.mMaterials) fd.mMaterials = new Buffer("Materials", mScene->Instance()->Device(), sizeof(DisneyMaterial) * materials.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT);
if (fd.mVertices && fd.mVertices->Size() < sizeof(StdVertex) * vertexCount)
safe_delete(fd.mVertices);
if (!fd.mVertices) fd.mVertices = new Buffer("Vertices", mScene->Instance()->Device(), sizeof(StdVertex) * vertexCount, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
fd.mNodes->Upload(nodes.data(), sizeof(GpuBvhNode) * nodes.size());
fd.mLeafNodes->Upload(leafNodes.data(), sizeof(GpuLeafNode) * leafNodes.size());
fd.mMaterials->Upload(materials.data(), sizeof(DisneyMaterial)* materials.size());
fd.mLights->Upload(lights.data(), sizeof(uint3) * lights.size());
fd.mTriangles->Upload(triangles.data(), sizeof(uint3) * triangles.size());
for (auto p : vertexCopies)
vkCmdCopyBuffer(*commandBuffer, *p.first, *fd.mVertices, p.second.size(), p.second.data());
VkBufferMemoryBarrier barrier = {};
barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER;
barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
barrier.buffer = *fd.mVertices;
barrier.size = fd.mVertices->Size();
vkCmdPipelineBarrier(*commandBuffer,
VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0,
0, nullptr,
1, &barrier,
0, nullptr);
fd.mLastBuild = mScene->Instance()->FrameCount();
PROFILER_END;
}
public:
inline int Priority() override { return 10000; }
PLUGIN_EXPORT Raytracing() : mScene(nullptr), mFrameIndex(0) { mEnabled = true; }
PLUGIN_EXPORT ~Raytracing() {
for (uint32_t i = 0; i < mScene->Instance()->Device()->MaxFramesInFlight(); i++) {
safe_delete(mFrameData[i].mPrimary);
safe_delete(mFrameData[i].mSecondary);
safe_delete(mFrameData[i].mMeta);
safe_delete(mFrameData[i].mResolveTmp);
safe_delete(mFrameData[i].mResolve);
safe_delete(mFrameData[i].mNodes);
safe_delete(mFrameData[i].mLeafNodes);
safe_delete(mFrameData[i].mVertices);
safe_delete(mFrameData[i].mTriangles);
safe_delete(mFrameData[i].mLights);
safe_delete(mFrameData[i].mMaterials);
}
safe_delete_array(mFrameData);
for (Object* obj : mObjects)
mScene->RemoveObject(obj);
}
PLUGIN_EXPORT bool Init(Scene* scene) override {
mScene = scene;
mScene->Environment()->EnableCelestials(false);
mScene->Environment()->EnableScattering(false);
mScene->Environment()->AmbientLight(.3f);
//mScene->Environment()->EnvironmentTexture(mScene->AssetManager()->LoadTexture("Assets/Textures/old_outdoor_theater_4k.hdr"));
#pragma region load glTF
string folder = "Assets/Models/";
string file = "cornellbox.gltf";
shared_ptr<Material> opaque = make_shared<Material>("PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm"));
opaque->EnableKeyword("TEXTURED");
opaque->SetParameter("TextureST", float4(1, 1, 0, 0));
shared_ptr<Material> alphaClip = make_shared<Material>("Cutout PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm"));
alphaClip->RenderQueue(5000);
alphaClip->BlendMode(BLEND_MODE_ALPHA);
alphaClip->CullMode(VK_CULL_MODE_NONE);
alphaClip->EnableKeyword("TEXTURED");
alphaClip->EnableKeyword("ALPHA_CLIP");
alphaClip->EnableKeyword("TWO_SIDED");
alphaClip->SetParameter("TextureST", float4(1, 1, 0, 0));
shared_ptr<Material> alphaBlend = make_shared<Material>("Transparent PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm"));
alphaBlend->RenderQueue(5000);
alphaBlend->BlendMode(BLEND_MODE_ALPHA);
alphaBlend->CullMode(VK_CULL_MODE_NONE);
alphaBlend->EnableKeyword("TEXTURED");
alphaBlend->EnableKeyword("TWO_SIDED");
alphaBlend->SetParameter("TextureST", float4(1, 1, 0, 0));
shared_ptr<Material> curOpaque = nullptr;
shared_ptr<Material> curClip = nullptr;
shared_ptr<Material> curBlend = nullptr;
uint32_t arraySize =
mScene->AssetManager()->LoadShader("Shaders/pbr.stm")->GetGraphics(PASS_MAIN, { "TEXTURED" })->mDescriptorBindings.at("MainTextures").second.descriptorCount;
uint32_t opaque_i = 0;
uint32_t clip_i = 0;
uint32_t blend_i = 0;
auto matfunc = [&](Scene* scene, aiMaterial* aimaterial) {
aiString alphaMode;
if (aimaterial->Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode) == AI_SUCCESS) {
if (alphaMode == aiString("MASK")) return alphaClip;
if (alphaMode == aiString("BLEND")) return alphaBlend;
}
return opaque;
};
auto objfunc = [&](Scene* scene, Object* object, aiMaterial* aimaterial) {
MeshRenderer* renderer = dynamic_cast<MeshRenderer*>(object);
if (!renderer) return;
Material* mat = renderer->Material();
uint32_t i;
if (mat == opaque.get()) {
i = opaque_i;
opaque_i++;
if (opaque_i >= arraySize) curOpaque.reset();
if (!curOpaque) {
opaque_i = opaque_i % arraySize;
curOpaque = make_shared<Material>("PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm"));
curOpaque->EnableKeyword("TEXTURED");
curOpaque->SetParameter("TextureST", float4(1, 1, 0, 0));
}
renderer->Material(curOpaque);
mat = curOpaque.get();
} else if (mat == alphaClip.get()) {
i = clip_i;
clip_i++;
if (clip_i >= arraySize) curClip.reset();
if (!curClip) {
clip_i = clip_i % arraySize;
curClip = make_shared<Material>("Cutout PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm"));
curClip->RenderQueue(5000);
curClip->BlendMode(BLEND_MODE_ALPHA);
curClip->CullMode(VK_CULL_MODE_NONE);
curClip->EnableKeyword("TEXTURED");
curClip->EnableKeyword("ALPHA_CLIP");
curClip->EnableKeyword("TWO_SIDED");
curClip->SetParameter("TextureST", float4(1, 1, 0, 0));
}
renderer->Material(curClip);
mat = curClip.get();
} else if (mat == alphaBlend.get()) {
i = blend_i;
blend_i++;
if (blend_i >= 64) curBlend.reset();
if (!curBlend) {
blend_i = blend_i % arraySize;
curBlend = make_shared<Material>("Transparent PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm"));
curBlend->RenderQueue(5000);
curBlend->BlendMode(BLEND_MODE_ALPHA);
curBlend->CullMode(VK_CULL_MODE_NONE);
curBlend->EnableKeyword("TEXTURED");
curBlend->EnableKeyword("TWO_SIDED");
curBlend->SetParameter("TextureST", float4(1, 1, 0, 0));
}
renderer->Material(curBlend);
mat = curBlend.get();
} else return;
mat->PassMask((PassType)(PASS_RAYTRACE));
aiColor3D emissiveColor(0);
aiColor4D baseColor(1);
float metallic = 1.f;
float roughness = 1.f;
aiString baseColorTexture, metalRoughTexture, normalTexture, emissiveTexture;
if (aimaterial->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, &baseColorTexture) == AI_SUCCESS && baseColorTexture.length) {
mat->SetParameter("MainTextures", i, scene->AssetManager()->LoadTexture(folder + baseColorTexture.C_Str()));
baseColor = aiColor4D(1);
} else
mat->SetParameter("MainTextures", i, scene->AssetManager()->LoadTexture("Assets/Textures/white.png"));
if (aimaterial->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &metalRoughTexture) == AI_SUCCESS && metalRoughTexture.length)
mat->SetParameter("MaskTextures", i, scene->AssetManager()->LoadTexture(folder + metalRoughTexture.C_Str(), false));
else
mat->SetParameter("MaskTextures", i, scene->AssetManager()->LoadTexture("Assets/Textures/mask.png", false));
if (aimaterial->GetTexture(aiTextureType_NORMALS, 0, &normalTexture) == AI_SUCCESS && normalTexture.length)
mat->SetParameter("NormalTextures", i, scene->AssetManager()->LoadTexture(folder + normalTexture.C_Str(), false));
else
mat->SetParameter("NormalTextures", i, scene->AssetManager()->LoadTexture("Assets/Textures/bump.png", false));
aimaterial->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, baseColor);
aimaterial->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, metallic);
aimaterial->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, roughness);
aimaterial->Get(AI_MATKEY_COLOR_EMISSIVE, emissiveColor);
renderer->PushConstant("TextureIndex", i);
renderer->PushConstant("Color", float4(baseColor.r, baseColor.g, baseColor.b, baseColor.a));
renderer->PushConstant("Roughness", roughness);
renderer->PushConstant("Metallic", metallic);
renderer->PushConstant("Emission", float3(emissiveColor.r, emissiveColor.g, emissiveColor.b));
};
Object* root = mScene->LoadModelScene(folder + file, matfunc, objfunc, .6f, 1.f, .05f, .0015f);
root->LocalRotation(quaternion(float3(0, PI / 2, 0)));
queue<Object*> nodes;
nodes.push(root);
while (nodes.size()) {
Object* o = nodes.front();
nodes.pop();
for (uint32_t i = 0; i < o->ChildCount(); i++)
nodes.push(o->Child(i));
mObjects.push_back(o);
if (Light* l = dynamic_cast<Light*>(o)){
if (l->Type() == LIGHT_TYPE_SUN){
l->CascadeCount(1);
l->ShadowDistance(30);
}
}
}
#pragma endregion
mFrameData = new FrameData[mScene->Instance()->Device()->MaxFramesInFlight()];
for (uint32_t i = 0; i < mScene->Instance()->Device()->MaxFramesInFlight(); i++) {
mFrameData[i].mPrimary = nullptr;
mFrameData[i].mSecondary = nullptr;
mFrameData[i].mMeta = nullptr;
mFrameData[i].mResolveTmp = nullptr;
mFrameData[i].mResolve = nullptr;
mFrameData[i].mNodes = nullptr;
mFrameData[i].mLeafNodes = nullptr;
mFrameData[i].mVertices = nullptr;
mFrameData[i].mTriangles = nullptr;
mFrameData[i].mLights = nullptr;
mFrameData[i].mMaterials = nullptr;
mFrameData[i].mBvhBase = 0;
mFrameData[i].mLightCount = 0;
mFrameData[i].mLastBuild = 0;
}
return true;
}
PLUGIN_EXPORT void PreRender(CommandBuffer* commandBuffer, Camera* camera, PassType pass) override {
if (pass != PASS_MAIN) return;
FrameData& fd = mFrameData[commandBuffer->Device()->FrameContextIndex()];
if (fd.mLastBuild <= mScene->LastBvhBuild())
Build(commandBuffer, fd);
VkPipelineStageFlags dstStage, srcStage;
VkImageMemoryBarrier barriers[4];
if (fd.mPrimary && (fd.mPrimary->Width() != camera->FramebufferWidth() || fd.mPrimary->Height() != camera->FramebufferHeight())) {
safe_delete(fd.mPrimary);
safe_delete(fd.mSecondary);
safe_delete(fd.mMeta);
safe_delete(fd.mResolveTmp);
safe_delete(fd.mResolve);
}
if (!fd.mPrimary) {
fd.mPrimary = new Texture("Raytrace Primary", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1,
VK_FORMAT_R32G32B32A32_SFLOAT, VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
fd.mSecondary = new Texture("Raytrace Secondary", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1,
VK_FORMAT_R32G32B32A32_SFLOAT, VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
fd.mMeta = new Texture("Raytrace Meta", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1,
VK_FORMAT_R32G32B32A32_SFLOAT, VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
fd.mResolveTmp = new Texture("Raytrace Resolve", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1,
VK_FORMAT_R16G16B16A16_SFLOAT, VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
fd.mResolve = new Texture("Raytrace Resolve", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1,
VK_FORMAT_R16G16B16A16_SFLOAT, VK_SAMPLE_COUNT_1_BIT,
VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT);
fd.mResolveTmp->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, commandBuffer);
barriers[0] = fd.mPrimary->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
barriers[1] = fd.mSecondary->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
barriers[2] = fd.mMeta->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
barriers[3] = fd.mResolve->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
vkCmdPipelineBarrier(*commandBuffer,
srcStage, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0,
0, nullptr,
0, nullptr,
4, barriers);
}
#pragma region raytrace
FrameData& pfd = mFrameData[(commandBuffer->Device()->FrameContextIndex() + (commandBuffer->Device()->MaxFramesInFlight()-1)) % commandBuffer->Device()->MaxFramesInFlight()];
bool accum = pfd.mPrimary && pfd.mPrimary->Width() == fd.mPrimary->Width() && pfd.mPrimary->Height() == fd.mPrimary->Height();
Shader* rt = mScene->AssetManager()->LoadShader("Shaders/raytrace.stm");
ComputeShader* trace = accum ? rt->GetCompute("Raytrace", { "ACCUMULATE" }) : rt->GetCompute("Raytrace", {});
vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, trace->mPipeline);
fd.mViewProjection = camera->ViewProjection();
fd.mInvViewProjection = inverse(camera->ViewProjection());
fd.mCameraPosition = camera->WorldPosition();
float2 res(fd.mPrimary->Width(), fd.mPrimary->Height());
float near = camera->Near();
float far = camera->Far();
uint32_t vs = sizeof(StdVertex);
uint32_t is = sizeof(uint32_t);
commandBuffer->PushConstant(trace, "LastViewProjection", &pfd.mViewProjection);
commandBuffer->PushConstant(trace, "LastCameraPosition", &pfd.mCameraPosition);
commandBuffer->PushConstant(trace, "InvViewProj", &fd.mInvViewProjection);
commandBuffer->PushConstant(trace, "Resolution", &res);
commandBuffer->PushConstant(trace, "Near", &near);
commandBuffer->PushConstant(trace, "Far", &far);
commandBuffer->PushConstant(trace, "CameraPosition", &fd.mCameraPosition);
commandBuffer->PushConstant(trace, "VertexStride", &vs);
commandBuffer->PushConstant(trace, "IndexStride", &is);
commandBuffer->PushConstant(trace, "BvhRoot", &fd.mBvhBase);
commandBuffer->PushConstant(trace, "FrameIndex", &mFrameIndex);
commandBuffer->PushConstant(trace, "LightCount", &fd.mLightCount);
DescriptorSet* ds = commandBuffer->Device()->GetTempDescriptorSet("RT", trace->mDescriptorSetLayouts[0]);
VkDeviceSize bufSize = AlignUp(sizeof(CameraBuffer), commandBuffer->Device()->Limits().minUniformBufferOffsetAlignment);
ds->CreateStorageTextureDescriptor(fd.mPrimary, trace->mDescriptorBindings.at("OutputPrimary").second.binding);
ds->CreateStorageTextureDescriptor(fd.mSecondary, trace->mDescriptorBindings.at("OutputSecondary").second.binding);
ds->CreateStorageTextureDescriptor(fd.mMeta, trace->mDescriptorBindings.at("OutputMeta").second.binding);
if (accum) {
ds->CreateSampledTextureDescriptor(pfd.mPrimary, trace->mDescriptorBindings.at("PreviousPrimary").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->CreateSampledTextureDescriptor(pfd.mSecondary, trace->mDescriptorBindings.at("PreviousSecondary").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->CreateSampledTextureDescriptor(pfd.mMeta, trace->mDescriptorBindings.at("PreviousMeta").second.binding, VK_IMAGE_LAYOUT_GENERAL);
}
ds->CreateStorageBufferDescriptor(fd.mNodes, 0, fd.mNodes->Size(), trace->mDescriptorBindings.at("SceneBvh").second.binding);
ds->CreateStorageBufferDescriptor(fd.mLeafNodes, 0, fd.mLeafNodes->Size(), trace->mDescriptorBindings.at("LeafNodes").second.binding);
ds->CreateStorageBufferDescriptor(fd.mVertices, 0, fd.mVertices->Size(), trace->mDescriptorBindings.at("Vertices").second.binding);
ds->CreateStorageBufferDescriptor(fd.mTriangles, 0, fd.mTriangles->Size(), trace->mDescriptorBindings.at("Triangles").second.binding);
ds->CreateStorageBufferDescriptor(fd.mMaterials, 0, fd.mMaterials->Size(), trace->mDescriptorBindings.at("Materials").second.binding);
ds->CreateStorageBufferDescriptor(fd.mLights, 0, fd.mLights->Size(), trace->mDescriptorBindings.at("Lights").second.binding);
ds->CreateSampledTextureDescriptor(mScene->AssetManager()->LoadTexture("Assets/Textures/rgbanoise.png", false), trace->mDescriptorBindings.at("NoiseTex").second.binding, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
ds->FlushWrites();
vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, trace->mPipelineLayout, 0, 1, *ds, 0, nullptr);
vkCmdDispatch(*commandBuffer, (fd.mPrimary->Width() + 7) / 8, (fd.mPrimary->Height() + 7) / 8, 1);
#pragma endregion
barriers[0] = fd.mPrimary->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
barriers[1] = fd.mSecondary->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
barriers[2] = fd.mMeta->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
vkCmdPipelineBarrier(*commandBuffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0,
0, nullptr,
0, nullptr,
3, barriers);
uint2 ires(camera->FramebufferWidth(), camera->FramebufferHeight());
#pragma region combine x
ComputeShader* combine = mScene->AssetManager()->LoadShader("Shaders/resolve.stm")->GetCompute("Combine", {"MULTI_COMBINE"});
vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipeline);
ds = commandBuffer->Device()->GetTempDescriptorSet("Resolve", combine->mDescriptorSetLayouts[0]);
ds->CreateSampledTextureDescriptor(fd.mPrimary, combine->mDescriptorBindings.at("Primary").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->CreateSampledTextureDescriptor(fd.mSecondary, combine->mDescriptorBindings.at("Secondary").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->CreateSampledTextureDescriptor(fd.mMeta, combine->mDescriptorBindings.at("Meta").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->CreateStorageTextureDescriptor(fd.mResolveTmp, combine->mDescriptorBindings.at("Output").second.binding);
ds->FlushWrites();
vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipelineLayout, 0, 1, *ds, 0, nullptr);
commandBuffer->PushConstant(combine, "InvViewProj", &fd.mInvViewProjection);
commandBuffer->PushConstant(combine, "Resolution", &ires);
commandBuffer->PushConstant(combine, "CameraPosition", &fd.mCameraPosition);
uint32_t axis = 0;
commandBuffer->PushConstant(combine, "BlurAxis", &axis);
vkCmdDispatch(*commandBuffer, (fd.mResolve->Width() + 7) / 8, (fd.mResolve->Height() + 7) / 8, 1);
#pragma endregion
barriers[0] = fd.mResolveTmp->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
vkCmdPipelineBarrier(*commandBuffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
0,
0, nullptr,
0, nullptr,
1, barriers);
#pragma region combine y
combine = mScene->AssetManager()->LoadShader("Shaders/resolve.stm")->GetCompute("Combine", {});
vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipeline);
ds = commandBuffer->Device()->GetTempDescriptorSet("Resolve2", combine->mDescriptorSetLayouts[0]);
ds->CreateSampledTextureDescriptor(fd.mResolveTmp, combine->mDescriptorBindings.at("Primary").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->CreateSampledTextureDescriptor(fd.mMeta, combine->mDescriptorBindings.at("Meta").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->CreateStorageTextureDescriptor(fd.mResolve, combine->mDescriptorBindings.at("Output").second.binding);
ds->FlushWrites();
vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipelineLayout, 0, 1, *ds, 0, nullptr);
commandBuffer->PushConstant(combine, "InvViewProj", &fd.mInvViewProjection);
commandBuffer->PushConstant(combine, "Resolution", &ires);
commandBuffer->PushConstant(combine, "CameraPosition", &fd.mCameraPosition);
axis = 1;
commandBuffer->PushConstant(combine, "BlurAxis", &axis);
vkCmdDispatch(*commandBuffer, (fd.mResolve->Width() + 7) / 8, (fd.mResolve->Height() + 7) / 8, 1);
#pragma endregion
barriers[0] = fd.mResolve->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage);
vkCmdPipelineBarrier(*commandBuffer,
VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
0,
0, nullptr,
0, nullptr,
1, barriers);
mFrameIndex++;
}
PLUGIN_EXPORT void PostRenderScene(CommandBuffer* commandBuffer, Camera* camera, PassType pass) override {
if (pass != PASS_MAIN) return;
GraphicsShader* shader = mScene->AssetManager()->LoadShader("Shaders/rtblit.stm")->GetGraphics(PASS_MAIN, {});
if (!shader) return;
VkPipelineLayout layout = commandBuffer->BindShader(shader, pass, nullptr);
if (!layout) return;
float4 st(1, 1, 0, 0);
float4 tst(1, -1, 0, 1);
float exposure = .4f;
FrameData& fd = mFrameData[commandBuffer->Device()->FrameContextIndex()];
commandBuffer->PushConstant(shader, "ScaleTranslate", &st);
commandBuffer->PushConstant(shader, "TextureST", &tst);
commandBuffer->PushConstant(shader, "Exposure", &exposure);
DescriptorSet* ds = commandBuffer->Device()->GetTempDescriptorSet("Blit", shader->mDescriptorSetLayouts[0]);
ds->CreateSampledTextureDescriptor(fd.mResolve, shader->mDescriptorBindings.at("Radiance").second.binding, VK_IMAGE_LAYOUT_GENERAL);
ds->FlushWrites();
vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, *ds, 0, nullptr);
vkCmdDraw(*commandBuffer, 6, 1, 0, 0);
}
};
ENGINE_PLUGIN(Raytracing) | 43.782934 | 284 | 0.729716 | cryptobuks1 |
c1be765e20213864af4152203dab76e411c8a402 | 1,364 | cpp | C++ | Sources/Athena2D/Tools/TextureCacheViewer.cpp | jccit/Athena | fa204647bf9e60ae113fcaf5e391813da51b0881 | [
"BSD-3-Clause"
] | null | null | null | Sources/Athena2D/Tools/TextureCacheViewer.cpp | jccit/Athena | fa204647bf9e60ae113fcaf5e391813da51b0881 | [
"BSD-3-Clause"
] | null | null | null | Sources/Athena2D/Tools/TextureCacheViewer.cpp | jccit/Athena | fa204647bf9e60ae113fcaf5e391813da51b0881 | [
"BSD-3-Clause"
] | null | null | null | #include "pch.h"
#include "TextureCacheViewer.h"
#include <imgui.h>
TextureCacheViewer::TextureCacheViewer(std::map<std::string, SDL_Texture*>* texCache)
{
title = "Texture Cache Viewer";
cache = texCache;
}
std::string selectedTexture;
void TextureCacheViewer::renderPanel()
{
if (isShowing()) {
// left
{
ImGui::BeginChild("items", ImVec2(200, 0), true);
for (auto& cacheEntry : *cache) {
if (selectedTexture.empty()) {
selectedTexture = cacheEntry.first;
}
if (ImGui::Selectable(cacheEntry.first.c_str(), selectedTexture == cacheEntry.first))
selectedTexture = cacheEntry.first;
}
ImGui::EndChild();
}
ImGui::SameLine();
// right
{
ImGui::BeginChild("item view", ImVec2(0, 0));
if (cache->count(selectedTexture)) {
SDL_Texture* tex = cache->at(selectedTexture);
int texWidth = 0;
int texHeight = 0;
SDL_QueryTexture(tex, nullptr, nullptr, &texWidth, &texHeight);
ImGui::Image((ImTextureID)tex, ImVec2(static_cast<float>(texWidth), static_cast<float>(texHeight)));
}
ImGui::EndChild();
}
ImGui::End();
}
}
| 25.735849 | 116 | 0.53739 | jccit |
c1bfb7e91d02182de5900b8f923a1994a968e98e | 14,499 | cpp | C++ | src/cinder/app/android/AppImplAndroid.cpp | rsh/Cinder-Emscripten | 4a08250c56656865c7c3a52fb9380980908b1439 | [
"BSD-2-Clause"
] | 3,494 | 2015-01-02T08:42:09.000Z | 2022-03-31T14:16:23.000Z | src/cinder/app/android/AppImplAndroid.cpp | rsh/Cinder-Emscripten | 4a08250c56656865c7c3a52fb9380980908b1439 | [
"BSD-2-Clause"
] | 1,284 | 2015-01-02T07:31:47.000Z | 2022-03-30T02:06:43.000Z | src/cinder/app/android/AppImplAndroid.cpp | rsh/Cinder-Emscripten | 4a08250c56656865c7c3a52fb9380980908b1439 | [
"BSD-2-Clause"
] | 780 | 2015-01-02T22:14:29.000Z | 2022-03-30T00:16:56.000Z | /*
Copyright (c) 2012, The Cinder Project, All rights reserved.
This code is intended for use with the Cinder C++ library: http://libcinder.org
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "cinder/app/android/AppImplAndroid.h"
#include "cinder/app/android/EventManagerAndroid.h"
#include "cinder/app/android/WindowImplAndroid.h"
#include "cinder/app/AppBase.h"
#include "cinder/app/TouchEvent.h"
#include "cinder/android/app/CinderNativeActivity.h"
#include <sys/types.h>
#include <unistd.h>
#include <fstream>
#include <sstream>
namespace cinder { namespace app {
static AppImplAndroid* sInstance = nullptr;
AppImplAndroid::TrackedTouch::TrackedTouch( int aId, float aX, float aY, double aCurrentTime )
: id( aId ), x( aX ), y( aY ), prevX( aX ), prevY( aY ), currentTime( aCurrentTime )
{
}
void AppImplAndroid::TrackedTouch::update( float aX, float aY, double aCurrentTime )
{
prevX = x;
prevY = y;
x = aX;
y = aY;
currentTime = aCurrentTime;
}
AppImplAndroid::AppImplAndroid( AppAndroid *aApp, const AppAndroid::Settings &settings )
: mApp( aApp ), mSetupHasBeenCalled( false ), mCanProcessEvents( false ), mActive( false ) //, mFocused( false )
{
sInstance = this;
EventManagerAndroid::instance()->setAppImplInst( this );
mNativeApp = EventManagerAndroid::instance()->getNativeApp();
mFrameRate = settings.getFrameRate();
mFrameRateEnabled = settings.isFrameRateEnabled();
mQuitOnLastWindowClosed = settings.isQuitOnLastWindowCloseEnabled();
cinder::android::app::CinderNativeActivity::setFullScreen( settings.isFullScreen() );
auto formats = settings.getWindowFormats();
if( formats.empty() ) {
formats.push_back( settings.getDefaultWindowFormat() );
}
for( auto &format : formats ) {
if( ! format.isTitleSpecified() ) {
format.setTitle( settings.getTitle() );
}
createWindow( format );
}
// Set the active window
if( ! mWindows.empty() ) {
setWindow( mWindows.back()->getWindow() );
}
}
AppImplAndroid::~AppImplAndroid()
{
}
AppImplAndroid *AppImplAndroid::getInstance()
{
return sInstance;
}
AppAndroid* AppImplAndroid::getApp()
{
return mApp;
}
struct android_app *AppImplAndroid::getNative()
{
return mNativeApp;
}
void AppImplAndroid::setup()
{
mApp->privateSetup__();
mSetupHasBeenCalled = true;
// issue initial app activation event
mApp->emitDidBecomeActive();
for( auto &window : mWindows ) {
window->resize();
}
// initialize our next frame time
mNextFrameTime = getElapsedSeconds();
// enable event processing
mCanProcessEvents = true;
}
void AppImplAndroid::sleepUntilNextFrame()
{
// get current time in seconds
double currentSeconds = getElapsedSeconds();
// calculate time per frame in seconds
double secondsPerFrame = 1.0 / mFrameRate;
// determine if application was frozen for a while and adjust next frame time
double elapsedSeconds = currentSeconds - mNextFrameTime;
if( elapsedSeconds > 1.0 ) {
int numSkipFrames = (int)(elapsedSeconds / secondsPerFrame);
mNextFrameTime += (numSkipFrames * secondsPerFrame);
}
// determine when next frame should be drawn
mNextFrameTime += secondsPerFrame;
// sleep and process messages until next frame
if( ( mFrameRateEnabled ) && ( mNextFrameTime > currentSeconds ) ) {
double sleepTime = std::max( mNextFrameTime - currentSeconds, 0.0 );
unsigned long sleepMicroSecs = sleepTime*1000000L;
usleep(sleepMicroSecs);
}
}
void AppImplAndroid::updateAndDraw()
{
mApp->privateUpdate__();
for( auto &window : mWindows ) {
window->draw();
}
}
void AppImplAndroid::onTouchBegan( int id, float x, float y )
{
double currentTime = app::getElapsedSeconds();
TrackedTouch tt = TrackedTouch( id, x, y, currentTime );
mTrackedTouches[id] = tt;
vec2 pos = vec2( tt.x, tt.y );
vec2 prevPos = vec2( tt.prevX, tt.prevY );
std::vector<TouchEvent::Touch> beganTouches;
beganTouches.push_back( TouchEvent::Touch( pos, prevPos, tt.id, tt.currentTime, nullptr ) );
// Update active touches
updateActiveTouches();
// Emit
if( mApp->isMultiTouchEnabled() ) {
TouchEvent event( getWindow(), beganTouches );
getWindow()->emitTouchesBegan( &event );
}
else {
if( -1 == mMouseTouchId ) {
mMouseTouchId = id;
mMouseTouchPos = ivec2( tt.x, tt.y );
int initiator = MouseEvent::LEFT_DOWN;
int modifier = MouseEvent::LEFT_DOWN;
MouseEvent event( getWindow(), initiator, tt.x, tt.y, modifier, 0.0f, 0 );
getWindow()->emitMouseDown( &event );
}
}
}
/*
void AppImplAndroid::onTouchMoved( int id, float x, float y )
{
double currentTime = app::getElapsedSeconds();
std::map<int, TrackedTouch>::iterator iter = mTrackedTouches.find( id );
if( iter != mTrackedTouches.end() ) {
TrackedTouch& tt = iter->second;
tt.update( x, y, currentTime );
vec2 pos = vec2( tt.x, tt.y );
vec2 prevPos = vec2( tt.prevX, tt.prevY );
std::vector<TouchEvent::Touch> movedTouches;
movedTouches.push_back( TouchEvent::Touch( pos, prevPos, tt.id, tt.currentTime, nullptr ) );
// Update active touches
updateActiveTouches();
// Emit
if( mApp->isMultiTouchEnabled() ) {
TouchEvent event( getWindow(), movedTouches );
getWindow()->emitTouchesMoved( &event );
}
else {
}
}
}
*/
void AppImplAndroid::onTouchesMoved( const std::vector<AppImplAndroid::TrackedTouch>& moveTrackedTouches )
{
double currentTime = app::getElapsedSeconds();
std::vector<TouchEvent::Touch> movedTouches;
for( const AppImplAndroid::TrackedTouch& mtt : moveTrackedTouches ) {
std::map<int, TrackedTouch>::iterator iter = mTrackedTouches.find( mtt.id );
if( iter != mTrackedTouches.end() ) {
TrackedTouch& tt = iter->second;
tt.update( mtt.x, mtt.y, currentTime );
vec2 pos = vec2( tt.x, tt.y );
vec2 prevPos = vec2( tt.prevX, tt.prevY );
movedTouches.push_back( TouchEvent::Touch( pos, prevPos, tt.id, tt.currentTime, nullptr ) );
}
}
// Update active touches
updateActiveTouches();
// Emit
if( ! movedTouches.empty() ) {
if( mApp->isMultiTouchEnabled() ) {
TouchEvent event( getWindow(), movedTouches );
getWindow()->emitTouchesMoved( &event );
}
else {
if( -1 != mMouseTouchId ) {
auto iter = mTrackedTouches.find( mMouseTouchId );
TrackedTouch& tt = iter->second;
mMouseTouchPos = ivec2( tt.x, tt.y );
int initiator = MouseEvent::LEFT_DOWN;
int modifier = MouseEvent::LEFT_DOWN;
MouseEvent event( getWindow(), initiator, tt.x, tt.y, modifier, 0.0f, 0 );
getWindow()->emitMouseDrag( &event );
}
}
}
}
void AppImplAndroid::onTouchEnded( int id, float x, float y )
{
double currentTime = app::getElapsedSeconds();
std::map<int, TrackedTouch>::iterator iter = mTrackedTouches.find( id );
if( iter != mTrackedTouches.end() ) {
TrackedTouch& tt = iter->second;
tt.update( x, y, currentTime );
vec2 pos = vec2( tt.x, tt.y );
vec2 prevPos = vec2( tt.prevX, tt.prevY );
std::vector<TouchEvent::Touch> endedTouches;
endedTouches.push_back( TouchEvent::Touch( pos, prevPos, tt.id, tt.currentTime, nullptr ) );
// Emit
if( mApp->isMultiTouchEnabled() ) {
TouchEvent event( getWindow(), endedTouches );
getWindow()->emitTouchesEnded( &event );
}
else {
if( id == mMouseTouchId ) {
mMouseTouchId = -1;
int initiator = MouseEvent::LEFT_DOWN;
int modifier = MouseEvent::LEFT_DOWN;
MouseEvent event( getWindow(), initiator, tt.x, tt.y, modifier, 0.0f, 0 );
getWindow()->emitMouseUp( &event );
}
}
// Remove the tracked touch
mTrackedTouches.erase( id );
// Find the next recent touch to map mouse to
if( ( ! mApp->isMultiTouchEnabled() ) && ( -1 == mMouseTouchId ) && ( ! mTrackedTouches.empty() ) ) {
TrackedTouch tt = mTrackedTouches.begin()->second;
for( auto& iter : mTrackedTouches ) {
if( iter.second.currentTime < tt.currentTime ) {
tt = iter.second;
}
}
mMouseTouchId = tt.id;
mMouseTouchPos = ivec2( tt.x, tt.y );
}
}
// Update active touches
updateActiveTouches();
}
const std::vector<TouchEvent::Touch>& AppImplAndroid::getActiveTouches() const
{
return mActiveTouches;
}
void AppImplAndroid::updateActiveTouches()
{
mActiveTouches.clear();
for( std::map<int, TrackedTouch>::iterator iter = mTrackedTouches.begin(); iter != mTrackedTouches.end(); ++iter ) {
TrackedTouch& tt = iter->second;
vec2 pos = vec2( tt.x, tt.y );
vec2 prevPos = vec2( tt.prevX, tt.prevY );
TouchEvent::Touch touch = TouchEvent::Touch( pos, prevPos, tt.id, tt.currentTime, nullptr );
mActiveTouches.push_back( touch );
}
}
WindowRef AppImplAndroid::createWindow( Window::Format format )
{
if( ! format.getRenderer() ) {
format.setRenderer( mApp->getDefaultRenderer()->clone() );
}
mWindows.push_back( new WindowImplAndroid( mNativeApp->window, format, nullptr, this ) );
// emit initial resize if we have fired setup
if( mSetupHasBeenCalled ) {
mWindows.back()->getWindow()->emitResize();
}
return mWindows.back()->getWindow();
}
void AppImplAndroid::reinitializeWindowSurface()
{
if( mActiveWindow ) {
// When the reinitialized from EnvironmentManager android_app->window (mNativeApp) will
// contain a new window. Propogate that along to the WindowImplAndroid.
mActiveWindow->getImpl()->reinitializeWindowSurface( mNativeApp->window );
}
}
void AppImplAndroid::quit()
{
// Close all windows, forcing the application to quit.
while( ! mWindows.empty() ) {
mWindows.back()->close();
}
// Always quit, even if ! isQuitOnLastWindowCloseEnabled()
EventManagerAndroid::instance()->setShouldQuit( true );
}
void AppImplAndroid::sleep( double seconds )
{
useconds_t milliseconds = (useconds_t)(seconds*1000.0);
useconds_t microsecs = milliseconds * 1000;
::usleep( microsecs );
}
bool AppImplAndroid::setupHasBeenCalled() const
{
return mSetupHasBeenCalled;
}
float AppImplAndroid::getFrameRate() const
{
return mFrameRate;
}
void AppImplAndroid::setFrameRate( float frameRate )
{
mFrameRate = frameRate;
mFrameRateEnabled = true;
mNextFrameTime = mApp->getElapsedSeconds();
}
void AppImplAndroid::disableFrameRate()
{
mFrameRateEnabled = false;
}
bool AppImplAndroid::isFrameRateEnabled() const
{
return mFrameRateEnabled;
}
RendererRef AppImplAndroid::findSharedRenderer( const RendererRef &searchRenderer )
{
if( ! searchRenderer )
return RendererRef();
for( const auto &win : mWindows ) {
RendererRef renderer = win->getRenderer();
if( renderer && ( typeid(*renderer) == typeid(*searchRenderer) ) )
return renderer;
}
return RendererRef();
}
WindowRef AppImplAndroid::getWindow() const
{
return mActiveWindow;
}
void AppImplAndroid::setWindow( WindowRef window )
{
mActiveWindow = window;
}
size_t AppImplAndroid::getNumWindows() const
{
return mWindows.size();
}
WindowRef AppImplAndroid::getWindowIndex( size_t index ) const
{
if( index >= mWindows.size() )
return cinder::app::WindowRef();
auto winIt = mWindows.begin();
std::advance( winIt, index );
return (*winIt)->mWindowRef;
}
WindowRef AppImplAndroid::getForegroundWindow() const
{
return mForegroundWindow;
}
void AppImplAndroid::setForegroundWindow( WindowRef window )
{
mForegroundWindow = window;
}
void AppImplAndroid::closeWindow( WindowImplAndroid *windowImpl )
{
auto winIt = find( mWindows.begin(), mWindows.end(), windowImpl );
if( winIt != mWindows.end() ) {
windowImpl->getWindow()->emitClose();
windowImpl->privateClose();
delete windowImpl; // this corresponds to winIt
mWindows.erase( winIt );
}
if( mWindows.empty() && mQuitOnLastWindowClosed ) {
EventManagerAndroid::instance()->setShouldQuit( true );
}
}
void AppImplAndroid::hideCursor()
{
throw (std::string(__FUNCTION__) + " not implemented yet").c_str();
}
void AppImplAndroid::showCursor()
{
throw (std::string(__FUNCTION__) + " not implemented yet").c_str();
}
ivec2 AppImplAndroid::getMousePos() const
{
return mMouseTouchPos;
}
// @REMOVE
// fs::path AppImplAndroid::getAppPath()
// {
// fs::path result;
// pid_t pid = getpid();
// std::stringstream ss;
// ss << "/proc/" << pid << "/cmdline";
// std::string procPath = ss.str();
// std::ifstream is( procPath.c_str() );
// if( is.is_open() ) {
// std::vector<char> buf;
// char c;
// while( is.get( c ) ) {
// buf.push_back( c );
// if( 0 == c ) {
// break;
// }
// }
// if( ! buf.empty() ) {
// result = std::string( (const char *)(&buf[0]), buf.size() );
// }
// }
// return result;
// }
fs::path AppImplAndroid::getOpenFilePath( const fs::path &initialPath, std::vector<std::string> extensions )
{
throw (std::string(__FUNCTION__) + " not implemented yet").c_str();
return fs::path();
}
fs::path AppImplAndroid::getSaveFilePath( const fs::path &initialPath, std::vector<std::string> extensions )
{
throw (std::string(__FUNCTION__) + " not implemented yet").c_str();
return fs::path();
}
fs::path AppImplAndroid::getFolderPath( const fs::path &initialPath )
{
throw (std::string(__FUNCTION__) + " not implemented yet").c_str();
return fs::path();
}
ivec2 AppImplAndroid::getScreenSize() const
{
ivec2 result = ivec2( 0 );
if( nullptr != mNativeApp->window ) {
result.x = ANativeWindow_getWidth( mNativeApp->window );
result.y = ANativeWindow_getHeight( mNativeApp->window );
}
return result;
}
} } // namespace cinder::app
| 26.652574 | 117 | 0.704118 | rsh |
c1c1ed9a884c62b14ed8e9ff4704ba783db8b35e | 11,757 | cpp | C++ | test/source/tests/executor_tests/inline_executor_tests.cpp | insujang/concurrencpp | 580f430caf1369521ee1422c15c4c8a89823972b | [
"MIT"
] | 1 | 2022-01-08T01:53:16.000Z | 2022-01-08T01:53:16.000Z | test/source/tests/executor_tests/inline_executor_tests.cpp | tlming16/concurrencpp | 580f430caf1369521ee1422c15c4c8a89823972b | [
"MIT"
] | null | null | null | test/source/tests/executor_tests/inline_executor_tests.cpp | tlming16/concurrencpp | 580f430caf1369521ee1422c15c4c8a89823972b | [
"MIT"
] | null | null | null | #include "concurrencpp/concurrencpp.h"
#include "infra/tester.h"
#include "infra/assertions.h"
#include "utils/object_observer.h"
#include "utils/test_generators.h"
#include "utils/test_ready_result.h"
#include "utils/executor_shutdowner.h"
namespace concurrencpp::tests {
void test_inline_executor_name();
void test_inline_executor_shutdown();
void test_inline_executor_max_concurrency_level();
void test_inline_executor_post_exception();
void test_inline_executor_post_foreign();
void test_inline_executor_post_inline();
void test_inline_executor_post();
void test_inline_executor_submit_exception();
void test_inline_executor_submit_foreign();
void test_inline_executor_submit_inline();
void test_inline_executor_submit();
void test_inline_executor_bulk_post_exception();
void test_inline_executor_bulk_post_foreign();
void test_inline_executor_bulk_post_inline();
void test_inline_executor_bulk_post();
void test_inline_executor_bulk_submit_exception();
void test_inline_executor_bulk_submit_foreign();
void test_inline_executor_bulk_submit_inline();
void test_inline_executor_bulk_submit();
void assert_executed_inline(const std::unordered_map<size_t, size_t>& execution_map) noexcept {
assert_equal(execution_map.size(), static_cast<size_t>(1));
assert_equal(execution_map.begin()->first, ::concurrencpp::details::thread::get_current_virtual_id());
}
} // namespace concurrencpp::tests
using concurrencpp::details::thread;
void concurrencpp::tests::test_inline_executor_name() {
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
assert_equal(executor->name, concurrencpp::details::consts::k_inline_executor_name);
}
void concurrencpp::tests::test_inline_executor_shutdown() {
auto executor = std::make_shared<inline_executor>();
assert_false(executor->shutdown_requested());
executor->shutdown();
assert_true(executor->shutdown_requested());
// it's ok to shut down an executor more than once
executor->shutdown();
assert_throws<concurrencpp::errors::runtime_shutdown>([executor] {
executor->enqueue(concurrencpp::task {});
});
assert_throws<concurrencpp::errors::runtime_shutdown>([executor] {
concurrencpp::task array[4];
std::span<concurrencpp::task> span = array;
executor->enqueue(span);
});
}
void concurrencpp::tests::test_inline_executor_max_concurrency_level() {
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
assert_equal(executor->max_concurrency_level(), concurrencpp::details::consts::k_inline_executor_max_concurrency_level);
}
void concurrencpp::tests::test_inline_executor_post_exception() {
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
executor->post([] {
throw std::runtime_error("");
});
}
void concurrencpp::tests::test_inline_executor_post_foreign() {
object_observer observer;
const size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
for (size_t i = 0; i < task_count; i++) {
executor->post(observer.get_testing_stub());
}
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_post_inline() {
object_observer observer;
constexpr size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
executor->post([executor, &observer] {
for (size_t i = 0; i < task_count; i++) {
executor->post(observer.get_testing_stub());
}
});
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_post() {
test_inline_executor_post_exception();
test_inline_executor_post_inline();
test_inline_executor_post_foreign();
}
void concurrencpp::tests::test_inline_executor_submit_exception() {
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
constexpr intptr_t id = 12345;
auto result = executor->submit([id] {
throw custom_exception(id);
});
result.wait();
test_ready_result_custom_exception(std::move(result), id);
}
void concurrencpp::tests::test_inline_executor_submit_foreign() {
object_observer observer;
const size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
std::vector<result<size_t>> results;
results.resize(task_count);
for (size_t i = 0; i < task_count; i++) {
results[i] = executor->submit(observer.get_testing_stub(i));
}
for (size_t i = 0; i < task_count; i++) {
assert_equal(results[i].status(), result_status::value);
assert_equal(results[i].get(), i);
}
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_submit_inline() {
object_observer observer;
constexpr size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
auto results_res = executor->submit([executor, &observer] {
std::vector<result<size_t>> results;
results.resize(task_count);
for (size_t i = 0; i < task_count; i++) {
results[i] = executor->submit(observer.get_testing_stub(i));
}
return results;
});
auto results = results_res.get();
for (size_t i = 0; i < task_count; i++) {
assert_equal(results[i].status(), result_status::value);
assert_equal(results[i].get(), i);
}
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_submit() {
test_inline_executor_submit_exception();
test_inline_executor_submit_foreign();
test_inline_executor_submit_inline();
}
void concurrencpp::tests::test_inline_executor_bulk_post_exception() {
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
auto thrower = [] {
throw std::runtime_error("");
};
std::vector<decltype(thrower)> tasks;
tasks.resize(4);
executor->bulk_post<decltype(thrower)>(tasks);
}
void concurrencpp::tests::test_inline_executor_bulk_post_foreign() {
object_observer observer;
const size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
std::vector<testing_stub> stubs;
stubs.reserve(task_count);
for (size_t i = 0; i < task_count; i++) {
stubs.emplace_back(observer.get_testing_stub());
}
std::span<testing_stub> span = stubs;
executor->bulk_post<testing_stub>(span);
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_bulk_post_inline() {
object_observer observer;
constexpr size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
executor->post([executor, &observer]() mutable {
std::vector<testing_stub> stubs;
stubs.reserve(task_count);
for (size_t i = 0; i < task_count; i++) {
stubs.emplace_back(observer.get_testing_stub());
}
executor->bulk_post<testing_stub>(stubs);
});
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_bulk_post() {
test_inline_executor_bulk_post_exception();
test_inline_executor_bulk_post_foreign();
test_inline_executor_bulk_post_inline();
}
void concurrencpp::tests::test_inline_executor_bulk_submit_exception() {
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
constexpr intptr_t id = 12345;
auto thrower = [id] {
throw custom_exception(id);
};
std::vector<decltype(thrower)> tasks;
tasks.resize(4, thrower);
auto results = executor->bulk_submit<decltype(thrower)>(tasks);
for (auto& result : results) {
result.wait();
test_ready_result_custom_exception(std::move(result), id);
}
}
void concurrencpp::tests::test_inline_executor_bulk_submit_foreign() {
object_observer observer;
const size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
std::vector<value_testing_stub> stubs;
stubs.reserve(task_count);
for (size_t i = 0; i < task_count; i++) {
stubs.emplace_back(observer.get_testing_stub(i));
}
auto results = executor->bulk_submit<value_testing_stub>(stubs);
for (size_t i = 0; i < task_count; i++) {
assert_equal(results[i].status(), result_status::value);
assert_equal(results[i].get(), i);
}
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_bulk_submit_inline() {
object_observer observer;
constexpr size_t task_count = 1'024;
auto executor = std::make_shared<inline_executor>();
executor_shutdowner shutdown(executor);
auto results_res = executor->submit([executor, &observer] {
std::vector<value_testing_stub> stubs;
stubs.reserve(task_count);
for (size_t i = 0; i < task_count; i++) {
stubs.emplace_back(observer.get_testing_stub(i));
}
return executor->bulk_submit<value_testing_stub>(stubs);
});
auto results = results_res.get();
for (size_t i = 0; i < task_count; i++) {
assert_equal(results[i].status(), result_status::value);
assert_equal(results[i].get(), i);
}
assert_equal(observer.get_execution_count(), task_count);
assert_equal(observer.get_destruction_count(), task_count);
assert_executed_inline(observer.get_execution_map());
}
void concurrencpp::tests::test_inline_executor_bulk_submit() {
test_inline_executor_bulk_submit_exception();
test_inline_executor_bulk_submit_foreign();
test_inline_executor_bulk_submit_inline();
}
using namespace concurrencpp::tests;
int main() {
tester tester("inline_executor test");
tester.add_step("name", test_inline_executor_name);
tester.add_step("shutdown", test_inline_executor_shutdown);
tester.add_step("max_concurrency_level", test_inline_executor_max_concurrency_level);
tester.add_step("post", test_inline_executor_post);
tester.add_step("submit", test_inline_executor_submit);
tester.add_step("bulk_post", test_inline_executor_bulk_post);
tester.add_step("bulk_submit", test_inline_executor_bulk_submit);
tester.launch_test();
return 0;
} | 33.305949 | 124 | 0.722378 | insujang |
c1c5cd073ae8e747c8e3761617eaa3f5f7a62784 | 9,936 | cpp | C++ | src/misc/sharedmemory.cpp | OpenSpace/Ghoul | af5545a13d140b15e7b37f581ea7dde522be2b5b | [
"MIT"
] | 8 | 2016-09-13T12:39:49.000Z | 2022-03-21T12:30:50.000Z | src/misc/sharedmemory.cpp | OpenSpace/Ghoul | af5545a13d140b15e7b37f581ea7dde522be2b5b | [
"MIT"
] | 33 | 2016-07-07T20:35:05.000Z | 2021-10-15T03:12:13.000Z | src/misc/sharedmemory.cpp | OpenSpace/Ghoul | af5545a13d140b15e7b37f581ea7dde522be2b5b | [
"MIT"
] | 16 | 2015-06-24T20:41:28.000Z | 2022-01-08T04:14:03.000Z | /*****************************************************************************************
* *
* GHOUL *
* General Helpful Open Utility Library *
* *
* Copyright (c) 2012-2021 *
* *
* 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 <ghoul/misc/sharedmemory.h>
#include <ghoul/fmt.h>
#include <ghoul/misc/crc32.h>
#include <atomic>
#ifndef WIN32
#include <errno.h>
#include <string.h>
#include <sys/shm.h>
// Common access type bits, used with ipcperm()
#define IPC_R 000400 // read permission
#define IPC_W 000200 // write/alter permission
#define IPC_M 010000 // permission to change control info
#else
#include <Windows.h>
#endif
namespace ghoul {
#ifdef WIN32
std::map<const std::string, HANDLE> SharedMemory::_createdSections;
#endif // WIN32
namespace {
struct Header {
std::atomic_flag mutex;
#ifdef WIN32
size_t size;
#endif // WIN32
};
Header* header(void* memory) {
return reinterpret_cast<Header*>(memory);
}
#ifdef WIN32
std::string lastErrorToString(DWORD err) {
LPTSTR errorBuffer = nullptr;
DWORD nValues = FormatMessage(
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr,
err,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPTSTR>(&errorBuffer),
0,
nullptr
);
if ((nValues > 0) && (errorBuffer != nullptr)) {
std::string errorMsg(errorBuffer);
LocalFree(errorBuffer);
return errorMsg;
}
else {
return "Error constructing format message for error: " + std::to_string(err);
}
}
#endif // WIN32
}
SharedMemory::SharedMemoryError::SharedMemoryError(std::string msg)
: RuntimeError(std::move(msg), "SharedMemory")
{}
SharedMemory::SharedMemoryNotFoundError::SharedMemoryNotFoundError()
: SharedMemoryError("Shared memory did not exist")
{}
void SharedMemory::create(const std::string& name, size_t size) {
// adjust for the header size
size += sizeof(Header);
#ifdef WIN32
HANDLE handle = CreateFileMapping(
INVALID_HANDLE_VALUE, // NOLINT
nullptr,
PAGE_READWRITE,
0,
static_cast<DWORD>(size),
name.c_str()
);
const DWORD error = GetLastError();
if (!handle) {
std::string errorMsg = lastErrorToString(error);
throw SharedMemoryError(fmt::format(
"Error creating shared memory '{}': {}", name, errorMsg
));
}
if (error == ERROR_ALREADY_EXISTS) {
throw SharedMemoryError(fmt::format(
"Error creating shared memory '{}': Section exists", name
));
}
void* memory = MapViewOfFileEx(handle, FILE_MAP_ALL_ACCESS, 0, 0, 0, nullptr);
if (!memory) {
std::string errorMsg = lastErrorToString(error);
throw SharedMemoryError(fmt::format(
"Error creating a view on shared memory '{}': {}", name, errorMsg
));
}
Header* h = header(memory);
h->mutex.clear();
h->size = size - sizeof(Header);
UnmapViewOfFile(memory);
_createdSections[name] = handle;
#else // ^^^^ WIN32 // !WIN32 vvvv
unsigned int h = hashCRC32(name);
int result = shmget(h, size, IPC_CREAT | IPC_EXCL | IPC_R | IPC_W | IPC_M);
if (result == -1) {
std::string errorMsg = strerror(errno);
throw SharedMemoryError(fmt::format(
"Error creating shared memory '{}': {}", name, errorMsg
));
}
void* memory = shmat(result, nullptr, SHM_R | SHM_W);
Header* memoryHeader = header(memory);
memoryHeader->mutex.clear();
shmdt(memory);
#endif
} // WIN32
void SharedMemory::remove(const std::string& name) {
#ifdef WIN32
if (_createdSections.find(name) == _createdSections.end()) {
throw SharedMemoryNotFoundError();
}
HANDLE h = _createdSections[name];
_createdSections.erase(name);
BOOL result = CloseHandle(h);
if (result == 0) {
DWORD error = GetLastError();
std::string errorMsg = lastErrorToString(error);
throw SharedMemoryError("Error closing handle: " + errorMsg);
}
#else // ^^^^ WIN32 // !WIN32 vvvv
unsigned int h = hashCRC32(name);
int result = shmget(h, 0, IPC_R | IPC_W | IPC_M);
if (result == -1) {
std::string errorMsg = strerror(errno);
throw SharedMemoryError("Error while retrieving shared memory: " + errorMsg);
}
result = shmctl(result, IPC_RMID, nullptr);
if (result == -1) {
std::string errorMsg = strerror(errno);
throw SharedMemoryError("Error while removing shared memory: " + errorMsg);
}
#endif // WIN32
}
bool SharedMemory::exists(const std::string& name) {
#ifdef WIN32
HANDLE handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name.c_str());
if (handle) {
// the file exists, so we have to close it immediately to not leak the handle
CloseHandle(handle);
return true;
}
// The handle doesn't exist, which can mean two things: the memory mapped file
// doesn't exist or it exists but there was an error accessing it
const DWORD error = GetLastError();
if (error == ERROR_FILE_NOT_FOUND) {
return false;
}
else {
std::string errorMsg = lastErrorToString(error);
throw SharedMemoryError(
"Error checking if shared memory exists: " + errorMsg
);
}
#else // ^^^^ WIN32 // !WIN32 vvvv
unsigned int h = hashCRC32(name);
int result = shmget(h, 0, IPC_EXCL);
return result != -1;
#endif // WIN32
}
SharedMemory::SharedMemory(std::string name)
: _name(std::move(name))
{
#ifdef WIN32
_sharedMemoryHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, _name.c_str());
if (!_sharedMemoryHandle) {
std::string errorMsg = lastErrorToString(GetLastError());
throw SharedMemoryError(fmt::format(
"Error accessing shared memory '{}': {}", name, errorMsg
));
}
_memory = MapViewOfFileEx(_sharedMemoryHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0, nullptr);
if (!_memory) {
CloseHandle(_sharedMemoryHandle);
std::string errorMsg = lastErrorToString(GetLastError());
throw SharedMemoryError(fmt::format(
"Error creating view for shared memory '{}': {}", name, errorMsg
));
}
#else // ^^^^ WIN32 // !WIN32 vvvv
unsigned int h = hashCRC32(_name);
_sharedMemoryHandle = shmget(h, 0, IPC_R | IPC_W | IPC_M);
if (_sharedMemoryHandle == -1) {
std::string errorMsg = strerror(errno);
throw SharedMemoryError(
"Error accessing shared memory '" + name + "': " + errorMsg
);
}
_memory = shmat(_sharedMemoryHandle, nullptr, SHM_R | SHM_W);
if (_memory == reinterpret_cast<void*>(-1)) {
std::string errorMsg = strerror(errno);
throw SharedMemoryError("Error mapping shared memory '" + name + "':" + errorMsg);
}
struct shmid_ds sharedMemoryInfo;
shmctl(_sharedMemoryHandle, IPC_STAT, &sharedMemoryInfo);
_size = sharedMemoryInfo.shm_segsz - sizeof(Header);
#endif // WIN32
}
SharedMemory::~SharedMemory() {
#ifdef WIN32
CloseHandle(_sharedMemoryHandle);
UnmapViewOfFile(_memory);
#else // ^^^^ WIN32 // !WIN32 vvvv
shmdt(_memory);
#endif // WIN32
}
void* SharedMemory::memory() const {
return reinterpret_cast<void*>(reinterpret_cast<char*>(_memory) + sizeof(Header));
}
size_t SharedMemory::size() const {
#ifdef WIN32
return header(_memory)->size;
#else // ^^^^ WIN32 // !WIN32 vvvv
return _size;
#endif // WIN32
}
std::string SharedMemory::name() const {
return _name;
}
void SharedMemory::acquireLock() {
Header* h = header(_memory);
while (h->mutex.test_and_set()) {}
}
void SharedMemory::releaseLock() {
Header* h = header(_memory);
h->mutex.clear();
}
} // namespace ghoul
| 34.620209 | 90 | 0.580213 | OpenSpace |
c1c5de6bb615ca0dfdf7e1ee0a053e96a1ee39ed | 2,627 | cpp | C++ | morphdialog.cpp | emreozanalkan/VPOpenCVProject | 953fccdac9fa4c9793e3aeb0b97352ccabd28a64 | [
"MIT"
] | 1 | 2021-11-30T11:43:34.000Z | 2021-11-30T11:43:34.000Z | morphdialog.cpp | emreozanalkan/VPOpenCVProject | 953fccdac9fa4c9793e3aeb0b97352ccabd28a64 | [
"MIT"
] | null | null | null | morphdialog.cpp | emreozanalkan/VPOpenCVProject | 953fccdac9fa4c9793e3aeb0b97352ccabd28a64 | [
"MIT"
] | null | null | null | #include "morphdialog.h"
#include "ui_morphdialog.h"
#include "pch.h"
MorphDialog::MorphDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MorphDialog)
{
ui->setupUi(this);
}
MorphDialog::~MorphDialog()
{
delete ui;
}
void MorphDialog::on_buttonBox_accepted()
{
QString morphologicalOperation = ui->comboBoxMorphologicalOperation->currentText();
if(morphologicalOperation == "Dilation")
morphOperation = cv::MORPH_DILATE;
else if(morphologicalOperation == "Erosion")
morphOperation = cv::MORPH_ERODE;
else if(morphologicalOperation == "Opening")
morphOperation = cv::MORPH_OPEN;
else if(morphologicalOperation == "Closing")
morphOperation = cv::MORPH_CLOSE;
else if(morphologicalOperation == "Morphological Gradient")
morphOperation = cv::MORPH_GRADIENT;
else if(morphologicalOperation == "Top Hat")
morphOperation = cv::MORPH_TOPHAT;
else if(morphologicalOperation == "Black Hat")
morphOperation = cv::MORPH_BLACKHAT;
else
morphOperation = cv::MORPH_DILATE;
QString kernelTypeString = ui->comboBoxMorphologicalKernelType->currentText();
if(kernelTypeString == "Rectangle")
kernelType = cv::MORPH_RECT;
else if(kernelTypeString == "Cross")
kernelType = cv::MORPH_CROSS;
else if(kernelTypeString == "Ellipse")
kernelType = cv::MORPH_ELLIPSE;
else
kernelType = cv::MORPH_RECT;
QString imagePaddingMethodString = ui->comboBoxMorphologicalPaddingMethod->currentText();
if(imagePaddingMethodString == "Border Replicate - aaaaaa|abcdefgh|hhhhhhh") // Border Replicate - aaaaaa|abcdefgh|hhhhhhh
imagePaddingMethod = cv::BORDER_REPLICATE;
else if(imagePaddingMethodString == "Border Reflect - fedcba|abcdefgh|hgfedcb") // Border Reflect - fedcba|abcdefgh|hgfedcb
imagePaddingMethod = cv::BORDER_REFLECT;
else if(imagePaddingMethodString == "Border Reflect 101 - gfedcb|abcdefgh|gfedcba") // Border Reflect 101 - gfedcb|abcdefgh|gfedcba
imagePaddingMethod = cv::BORDER_REFLECT_101;
else if(imagePaddingMethodString == "Border Wrap - cdefgh|abcdefgh|abcdefg") // Border Wrap - cdefgh|abcdefgh|abcdefg
imagePaddingMethod = cv::BORDER_WRAP;
else
imagePaddingMethod = cv::BORDER_REPLICATE;
iterationCount = ui->spinBoxMorphologicalIterationCount->value();
int kSize = ui->spinBoxMorphologicalKernelSize->value();
kernelSize = new cv::Size(kSize, kSize);
anchorPoint = new cv::Point(ui->spinBoxMorphologicalKernelAnchorX->value(), ui->spinBoxMorphologicalKernelAnchorY->value());
}
| 39.80303 | 135 | 0.714884 | emreozanalkan |
c1c78d1f34346d9b979c3fa80ce828abe80aa0d1 | 1,733 | hpp | C++ | container/contiguous_storage_impl.hpp | birbacher/plaincontainers | 27386929da24b3d82887699458c99fc293618d05 | [
"BSL-1.0"
] | null | null | null | container/contiguous_storage_impl.hpp | birbacher/plaincontainers | 27386929da24b3d82887699458c99fc293618d05 | [
"BSL-1.0"
] | null | null | null | container/contiguous_storage_impl.hpp | birbacher/plaincontainers | 27386929da24b3d82887699458c99fc293618d05 | [
"BSL-1.0"
] | null | null | null | #ifndef NEWCONTAINER_CONTAINER_CONTIGUOUSSTORAGE_IMPL_INCLUDED
#define NEWCONTAINER_CONTAINER_CONTIGUOUSSTORAGE_IMPL_INCLUDED
#include "container/contiguous_storage.hpp"
#include "memory/interface/allocator.hpp"
#include "memory/adapter/typed_allocator.hpp"
#include <cassert>
#include <memory>
#include <utility>
namespace container {
template<typename ElemType, typename Allocator>
contiguous_storage<ElemType, Allocator>::contiguous_storage(
allocator_type& allocator_instance,
size_type const element_count
) noexcept
: allocator_adapter_instance(allocator_instance)
, storage(allocator_adapter_instance.allocate(element_count))
, capacity(element_count)
{
}
template<typename ElemType, typename Allocator>
contiguous_storage<ElemType, Allocator>::~contiguous_storage() noexcept
{
if(storage)
allocator_adapter_instance.deallocate(storage, capacity);
}
template<typename ElemType, typename Allocator>
contiguous_storage<ElemType, Allocator>::contiguous_storage(
contiguous_storage&& other
) noexcept
: contiguous_storage()
{
swap(other);
}
template<typename ElemType, typename Allocator>
auto contiguous_storage<ElemType, Allocator>::operator = (
contiguous_storage&& other
) noexcept
-> contiguous_storage&
{
contiguous_storage temp(std::move(other));
swap(temp);
return *this;
}
template<typename ElemType, typename Allocator>
void contiguous_storage<ElemType, Allocator>::swap(
contiguous_storage& other
) noexcept
{
using std::swap;
swap(storage, other.storage);
swap(capacity, other.capacity);
swap(allocator_adapter_instance, other.allocator_adapter_instance);
}
} //namespace container
#endif
| 26.661538 | 71 | 0.767455 | birbacher |
c1caebb9e7442b6d33149272bad939419cc88a4b | 9,640 | cpp | C++ | test_conformance/SVM/test_cross_buffer_pointers.cpp | jainvikas8/OpenCL-CTS | b7e7a3eb65d80d6847bd522f66f876fd5f6fe938 | [
"Apache-2.0"
] | 130 | 2017-05-16T14:15:25.000Z | 2022-03-26T22:31:05.000Z | test_conformance/SVM/test_cross_buffer_pointers.cpp | jainvikas8/OpenCL-CTS | b7e7a3eb65d80d6847bd522f66f876fd5f6fe938 | [
"Apache-2.0"
] | 919 | 2017-05-19T08:01:20.000Z | 2022-03-29T23:08:35.000Z | test_conformance/SVM/test_cross_buffer_pointers.cpp | jainvikas8/OpenCL-CTS | b7e7a3eb65d80d6847bd522f66f876fd5f6fe938 | [
"Apache-2.0"
] | 125 | 2017-05-17T01:14:15.000Z | 2022-03-25T22:34:42.000Z | //
// Copyright (c) 2017 The Khronos Group Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include "common.h"
// create linked lists that use nodes from two different buffers.
const char *SVMCrossBufferPointers_test_kernel[] = {
"\n"
"typedef struct Node {\n"
" int global_id;\n"
" int position_in_list;\n"
" __global struct Node* pNext;\n"
"} Node;\n"
"\n"
"__global Node* allocate_node(__global Node* pNodes1, __global Node* pNodes2, volatile __global int* allocation_index, size_t i)\n"
"{\n"
// mix things up, adjacent work items will allocate from different buffers
" if(i & 0x1)\n"
" return &pNodes1[atomic_inc(allocation_index)];\n"
" else\n"
" return &pNodes2[atomic_inc(allocation_index)];\n"
"}\n"
"\n"
// The allocation_index parameter must be initialized on the host to N work-items
// The first N nodes in pNodes will be the heads of the lists.
"__kernel void create_linked_lists(__global Node* pNodes, __global Node* pNodes2, volatile __global int* allocation_index, int list_length)\n"
"{\n"
" size_t i = get_global_id(0);\n"
" __global Node *pNode = &pNodes[i];\n"
"\n"
" pNode->global_id = i;\n"
" pNode->position_in_list = 0;\n"
"\n"
" __global Node *pNew;\n"
" for(int j=1; j < list_length; j++)\n"
" {\n"
" pNew = allocate_node(pNodes, pNodes2, allocation_index, i);\n"
" pNew->global_id = i;\n"
" pNew->position_in_list = j;\n"
" pNode->pNext = pNew; // link new node onto end of list\n"
" pNode = pNew; // move to end of list\n"
" }\n"
"}\n"
"\n"
"__kernel void verify_linked_lists(__global Node* pNodes, __global Node* pNodes2, volatile __global uint* num_correct, int list_length)\n"
"{\n"
" size_t i = get_global_id(0);\n"
" __global Node *pNode = &pNodes[i];\n"
"\n"
" for(int j=0; j < list_length; j++)\n"
" {\n"
" if( pNode->global_id == i && pNode->position_in_list == j)\n"
" {\n"
" atomic_inc(num_correct);\n"
" }\n"
" else {\n"
" break;\n"
" }\n"
" pNode = pNode->pNext;\n"
" }\n"
"}\n"
};
// Creates linked list using host code.
cl_int create_linked_lists_on_host(cl_command_queue cmdq, cl_mem nodes, cl_mem nodes2, cl_int ListLength, size_t numLists )
{
cl_int error = CL_SUCCESS;
log_info("SVM: creating linked list on host ");
Node *pNodes = (Node*) clEnqueueMapBuffer(cmdq, nodes, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(Node)*ListLength*numLists, 0, NULL,NULL, &error);
test_error2(error, pNodes, "clEnqueueMapBuffer failed");
Node *pNodes2 = (Node*) clEnqueueMapBuffer(cmdq, nodes2, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(Node)*ListLength*numLists, 0, NULL,NULL, &error);
test_error2(error, pNodes2, "clEnqueueMapBuffer failed");
create_linked_lists(pNodes, numLists, ListLength);
error = clEnqueueUnmapMemObject(cmdq, nodes, pNodes, 0,NULL,NULL);
test_error(error, "clEnqueueUnmapMemObject failed");
error = clEnqueueUnmapMemObject(cmdq, nodes2, pNodes2, 0,NULL,NULL);
test_error(error, "clEnqueueUnmapMemObject failed");
error = clFinish(cmdq);
test_error(error, "clFinish failed");
return error;
}
// Verify correctness of the linked list using host code.
cl_int verify_linked_lists_on_host(int ci, cl_command_queue cmdq, cl_mem nodes, cl_mem nodes2, cl_int ListLength, size_t numLists )
{
cl_int error = CL_SUCCESS;
//log_info(" and verifying on host ");
Node *pNodes = (Node*) clEnqueueMapBuffer(cmdq, nodes, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(Node)*ListLength * numLists, 0, NULL,NULL, &error);
test_error2(error, pNodes, "clEnqueueMapBuffer failed");
Node *pNodes2 = (Node*) clEnqueueMapBuffer(cmdq, nodes2, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, sizeof(Node)*ListLength * numLists, 0, NULL,NULL, &error);
test_error2(error, pNodes, "clEnqueueMapBuffer failed");
error = verify_linked_lists(pNodes, numLists, ListLength);
if(error) return -1;
error = clEnqueueUnmapMemObject(cmdq, nodes, pNodes, 0,NULL,NULL);
test_error(error, "clEnqueueUnmapMemObject failed");
error = clEnqueueUnmapMemObject(cmdq, nodes2, pNodes2, 0,NULL,NULL);
test_error(error, "clEnqueueUnmapMemObject failed");
error = clFinish(cmdq);
test_error(error, "clFinish failed");
return error;
}
// This tests that shared buffers are able to contain pointers that point to other shared buffers.
// This tests that all devices and the host share a common address space; using only the coarse-grain features.
// This is done by creating a linked list on a device and then verifying the correctness of the list
// on another device or the host.
// The linked list nodes are allocated from two different buffers this is done to ensure that cross buffer pointers work correctly.
// This basic test is performed for all combinations of devices and the host.
int test_svm_cross_buffer_pointers_coarse_grain(cl_device_id deviceID, cl_context context2, cl_command_queue queue, int num_elements)
{
clContextWrapper context = NULL;
clProgramWrapper program = NULL;
cl_uint num_devices = 0;
cl_int error = CL_SUCCESS;
clCommandQueueWrapper queues[MAXQ];
error = create_cl_objects(deviceID, &SVMCrossBufferPointers_test_kernel[0], &context, &program, &queues[0], &num_devices, CL_DEVICE_SVM_COARSE_GRAIN_BUFFER);
if(error) return -1;
size_t numLists = num_elements;
cl_int ListLength = 32;
clKernelWrapper kernel_create_lists = clCreateKernel(program, "create_linked_lists", &error);
test_error(error, "clCreateKernel failed");
clKernelWrapper kernel_verify_lists = clCreateKernel(program, "verify_linked_lists", &error);
test_error(error, "clCreateKernel failed");
// this buffer holds some of the linked list nodes.
Node* pNodes = (Node*) clSVMAlloc(context, CL_MEM_READ_WRITE, sizeof(Node)*ListLength*numLists, 0);
// this buffer holds some of the linked list nodes.
Node* pNodes2 = (Node*) clSVMAlloc(context, CL_MEM_READ_WRITE, sizeof(Node)*ListLength*numLists, 0);
{
clMemWrapper nodes = clCreateBuffer(context, CL_MEM_USE_HOST_PTR, sizeof(Node)*ListLength*numLists, pNodes, &error);
test_error(error, "clCreateBuffer failed.");
clMemWrapper nodes2 = clCreateBuffer(context, CL_MEM_USE_HOST_PTR, sizeof(Node)*ListLength*numLists, pNodes2, &error);
test_error(error, "clCreateBuffer failed.");
// this buffer holds the index into the nodes buffer that is used for node allocation
clMemWrapper allocator = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_int), NULL, &error);
test_error(error, "clCreateBuffer failed.");
// this buffer holds the count of correct nodes which is computed by the verify kernel.
clMemWrapper num_correct = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(cl_int), NULL, &error);
test_error(error, "clCreateBuffer failed.");
error |= clSetKernelArg(kernel_create_lists, 0, sizeof(void*), (void *) &nodes);
//error |= clSetKernelArgSVMPointer(kernel_create_lists, 0, (void *) pNodes);
error |= clSetKernelArg(kernel_create_lists, 1, sizeof(void*), (void *) &nodes2);
error |= clSetKernelArg(kernel_create_lists, 2, sizeof(void*), (void *) &allocator);
error |= clSetKernelArg(kernel_create_lists, 3, sizeof(cl_int), (void *) &ListLength);
error |= clSetKernelArg(kernel_verify_lists, 0, sizeof(void*), (void *) &nodes);
error |= clSetKernelArg(kernel_verify_lists, 1, sizeof(void*), (void *) &nodes2);
error |= clSetKernelArg(kernel_verify_lists, 2, sizeof(void*), (void *) &num_correct);
error |= clSetKernelArg(kernel_verify_lists, 3, sizeof(cl_int), (void *) &ListLength);
test_error(error, "clSetKernelArg failed");
// Create linked list on one device and verify on another device (or the host).
// Do this for all possible combinations of devices and host within the platform.
for (int ci=0; ci<(int)num_devices+1; ci++) // ci is CreationIndex, index of device/q to create linked list on
{
for (int vi=0; vi<(int)num_devices+1; vi++) // vi is VerificationIndex, index of device/q to verify linked list on
{
if(ci == num_devices) // last device index represents the host, note the num_device+1 above.
{
error = create_linked_lists_on_host(queues[0], nodes, nodes2, ListLength, numLists);
if(error) return -1;
}
else
{
error = create_linked_lists_on_device(ci, queues[ci], allocator, kernel_create_lists, numLists);
if(error) return -1;
}
if(vi == num_devices)
{
error = verify_linked_lists_on_host(vi, queues[0], nodes, nodes2, ListLength, numLists);
if(error) return -1;
}
else
{
error = verify_linked_lists_on_device(vi, queues[vi], num_correct, kernel_verify_lists, ListLength, numLists);
if(error) return -1;
}
} // inner loop, vi
} // outer loop, ci
}
clSVMFree(context, pNodes2);
clSVMFree(context, pNodes);
return 0;
}
| 43.818182 | 159 | 0.695747 | jainvikas8 |
c1cba5e3548121de6d7a0cbe39a36f7beb25fe6b | 13,348 | cpp | C++ | flatland_server/src/debug_visualization.cpp | schmiddey/flatland | 7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb | [
"BSD-3-Clause"
] | null | null | null | flatland_server/src/debug_visualization.cpp | schmiddey/flatland | 7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb | [
"BSD-3-Clause"
] | null | null | null | flatland_server/src/debug_visualization.cpp | schmiddey/flatland | 7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb | [
"BSD-3-Clause"
] | null | null | null | /*
* ______ __ __ __
* /\ _ \ __ /\ \/\ \ /\ \__
* \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____
* \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\
* \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\
* \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/
* \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/
* @copyright Copyright 2017 Avidbots Corp.
* @name debug_visualization.cpp
* @brief Transform box2d types into published visualization messages
* @author Joseph Duchesne
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2017, Avidbots Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Avidbots Corp. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "flatland_server/debug_visualization.h"
#include <Box2D/Box2D.h>
#include <rclcpp/rclcpp.hpp>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2/convert.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <map>
#include <string>
namespace flatland_server {
DebugVisualization::DebugVisualization(rclcpp::Node::SharedPtr node) : node_(node) {
topic_list_publisher_ =
node_->create_publisher<flatland_msgs::msg::DebugTopicList>("topics", 1);
}
std::shared_ptr<DebugVisualization> DebugVisualization::Get(rclcpp::Node::SharedPtr node) {
static std::shared_ptr<DebugVisualization> instance;
// todo: fix this? How should singletons work with shared pointers?
if (!instance) {
instance = std::make_shared<DebugVisualization>(node);
}
return instance;
}
void DebugVisualization::JointToMarkers(
visualization_msgs::msg::MarkerArray& markers, b2Joint* joint, float r, float g,
float b, float a) {
if (joint->GetType() == e_distanceJoint ||
joint->GetType() == e_pulleyJoint || joint->GetType() == e_mouseJoint) {
RCLCPP_ERROR(rclcpp::get_logger("DebugVis"),
"Unimplemented visualization joints. See b2World.cpp for "
"implementation");
return;
}
visualization_msgs::msg::Marker marker;
marker.header.frame_id = "map";
marker.color.r = r;
marker.color.g = g;
marker.color.b = b;
marker.color.a = a;
marker.type = marker.LINE_LIST;
marker.scale.x = 0.01;
geometry_msgs::msg::Point p_a1, p_a2, p_b1, p_b2;
p_a1.x = joint->GetAnchorA().x;
p_a1.y = joint->GetAnchorA().y;
p_a2.x = joint->GetAnchorB().x;
p_a2.y = joint->GetAnchorB().y;
p_b1.x = joint->GetBodyA()->GetPosition().x;
p_b1.y = joint->GetBodyA()->GetPosition().y;
p_b2.x = joint->GetBodyB()->GetPosition().x;
p_b2.y = joint->GetBodyB()->GetPosition().y;
// Visualization shows lines from bodyA to anchorA, bodyB to anchorB, and
// anchorA to anchorB
marker.id = markers.markers.size();
marker.points.push_back(p_b1);
marker.points.push_back(p_a1);
marker.points.push_back(p_b2);
marker.points.push_back(p_a2);
marker.points.push_back(p_a1);
marker.points.push_back(p_a2);
markers.markers.push_back(marker);
marker.id = markers.markers.size();
marker.type = marker.CUBE_LIST;
marker.scale.x = marker.scale.y = marker.scale.z = 0.03;
marker.points.clear();
marker.points.push_back(p_a1);
marker.points.push_back(p_a2);
marker.points.push_back(p_b1);
marker.points.push_back(p_b2);
markers.markers.push_back(marker);
}
void DebugVisualization::BodyToMarkers(visualization_msgs::msg::MarkerArray& markers,
b2Body* body, float r, float g, float b,
float a) {
b2Fixture* fixture = body->GetFixtureList();
while (fixture != NULL) { // traverse fixture linked list
visualization_msgs::msg::Marker marker;
marker.header.frame_id = "map";
marker.id = markers.markers.size();
marker.color.r = r;
marker.color.g = g;
marker.color.b = b;
marker.color.a = a;
marker.pose.position.x = body->GetPosition().x;
marker.pose.position.y = body->GetPosition().y;
tf2::Quaternion q; // use tf2 to convert 2d yaw -> 3d quaternion
q.setRPY(0, 0, body->GetAngle()); // from euler angles: roll, pitch, yaw
marker.pose.orientation = tf2::toMsg(q);
bool add_marker = true;
// Get the shape from the fixture
switch (fixture->GetType()) {
case b2Shape::e_circle: {
b2CircleShape* circle = (b2CircleShape*)fixture->GetShape();
marker.type = marker.SPHERE_LIST;
float diameter = circle->m_radius * 2.0;
marker.scale.z = 0.01;
marker.scale.x = diameter;
marker.scale.y = diameter;
geometry_msgs::msg::Point p;
p.x = circle->m_p.x;
p.y = circle->m_p.y;
marker.points.push_back(p);
} break;
case b2Shape::e_polygon: { // Convert b2Polygon -> LINE_STRIP
b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape();
marker.type = marker.LINE_STRIP;
marker.scale.x = 0.03; // 3cm wide lines
for (int i = 0; i < poly->m_count; i++) {
geometry_msgs::msg::Point p;
p.x = poly->m_vertices[i].x;
p.y = poly->m_vertices[i].y;
marker.points.push_back(p);
}
marker.points.push_back(marker.points[0]); // Close the shape
} break;
case b2Shape::e_edge: { // Convert b2Edge -> LINE_LIST
geometry_msgs::msg::Point p; // b2Edge uses vertex1 and 2 for its edges
b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
// If the last marker is a line list, extend it
if (markers.markers.size() > 0 &&
markers.markers.back().type == marker.LINE_LIST) {
add_marker = false;
p.x = edge->m_vertex1.x;
p.y = edge->m_vertex1.y;
markers.markers.back().points.push_back(p);
p.x = edge->m_vertex2.x;
p.y = edge->m_vertex2.y;
markers.markers.back().points.push_back(p);
} else { // otherwise create a new line list
marker.type = marker.LINE_LIST;
marker.scale.x = 0.03; // 3cm wide lines
p.x = edge->m_vertex1.x;
p.y = edge->m_vertex1.y;
marker.points.push_back(p);
p.x = edge->m_vertex2.x;
p.y = edge->m_vertex2.y;
marker.points.push_back(p);
}
} break;
default: // Unsupported shape
rclcpp::Clock steady_clock = rclcpp::Clock(RCL_STEADY_TIME);
RCLCPP_WARN_THROTTLE(rclcpp::get_logger("Debug Visualization"), steady_clock, 1000, "Unsupported Box2D shape %d",
static_cast<int>(fixture->GetType()));
fixture = fixture->GetNext();
continue; // Do not add broken marker
break;
}
if (add_marker) {
markers.markers.push_back(marker); // Add the new marker
}
fixture = fixture->GetNext(); // Traverse the linked list of fixtures
}
}
void DebugVisualization::Publish(const Timekeeper& timekeeper) {
// Iterate over the topics_ map as pair(name, topic)
std::vector<std::string> to_delete;
for (auto& topic : topics_) {
if (!topic.second.needs_publishing) {
continue;
}
// since if empty markers are published rviz will continue to publish
// using the old data, delete the topic list
if (topic.second.markers.markers.size() == 0) {
to_delete.push_back(topic.first);
} else {
// Iterate the marker array to update all the timestamps
for (unsigned int i = 0; i < topic.second.markers.markers.size(); i++) {
topic.second.markers.markers[i].header.stamp = timekeeper.GetSimTime();
}
topic.second.publisher->publish(topic.second.markers);
topic.second.needs_publishing = false;
}
}
if (to_delete.size() > 0) {
for (const auto& topic : to_delete) {
RCLCPP_WARN(rclcpp::get_logger("DebugVis"), "Deleting topic %s", topic.c_str());
topics_.erase(topic);
}
PublishTopicList();
}
}
void DebugVisualization::VisualizeLayer(std::string name, Body* body) {
AddTopicIfNotExist(name);
b2Fixture* fixture = body->physics_body_->GetFixtureList();
visualization_msgs::msg::Marker marker;
if (fixture == NULL) return; // Nothing to visualize, empty linked list
while (fixture != NULL) { // traverse fixture linked list
marker.header.frame_id = "map";
marker.id = topics_[name].markers.markers.size();
marker.color.r = body->color_.r;
marker.color.g = body->color_.g;
marker.color.b = body->color_.b;
marker.color.a = body->color_.a;
marker.scale.x = marker.scale.y = marker.scale.z = 1.0;
marker.frame_locked = true;
marker.pose.position.x = body->physics_body_->GetPosition().x;
marker.pose.position.y = body->physics_body_->GetPosition().y;
tf2::Quaternion q; // use tf2 to convert 2d yaw -> 3d quaternion
q.setRPY(0, 0, body->physics_body_
->GetAngle()); // from euler angles: roll, pitch, yaw
marker.pose.orientation = tf2::toMsg(q);
marker.type = marker.TRIANGLE_LIST;
YamlReader reader(node_, body->properties_);
YamlReader debug_reader =
reader.SubnodeOpt("debug", YamlReader::NodeTypeCheck::MAP);
float min_z = debug_reader.Get<float>("min_z", 0.0);
float max_z = debug_reader.Get<float>("max_z", 1.0);
// Get the shape from the fixture
if (fixture->GetType() == b2Shape::e_edge) {
geometry_msgs::msg::Point p; // b2Edge uses vertex1 and 2 for its edges
b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape();
p.x = edge->m_vertex1.x;
p.y = edge->m_vertex1.y;
p.z = min_z;
marker.points.push_back(p);
p.x = edge->m_vertex2.x;
p.y = edge->m_vertex2.y;
p.z = min_z;
marker.points.push_back(p);
p.x = edge->m_vertex2.x;
p.y = edge->m_vertex2.y;
p.z = max_z;
marker.points.push_back(p);
p.x = edge->m_vertex1.x;
p.y = edge->m_vertex1.y;
p.z = min_z;
marker.points.push_back(p);
p.x = edge->m_vertex2.x;
p.y = edge->m_vertex2.y;
p.z = max_z;
marker.points.push_back(p);
p.x = edge->m_vertex1.x;
p.y = edge->m_vertex1.y;
p.z = max_z;
marker.points.push_back(p);
}
fixture = fixture->GetNext(); // Traverse the linked list of fixtures
}
topics_[name].markers.markers.push_back(marker); // Add the new marker
topics_[name].needs_publishing = true;
}
void DebugVisualization::Visualize(std::string name, b2Body* body, float r,
float g, float b, float a) {
AddTopicIfNotExist(name);
BodyToMarkers(topics_[name].markers, body, r, g, b, a);
topics_[name].needs_publishing = true;
}
void DebugVisualization::Visualize(std::string name, b2Joint* joint, float r,
float g, float b, float a) {
AddTopicIfNotExist(name);
JointToMarkers(topics_[name].markers, joint, r, g, b, a);
topics_[name].needs_publishing = true;
}
void DebugVisualization::Reset(std::string name) {
if (topics_.count(name) > 0) { // If the topic exists, clear it
topics_[name].markers.markers.clear();
topics_[name].needs_publishing = true;
}
}
void DebugVisualization::AddTopicIfNotExist(const std::string& name) {
// If the topic doesn't exist yet, create it
if (topics_.count(name) == 0) {
topics_[name] = {
node_->create_publisher<visualization_msgs::msg::MarkerArray>(name, 1), true,
visualization_msgs::msg::MarkerArray()};
RCLCPP_INFO_ONCE(rclcpp::get_logger("Debug Visualization"), "Visualizing %s", name.c_str());
PublishTopicList();
}
}
void DebugVisualization::PublishTopicList() {
flatland_msgs::msg::DebugTopicList topic_list;
for (auto const& topic_pair : topics_)
topic_list.topics.push_back(topic_pair.first);
topic_list_publisher_->publish(topic_list);
}
} //namespace flatland_server
| 36.173442 | 121 | 0.641744 | schmiddey |
c1cd25572d1bd1f2e3eeef5280aa22a2722479d7 | 12,144 | cpp | C++ | src/coreclr/jit/likelyclass.cpp | JimmyCushnie/runtime | b7eb82871f1d742efb444873e11dd6241cea73d2 | [
"MIT"
] | 3 | 2021-06-24T15:39:52.000Z | 2021-11-04T02:13:43.000Z | src/coreclr/jit/likelyclass.cpp | JimmyCushnie/runtime | b7eb82871f1d742efb444873e11dd6241cea73d2 | [
"MIT"
] | 18 | 2019-12-03T00:21:59.000Z | 2022-01-30T04:45:58.000Z | src/coreclr/jit/likelyclass.cpp | JimmyCushnie/runtime | b7eb82871f1d742efb444873e11dd6241cea73d2 | [
"MIT"
] | 2 | 2022-03-05T21:34:42.000Z | 2022-03-10T15:17:42.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Likely Class Processing XX
XX XX
XX Parses Pgo data to find the most likely class in use at a given XX
XX IL offset in a method. Used by both the JIT, and by crossgen XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef DLLEXPORT
#define DLLEXPORT
#endif // !DLLEXPORT
// Data item in class profile histogram
//
struct LikelyClassHistogramEntry
{
// Class that was observed at runtime
INT_PTR m_mt; // This may be an "unknown type handle"
// Number of observations in the table
unsigned m_count;
};
// Summarizes a ClassProfile table by forming a Histogram
//
struct LikelyClassHistogram
{
LikelyClassHistogram(INT_PTR* histogramEntries, unsigned entryCount);
// Sum of counts from all entries in the histogram. This includes "unknown" entries which are not captured in
// m_histogram
unsigned m_totalCount;
// Rough guess at count of unknown types
unsigned m_unknownTypes;
// Histogram entries, in no particular order.
LikelyClassHistogramEntry m_histogram[64];
UINT32 countHistogramElements = 0;
LikelyClassHistogramEntry HistogramEntryAt(unsigned index)
{
return m_histogram[index];
}
};
//------------------------------------------------------------------------
// LikelyClassHistogram::LikelyClassHistgram: construct a new histogram
//
// Arguments:
// histogramEntries - pointer to the table portion of a ClassProfile* object (see corjit.h)
// entryCount - number of entries in the table to examine
//
LikelyClassHistogram::LikelyClassHistogram(INT_PTR* histogramEntries, unsigned entryCount)
{
m_unknownTypes = 0;
m_totalCount = 0;
uint32_t unknownTypeHandleMask = 0;
for (unsigned k = 0; k < entryCount; k++)
{
if (histogramEntries[k] == 0)
{
continue;
}
m_totalCount++;
INT_PTR currentEntry = histogramEntries[k];
bool found = false;
unsigned h = 0;
for (; h < countHistogramElements; h++)
{
if (m_histogram[h].m_mt == currentEntry)
{
m_histogram[h].m_count++;
found = true;
break;
}
}
if (!found)
{
if (countHistogramElements >= _countof(m_histogram))
{
continue;
}
LikelyClassHistogramEntry newEntry;
newEntry.m_mt = currentEntry;
newEntry.m_count = 1;
m_histogram[countHistogramElements++] = newEntry;
}
}
}
//------------------------------------------------------------------------
// getLikelyClass: find class profile data for an IL offset, and return the most likely class
//
// Arguments:
// schema - profile schema
// countSchemaItems - number of items in the schema
// pInstrumentationData - associated data
// ilOffset - il offset of the callvirt
// pLikelihood - [OUT] likelihood of observing that entry [0...100]
// pNumberOfClasses - [OUT] estimated number of classes seen at runtime
//
// Returns:
// Class handle for the most likely class, or nullptr
//
// Notes:
// A "monomorphic" call site will return likelihood 100 and number of entries = 1.
//
// This is used by the devirtualization logic below, and by crossgen2 when producing
// the R2R image (to reduce the sizecost of carrying the type histogram)
//
// This code can runs without a jit instance present, so JITDUMP and related
// cannot be used.
//
extern "C" DLLEXPORT CORINFO_CLASS_HANDLE WINAPI getLikelyClass(ICorJitInfo::PgoInstrumentationSchema* schema,
UINT32 countSchemaItems,
BYTE* pInstrumentationData,
int32_t ilOffset,
UINT32* pLikelihood,
UINT32* pNumberOfClasses)
{
*pLikelihood = 0;
*pNumberOfClasses = 0;
if (schema == NULL)
return NULL;
for (COUNT_T i = 0; i < countSchemaItems; i++)
{
if (schema[i].ILOffset != (int32_t)ilOffset)
continue;
if ((schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::GetLikelyClass) &&
(schema[i].Count == 1))
{
*pNumberOfClasses = (UINT32)schema[i].Other >> 8;
*pLikelihood = (UINT32)(schema[i].Other & 0xFF);
INT_PTR result = *(INT_PTR*)(pInstrumentationData + schema[i].Offset);
if (ICorJitInfo::IsUnknownTypeHandle(result))
return NULL;
else
return (CORINFO_CLASS_HANDLE)result;
}
bool isHistogramCount =
(schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramIntCount) ||
(schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramLongCount);
if (isHistogramCount && (schema[i].Count == 1) && ((i + 1) < countSchemaItems) &&
(schema[i + 1].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramTypeHandle))
{
// Form a histogram
//
LikelyClassHistogram h((INT_PTR*)(pInstrumentationData + schema[i + 1].Offset), schema[i + 1].Count);
// Use histogram count as number of classes estimate
//
*pNumberOfClasses = (uint32_t)h.countHistogramElements + h.m_unknownTypes;
// Report back what we've learned
// (perhaps, use count to augment likelihood?)
//
switch (*pNumberOfClasses)
{
case 0:
{
return NULL;
}
break;
case 1:
{
if (ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(0).m_mt))
{
return NULL;
}
*pLikelihood = 100;
return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(0).m_mt;
}
break;
case 2:
{
if ((h.HistogramEntryAt(0).m_count >= h.HistogramEntryAt(1).m_count) &&
!ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(0).m_mt))
{
*pLikelihood = (100 * h.HistogramEntryAt(0).m_count) / h.m_totalCount;
return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(0).m_mt;
}
else if (!ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(1).m_mt))
{
*pLikelihood = (100 * h.HistogramEntryAt(1).m_count) / h.m_totalCount;
return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(1).m_mt;
}
else
{
return NULL;
}
}
break;
default:
{
// Find maximum entry and return it
//
unsigned maxKnownIndex = 0;
unsigned maxKnownCount = 0;
for (unsigned m = 0; m < h.countHistogramElements; m++)
{
if ((h.HistogramEntryAt(m).m_count > maxKnownCount) &&
!ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(m).m_mt))
{
maxKnownIndex = m;
maxKnownCount = h.HistogramEntryAt(m).m_count;
}
}
if (maxKnownCount > 0)
{
*pLikelihood = (100 * maxKnownCount) / h.m_totalCount;
return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(maxKnownIndex).m_mt;
}
return NULL;
}
break;
}
}
}
// Failed to find histogram data for this method
//
return NULL;
}
//------------------------------------------------------------------------
// getRandomClass: find class profile data for an IL offset, and return
// one of the possible classes at random
//
// Arguments:
// schema - profile schema
// countSchemaItems - number of items in the schema
// pInstrumentationData - associated data
// ilOffset - il offset of the callvirt
// random - randomness generator
//
// Returns:
// Randomly observed class, or nullptr.
//
CORINFO_CLASS_HANDLE Compiler::getRandomClass(ICorJitInfo::PgoInstrumentationSchema* schema,
UINT32 countSchemaItems,
BYTE* pInstrumentationData,
int32_t ilOffset,
CLRRandom* random)
{
if (schema == nullptr)
{
return NO_CLASS_HANDLE;
}
for (COUNT_T i = 0; i < countSchemaItems; i++)
{
if (schema[i].ILOffset != (int32_t)ilOffset)
{
continue;
}
if ((schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::GetLikelyClass) &&
(schema[i].Count == 1))
{
INT_PTR result = *(INT_PTR*)(pInstrumentationData + schema[i].Offset);
if (ICorJitInfo::IsUnknownTypeHandle(result))
{
return NO_CLASS_HANDLE;
}
else
{
return (CORINFO_CLASS_HANDLE)result;
}
}
bool isHistogramCount =
(schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramIntCount) ||
(schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramLongCount);
if (isHistogramCount && (schema[i].Count == 1) && ((i + 1) < countSchemaItems) &&
(schema[i + 1].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramTypeHandle))
{
// Form a histogram
//
LikelyClassHistogram h((INT_PTR*)(pInstrumentationData + schema[i + 1].Offset), schema[i + 1].Count);
if (h.countHistogramElements == 0)
{
return NO_CLASS_HANDLE;
}
// Choose an entry at random.
//
unsigned randomEntryIndex = random->Next(0, h.countHistogramElements - 1);
LikelyClassHistogramEntry randomEntry = h.HistogramEntryAt(randomEntryIndex);
if (ICorJitInfo::IsUnknownTypeHandle(randomEntry.m_mt))
{
return NO_CLASS_HANDLE;
}
return (CORINFO_CLASS_HANDLE)randomEntry.m_mt;
}
}
return NO_CLASS_HANDLE;
}
| 36.911854 | 120 | 0.523798 | JimmyCushnie |
c1cd7ca6031e50ca4a041303f4cf8898726f2ed3 | 1,735 | cpp | C++ | functions/func.cpp | lucienmakutano/learn-cpp | de78caba34295938462b229a8669feaf401b3dbe | [
"MIT"
] | null | null | null | functions/func.cpp | lucienmakutano/learn-cpp | de78caba34295938462b229a8669feaf401b3dbe | [
"MIT"
] | null | null | null | functions/func.cpp | lucienmakutano/learn-cpp | de78caba34295938462b229a8669feaf401b3dbe | [
"MIT"
] | null | null | null | #include "func.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void print_vector(vector<string> v);
void print_vector(vector<int> v = {1, 2, 3, 4, 5});
void print_array(int arr[], size_t size); // mutable
void print_array(const int arr[], size_t size); // immutable
void pass_by_ref(int &num); // mutable
void pass_by_const_ref(const int &num); // immutable
void swap(int &a, int &b);
void scopes();
void print_vector(vector<string> v)
{
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
}
// function overloading + default arguments
void print_vector(vector<int> v)
{
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
}
// In this case the function can modify the array elements
void print_array(int arr[], size_t size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << endl;
arr[i] = i;
}
}
// To protect ourselves from modifying the array elements,
// we can use `const` to make the array a read-only array
void print_array(const int arr[], size_t size)
{
for (int i = 0; i < size; i++)
{
cout << arr[i] << endl;
}
}
void pass_by_ref(int &num)
{
num = num + 1;
}
void pass_by_const_ref(const int &num) // immutable
{
// num = num + 1; // error
cout << num << endl;
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void scopes()
{
int a = 10;
{
int a = 20;
cout << a << endl; // 20
}
cout << a << endl; // 10
}
void func_work()
{
vector<string> v;
v.push_back("Hello");
v.push_back("World");
v.push_back("!");
print_vector(v);
print_vector();
}
| 18.263158 | 60 | 0.55562 | lucienmakutano |
c1cf093e7a3067bf1522ffa59ba9b94aa1a8b52e | 4,233 | cc | C++ | chrome/browser/ui/ash/assistant/assistant_image_downloader.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/ui/ash/assistant/assistant_image_downloader.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/ui/ash/assistant/assistant_image_downloader.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/ash/assistant/assistant_image_downloader.h"
#include "ash/public/interfaces/assistant_controller.mojom.h"
#include "ash/public/interfaces/constants.mojom.h"
#include "chrome/browser/bitmap_fetcher/bitmap_fetcher.h"
#include "chrome/browser/bitmap_fetcher/bitmap_fetcher_delegate.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "content/public/browser/storage_partition.h"
#include "net/base/load_flags.h"
#include "services/service_manager/public/cpp/connector.h"
namespace {
constexpr net::NetworkTrafficAnnotationTag kNetworkTrafficAnnotationTag =
net::DefineNetworkTrafficAnnotation("assistant_image_downloader", R"(
"semantics: {
sender: "Google Assistant"
description:
"The Google Assistant requires dynamic loading of images to "
"provide a media rich user experience. Images are downloaded on "
"an as needed basis."
trigger:
"Generally triggered in direct response to a user issued query. "
"A single query may necessitate the downloading of multiple "
"images."
destination: GOOGLE_OWNED_SERVICE
}
"policy": {
cookies_allowed: NO
setting:
"The Google Assistant can be enabled/disabled in Chrome Settings "
"and is subject to eligibility requirements."
})");
// DownloadTask ----------------------------------------------------------------
class DownloadTask : public BitmapFetcherDelegate {
public:
DownloadTask(Profile* profile,
const GURL& url,
ash::mojom::AssistantImageDownloader::DownloadCallback callback)
: callback_(std::move(callback)) {
StartTask(profile, url);
}
~DownloadTask() override = default;
// BitmapFetcherDelegate:
void OnFetchComplete(const GURL& url, const SkBitmap* bitmap) override {
std::move(callback_).Run(bitmap
? gfx::ImageSkia::CreateFrom1xBitmap(*bitmap)
: gfx::ImageSkia());
delete this;
}
private:
void StartTask(Profile* profile, const GURL& url) {
bitmap_fetcher_ = std::make_unique<BitmapFetcher>(
url, this, kNetworkTrafficAnnotationTag);
bitmap_fetcher_->Init(
/*referrer=*/std::string(), net::URLRequest::NEVER_CLEAR_REFERRER,
net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES |
net::LOAD_DO_NOT_SEND_AUTH_DATA | net::LOAD_MAYBE_USER_GESTURE);
bitmap_fetcher_->Start(
content::BrowserContext::GetDefaultStoragePartition(profile)
->GetURLLoaderFactoryForBrowserProcess()
.get());
}
ash::mojom::AssistantImageDownloader::DownloadCallback callback_;
std::unique_ptr<BitmapFetcher> bitmap_fetcher_;
DISALLOW_COPY_AND_ASSIGN(DownloadTask);
};
} // namespace
// AssistantImageDownloader ----------------------------------------------------
AssistantImageDownloader::AssistantImageDownloader(
service_manager::Connector* connector)
: binding_(this) {
// Bind to the Assistant controller in ash.
ash::mojom::AssistantControllerPtr assistant_controller;
connector->BindInterface(ash::mojom::kServiceName, &assistant_controller);
ash::mojom::AssistantImageDownloaderPtr ptr;
binding_.Bind(mojo::MakeRequest(&ptr));
assistant_controller->SetAssistantImageDownloader(std::move(ptr));
}
AssistantImageDownloader::~AssistantImageDownloader() = default;
void AssistantImageDownloader::Download(
const AccountId& account_id,
const GURL& url,
ash::mojom::AssistantImageDownloader::DownloadCallback callback) {
Profile* profile =
chromeos::ProfileHelper::Get()->GetProfileByAccountId(account_id);
if (!profile) {
LOG(WARNING) << "Unable to retrieve profile for account_id.";
std::move(callback).Run(gfx::ImageSkia());
return;
}
// The download task will delete itself upon task completion.
new DownloadTask(profile, url, std::move(callback));
}
| 36.808696 | 80 | 0.680605 | zipated |
c1d2d453c9226130da137be752450c95480cdc81 | 14,675 | cpp | C++ | src/dawn/tests/unittests/wire/WireAdapterTests.cpp | Antidote/dawn-cmake | b8c6d669fa3c0087aa86653a4078386ffb42f199 | [
"BSD-3-Clause"
] | 1 | 2021-12-06T14:21:54.000Z | 2021-12-06T14:21:54.000Z | src/dawn/tests/unittests/wire/WireAdapterTests.cpp | AartOdding/dawn | f2556ab35c0eecdfd93c02f7c226a5c94316d143 | [
"BSD-3-Clause"
] | null | null | null | src/dawn/tests/unittests/wire/WireAdapterTests.cpp | AartOdding/dawn | f2556ab35c0eecdfd93c02f7c226a5c94316d143 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Dawn 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 "dawn/tests/MockCallback.h"
#include "dawn/tests/unittests/wire/WireTest.h"
#include "dawn/wire/WireClient.h"
#include "dawn/wire/WireServer.h"
#include <webgpu/webgpu_cpp.h>
#include <unordered_set>
#include <vector>
namespace {
using namespace testing;
using namespace dawn::wire;
class WireAdapterTests : public WireTest {
protected:
// Bootstrap the tests and create a fake adapter.
void SetUp() override {
WireTest::SetUp();
auto reservation = GetWireClient()->ReserveInstance();
instance = wgpu::Instance::Acquire(reservation.instance);
WGPUInstance apiInstance = api.GetNewInstance();
EXPECT_CALL(api, InstanceReference(apiInstance));
EXPECT_TRUE(GetWireServer()->InjectInstance(apiInstance, reservation.id,
reservation.generation));
wgpu::RequestAdapterOptions options = {};
MockCallback<WGPURequestAdapterCallback> cb;
auto* userdata = cb.MakeUserdata(this);
instance.RequestAdapter(&options, cb.Callback(), userdata);
// Expect the server to receive the message. Then, mock a fake reply.
apiAdapter = api.GetNewAdapter();
EXPECT_CALL(api, OnInstanceRequestAdapter(apiInstance, NotNull(), NotNull(), NotNull()))
.WillOnce(InvokeWithoutArgs([&]() {
EXPECT_CALL(api, AdapterGetProperties(apiAdapter, NotNull()))
.WillOnce(WithArg<1>(Invoke([&](WGPUAdapterProperties* properties) {
*properties = {};
properties->name = "";
properties->driverDescription = "";
})));
EXPECT_CALL(api, AdapterGetLimits(apiAdapter, NotNull()))
.WillOnce(WithArg<1>(Invoke([&](WGPUSupportedLimits* limits) {
*limits = {};
return true;
})));
EXPECT_CALL(api, AdapterEnumerateFeatures(apiAdapter, nullptr))
.WillOnce(Return(0))
.WillOnce(Return(0));
api.CallInstanceRequestAdapterCallback(
apiInstance, WGPURequestAdapterStatus_Success, apiAdapter, nullptr);
}));
FlushClient();
// Expect the callback in the client.
WGPUAdapter cAdapter;
EXPECT_CALL(cb, Call(WGPURequestAdapterStatus_Success, NotNull(), nullptr, this))
.WillOnce(SaveArg<1>(&cAdapter));
FlushServer();
EXPECT_NE(cAdapter, nullptr);
adapter = wgpu::Adapter::Acquire(cAdapter);
}
void TearDown() override {
adapter = nullptr;
instance = nullptr;
WireTest::TearDown();
}
WGPUAdapter apiAdapter;
wgpu::Instance instance;
wgpu::Adapter adapter;
};
// Test that the DeviceDescriptor is passed from the client to the server.
TEST_F(WireAdapterTests, RequestDevicePassesDescriptor) {
MockCallback<WGPURequestDeviceCallback> cb;
auto* userdata = cb.MakeUserdata(this);
// Test an empty descriptor
{
wgpu::DeviceDescriptor desc = {};
adapter.RequestDevice(&desc, cb.Callback(), userdata);
EXPECT_CALL(api, OnAdapterRequestDevice(apiAdapter, NotNull(), NotNull(), NotNull()))
.WillOnce(WithArg<1>(Invoke([](const WGPUDeviceDescriptor* apiDesc) {
EXPECT_EQ(apiDesc->label, nullptr);
EXPECT_EQ(apiDesc->requiredFeaturesCount, 0u);
EXPECT_EQ(apiDesc->requiredLimits, nullptr);
})));
FlushClient();
}
// Test a non-empty descriptor
{
wgpu::RequiredLimits limits = {};
limits.limits.maxStorageTexturesPerShaderStage = 5;
std::vector<wgpu::FeatureName> features = {wgpu::FeatureName::TextureCompressionETC2,
wgpu::FeatureName::TextureCompressionASTC};
wgpu::DeviceDescriptor desc = {};
desc.label = "hello device";
desc.requiredLimits = &limits;
desc.requiredFeaturesCount = features.size();
desc.requiredFeatures = features.data();
adapter.RequestDevice(&desc, cb.Callback(), userdata);
EXPECT_CALL(api, OnAdapterRequestDevice(apiAdapter, NotNull(), NotNull(), NotNull()))
.WillOnce(WithArg<1>(Invoke([&](const WGPUDeviceDescriptor* apiDesc) {
EXPECT_STREQ(apiDesc->label, desc.label);
ASSERT_EQ(apiDesc->requiredFeaturesCount, features.size());
for (uint32_t i = 0; i < features.size(); ++i) {
EXPECT_EQ(apiDesc->requiredFeatures[i],
static_cast<WGPUFeatureName>(features[i]));
}
ASSERT_NE(apiDesc->requiredLimits, nullptr);
EXPECT_EQ(apiDesc->requiredLimits->nextInChain, nullptr);
EXPECT_EQ(apiDesc->requiredLimits->limits.maxStorageTexturesPerShaderStage,
limits.limits.maxStorageTexturesPerShaderStage);
})));
FlushClient();
}
// Delete the adapter now, or it'll call the mock callback after it's deleted.
adapter = nullptr;
}
// Test that RequestDevice forwards the device information to the client.
TEST_F(WireAdapterTests, RequestDeviceSuccess) {
MockCallback<WGPURequestDeviceCallback> cb;
auto* userdata = cb.MakeUserdata(this);
wgpu::SupportedLimits fakeLimits = {};
fakeLimits.limits.maxTextureDimension1D = 433;
fakeLimits.limits.maxVertexAttributes = 1243;
std::initializer_list<wgpu::FeatureName> fakeFeatures = {
wgpu::FeatureName::Depth32FloatStencil8,
wgpu::FeatureName::TextureCompressionBC,
};
wgpu::DeviceDescriptor desc = {};
adapter.RequestDevice(&desc, cb.Callback(), userdata);
// Expect the server to receive the message. Then, mock a fake reply.
WGPUDevice apiDevice = api.GetNewDevice();
EXPECT_CALL(api, OnAdapterRequestDevice(apiAdapter, NotNull(), NotNull(), NotNull()))
.WillOnce(InvokeWithoutArgs([&]() {
// Set on device creation to forward callbacks to the client.
EXPECT_CALL(api,
OnDeviceSetUncapturedErrorCallback(apiDevice, NotNull(), NotNull()))
.Times(1);
EXPECT_CALL(api, OnDeviceSetLoggingCallback(apiDevice, NotNull(), NotNull()))
.Times(1);
EXPECT_CALL(api, OnDeviceSetDeviceLostCallback(apiDevice, NotNull(), NotNull()))
.Times(1);
EXPECT_CALL(api, DeviceGetLimits(apiDevice, NotNull()))
.WillOnce(WithArg<1>(Invoke([&](WGPUSupportedLimits* limits) {
*reinterpret_cast<wgpu::SupportedLimits*>(limits) = fakeLimits;
return true;
})));
EXPECT_CALL(api, DeviceEnumerateFeatures(apiDevice, nullptr))
.WillOnce(Return(fakeFeatures.size()));
EXPECT_CALL(api, DeviceEnumerateFeatures(apiDevice, NotNull()))
.WillOnce(WithArg<1>(Invoke([&](WGPUFeatureName* features) {
for (wgpu::FeatureName feature : fakeFeatures) {
*(features++) = static_cast<WGPUFeatureName>(feature);
}
return fakeFeatures.size();
})));
api.CallAdapterRequestDeviceCallback(apiAdapter, WGPURequestDeviceStatus_Success,
apiDevice, nullptr);
}));
FlushClient();
// Expect the callback in the client and all the device information to match.
EXPECT_CALL(cb, Call(WGPURequestDeviceStatus_Success, NotNull(), nullptr, this))
.WillOnce(WithArg<1>(Invoke([&](WGPUDevice cDevice) {
wgpu::Device device = wgpu::Device::Acquire(cDevice);
wgpu::SupportedLimits limits;
EXPECT_TRUE(device.GetLimits(&limits));
EXPECT_EQ(limits.limits.maxTextureDimension1D,
fakeLimits.limits.maxTextureDimension1D);
EXPECT_EQ(limits.limits.maxVertexAttributes, fakeLimits.limits.maxVertexAttributes);
std::vector<wgpu::FeatureName> features;
features.resize(device.EnumerateFeatures(nullptr));
ASSERT_EQ(features.size(), fakeFeatures.size());
EXPECT_EQ(device.EnumerateFeatures(&features[0]), features.size());
std::unordered_set<wgpu::FeatureName> featureSet(fakeFeatures);
for (wgpu::FeatureName feature : features) {
EXPECT_EQ(featureSet.erase(feature), 1u);
}
})));
FlushServer();
// Cleared when the device is destroyed.
EXPECT_CALL(api, OnDeviceSetUncapturedErrorCallback(apiDevice, nullptr, nullptr)).Times(1);
EXPECT_CALL(api, OnDeviceSetLoggingCallback(apiDevice, nullptr, nullptr)).Times(1);
EXPECT_CALL(api, OnDeviceSetDeviceLostCallback(apiDevice, nullptr, nullptr)).Times(1);
}
// Test that features requested that the implementation supports, but not the
// wire reject the callback.
TEST_F(WireAdapterTests, RequestFeatureUnsupportedByWire) {
MockCallback<WGPURequestDeviceCallback> cb;
auto* userdata = cb.MakeUserdata(this);
std::initializer_list<wgpu::FeatureName> fakeFeatures = {
// Some value that is not a valid feature
static_cast<wgpu::FeatureName>(-2),
wgpu::FeatureName::TextureCompressionASTC,
};
wgpu::DeviceDescriptor desc = {};
adapter.RequestDevice(&desc, cb.Callback(), userdata);
// Expect the server to receive the message. Then, mock a fake reply.
// The reply contains features that the device implementation supports, but the
// wire does not.
WGPUDevice apiDevice = api.GetNewDevice();
EXPECT_CALL(api, OnAdapterRequestDevice(apiAdapter, NotNull(), NotNull(), NotNull()))
.WillOnce(InvokeWithoutArgs([&]() {
EXPECT_CALL(api, DeviceEnumerateFeatures(apiDevice, nullptr))
.WillOnce(Return(fakeFeatures.size()));
EXPECT_CALL(api, DeviceEnumerateFeatures(apiDevice, NotNull()))
.WillOnce(WithArg<1>(Invoke([&](WGPUFeatureName* features) {
for (wgpu::FeatureName feature : fakeFeatures) {
*(features++) = static_cast<WGPUFeatureName>(feature);
}
return fakeFeatures.size();
})));
// The device was actually created, but the wire didn't support its features.
// Expect it to be released.
EXPECT_CALL(api, DeviceRelease(apiDevice));
// Fake successful creation. The client still receives a failure due to
// unsupported features.
api.CallAdapterRequestDeviceCallback(apiAdapter, WGPURequestDeviceStatus_Success,
apiDevice, nullptr);
}));
FlushClient();
// Expect an error callback since the feature is not supported.
EXPECT_CALL(cb, Call(WGPURequestDeviceStatus_Error, nullptr, NotNull(), this)).Times(1);
FlushServer();
}
// Test that RequestDevice errors forward to the client.
TEST_F(WireAdapterTests, RequestDeviceError) {
MockCallback<WGPURequestDeviceCallback> cb;
auto* userdata = cb.MakeUserdata(this);
wgpu::DeviceDescriptor desc = {};
adapter.RequestDevice(&desc, cb.Callback(), userdata);
// Expect the server to receive the message. Then, mock an error.
EXPECT_CALL(api, OnAdapterRequestDevice(apiAdapter, NotNull(), NotNull(), NotNull()))
.WillOnce(InvokeWithoutArgs([&]() {
api.CallAdapterRequestDeviceCallback(apiAdapter, WGPURequestDeviceStatus_Error,
nullptr, "Request device failed");
}));
FlushClient();
// Expect the callback in the client.
EXPECT_CALL(
cb, Call(WGPURequestDeviceStatus_Error, nullptr, StrEq("Request device failed"), this))
.Times(1);
FlushServer();
}
// Test that RequestDevice receives unknown status if the adapter is deleted
// before the callback happens.
TEST_F(WireAdapterTests, RequestDeviceAdapterDestroyedBeforeCallback) {
MockCallback<WGPURequestDeviceCallback> cb;
auto* userdata = cb.MakeUserdata(this);
wgpu::DeviceDescriptor desc = {};
adapter.RequestDevice(&desc, cb.Callback(), userdata);
EXPECT_CALL(cb, Call(WGPURequestDeviceStatus_Unknown, nullptr, NotNull(), this)).Times(1);
adapter = nullptr;
}
// Test that RequestDevice receives unknown status if the wire is disconnected
// before the callback happens.
TEST_F(WireAdapterTests, RequestDeviceWireDisconnectedBeforeCallback) {
MockCallback<WGPURequestDeviceCallback> cb;
auto* userdata = cb.MakeUserdata(this);
wgpu::DeviceDescriptor desc = {};
adapter.RequestDevice(&desc, cb.Callback(), userdata);
EXPECT_CALL(cb, Call(WGPURequestDeviceStatus_Unknown, nullptr, NotNull(), this)).Times(1);
GetWireClient()->Disconnect();
}
} // anonymous namespace
| 44.335347 | 100 | 0.596661 | Antidote |
c1d398d751c40a07b8c1e391757793dd50315106 | 2,047 | cpp | C++ | extensions/test/nsphere/nsphere-multi_within.cpp | jonasdmentia/geometry | 097f6fdbe98118be82cd1917cc72c3c6a37bdf30 | [
"BSL-1.0"
] | 326 | 2015-02-08T13:47:49.000Z | 2022-03-16T02:13:59.000Z | extensions/test/nsphere/nsphere-multi_within.cpp | jonasdmentia/geometry | 097f6fdbe98118be82cd1917cc72c3c6a37bdf30 | [
"BSL-1.0"
] | 623 | 2015-01-02T23:45:23.000Z | 2022-03-09T11:15:23.000Z | extensions/test/nsphere/nsphere-multi_within.cpp | jonasdmentia/geometry | 097f6fdbe98118be82cd1917cc72c3c6a37bdf30 | [
"BSL-1.0"
] | 215 | 2015-01-14T15:50:38.000Z | 2022-02-23T03:58:36.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
//
// Copyright (c) 2007-2012 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)
#include <geometry_test_common.hpp>
#include <boost/geometry/algorithms/correct.hpp>
#include <boost/geometry/algorithms/within.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/geometries.hpp>
#include <boost/geometry/geometries/ring.hpp>
#include <boost/geometry/geometries/linestring.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/multi/algorithms/within.hpp>
#include <boost/geometry/multi/core/point_type.hpp>
#include <boost/geometry/multi/geometries/multi_geometries.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/extensions/nsphere/nsphere.hpp>
int test_main( int , char* [] )
{
typedef bg::model::d2::point_xy<double> gl_point;
typedef bg::model::nsphere<gl_point, double> gl_circle;
typedef bg::model::ring<gl_point> gl_ring;
typedef bg::model::polygon<gl_point> gl_polygon;
typedef bg::model::multi_polygon<gl_polygon> gl_multi_polygon;
gl_circle circle(gl_point(1, 1), 2.5);
gl_ring ring;
ring.push_back(gl_point(0,0));
ring.push_back(gl_point(1,0));
ring.push_back(gl_point(1,1));
ring.push_back(gl_point(0,1));
bg::correct(ring);
gl_polygon pol;
pol.outer() = ring;
gl_multi_polygon multi_polygon;
multi_polygon.push_back(pol);
// Multipolygon in circle
BOOST_CHECK_EQUAL(bg::within(multi_polygon, circle), true);
multi_polygon.front().outer().insert(multi_polygon.front().outer().begin() + 1, gl_point(10, 10));
BOOST_CHECK_EQUAL(bg::within(multi_polygon, circle), false);
return 0;
}
| 35.912281 | 102 | 0.745481 | jonasdmentia |
c1d6dd87f8eae1fe05c6d040b6aaee7b6fac87aa | 7,257 | cpp | C++ | Official Windows Platform Sample/Windows Phone 8.1 samples/[C++]-Windows Phone 8.1 samples/Association launching sample/C++/Shared/App.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 2 | 2022-01-21T01:40:58.000Z | 2022-01-21T01:41:10.000Z | Official Windows Platform Sample/Windows Phone 8.1 samples/[C++]-Windows Phone 8.1 samples/Association launching sample/C++/Shared/App.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2022-03-15T04:21:41.000Z | 2022-03-15T04:21:41.000Z | Official Windows Platform Sample/Windows Phone 8.1 samples/[C++]-Windows Phone 8.1 samples/Association launching sample/C++/Shared/App.xaml.cpp | zzgchina888/msdn-code-gallery-microsoft | 21cb9b6bc0da3b234c5854ecac449cb3bd261f29 | [
"MIT"
] | 1 | 2015-12-25T11:15:10.000Z | 2015-12-25T11:15:10.000Z | // Copyright (c) Microsoft. All rights reserved.
#include "pch.h"
using namespace SDKSample;
using namespace Concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel;
using namespace Windows::ApplicationModel::Activation;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
App::App()
{
InitializeComponent();
Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending);
}
Frame^ App::CreateRootFrame()
{
Frame^ rootFrame = dynamic_cast<Frame^>(Window::Current->Content);
if (rootFrame == nullptr)
{
// Create a Frame to act as the navigation context
rootFrame = ref new Frame();
// Set the default language
rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0);
rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed);
// Place the frame in the current Window
Window::Current->Content = rootFrame;
}
return rootFrame;
}
concurrency::task<void> App::RestoreStatus(ApplicationExecutionState previousExecutionState)
{
auto prerequisite = task<void>([](){});
if (previousExecutionState == ApplicationExecutionState::Terminated)
{
prerequisite = SuspensionManager::RestoreAsync();
}
return prerequisite;
}
void App::OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^ e)
{
auto rootFrame = CreateRootFrame();
RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite)
{
try
{
prerequisite.get();
}
catch (Platform::Exception^)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
//MainPage is always in rootFrame so we don't have to worry about restoring the navigation state on resume
rootFrame->Navigate(TypeName(MainPage::typeid));
auto p = dynamic_cast<MainPage^>(rootFrame->Content);
p->FileEvent = e;
p->ProtocolEvent = nullptr;
p->NavigateToFilePage();
// Ensure the current window is active
Window::Current->Activate();
}, task_continuation_context::use_current());
}
void App::OnActivated(IActivatedEventArgs^ e)
{
if (e->Kind == Windows::ApplicationModel::Activation::ActivationKind::Protocol)
{
auto rootFrame = CreateRootFrame();
RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite)
{
try
{
prerequisite.get();
}
catch (Platform::Exception^)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
//MainPage is always in rootFrame so we don't have to worry about restoring the navigation state on resume
rootFrame->Navigate(TypeName(MainPage::typeid));
auto p = dynamic_cast<MainPage^>(rootFrame->Content);
p->FileEvent = nullptr;
p->ProtocolEvent = safe_cast<Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs^>(e);
p->NavigateToProtocolPage();
// Ensure the current window is active
Window::Current->Activate();
}, task_continuation_context::use_current());
}
#if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
else if (e->Kind == Windows::ApplicationModel::Activation::ActivationKind::PickFileContinuation)
{
Application::OnActivated(e);
continuationManager = ref new ContinuationManager();
RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite)
{
try
{
prerequisite.get();
}
catch (Platform::Exception^)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
auto continuationEventArgs = dynamic_cast<IContinuationActivatedEventArgs^>(e);
if (continuationEventArgs != nullptr)
{
MainPage^ mainPage = MainPage::Current;
Frame^ scenarioFrame = dynamic_cast<Frame^>(mainPage->FindName("ScenarioFrame"));
if (scenarioFrame == nullptr)
{
return;
}
continuationManager->Continue(continuationEventArgs, scenarioFrame);
}
}, task_continuation_context::use_current());
}
#endif //WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
void App::OnLaunched(LaunchActivatedEventArgs^ e)
{
auto rootFrame = CreateRootFrame();
RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite)
{
try
{
prerequisite.get();
}
catch (Platform::Exception^)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
//MainPage is always in rootFrame so we don't have to worry about restoring the navigation state on resume
rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments);
// Ensure the current window is active
Window::Current->Activate();
}, task_continuation_context::use_current());
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e)
{
(void)sender; // Unused parameter
auto deferral = e->SuspendingOperation->GetDeferral();
SuspensionManager::SaveAsync().then([=]()
{
deferral->Complete();
});
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e)
{
throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name);
} | 34.393365 | 139 | 0.656194 | zzgchina888 |
c1d7583e79ffaeaa215c722b6e9e26caa25f093d | 577 | hpp | C++ | src/network/net_message_handler.hpp | KMM2019-CrazyTaxi/central-module-main | b5506cb63ccb6eedd8b4f8e75aa17f1835926aa8 | [
"MIT"
] | null | null | null | src/network/net_message_handler.hpp | KMM2019-CrazyTaxi/central-module-main | b5506cb63ccb6eedd8b4f8e75aa17f1835926aa8 | [
"MIT"
] | 15 | 2019-11-02T15:25:55.000Z | 2019-12-20T12:26:46.000Z | src/network/net_message_handler.hpp | KMM2019-CrazyTaxi/central-module | b5506cb63ccb6eedd8b4f8e75aa17f1835926aa8 | [
"MIT"
] | null | null | null | #ifndef CM_NET_MESSAGE_HANDLER_H
#define CM_NET_MESSAGE_HANDLER_H
#include <vector>
#include "packet.hpp"
/**
* Handles a vector of packets and returns a vector of packets that contains the answer
* to the packets.
*
* @param packets A std::vector containing the packets to handle
* @return A new vector containing the answer packets
*/
std::vector<packet> handle_packets(const std::vector<packet>& packets);
/**
* Handles a single packet
*
* @param p The packet to handle
* @return The answer to the packet p
*/
packet handle_packet(const packet& p);
#endif | 22.192308 | 87 | 0.736568 | KMM2019-CrazyTaxi |
c1d9de270f011de0e626c20b462b816570c9623d | 90,323 | cpp | C++ | src/cpp/lib/codec/mp3/layer2.cpp | jojanper/mp3dec | abaa34acbcc8f82cc04f47ab566a1f34b55e66c5 | [
"MIT"
] | 2 | 2021-09-03T19:36:03.000Z | 2021-12-08T01:31:31.000Z | src/cpp/lib/codec/mp3/layer2.cpp | jojanper/mp3dec | abaa34acbcc8f82cc04f47ab566a1f34b55e66c5 | [
"MIT"
] | 10 | 2020-03-25T16:55:28.000Z | 2022-03-06T13:12:55.000Z | src/cpp/lib/codec/mp3/layer2.cpp | jojanper/mp3dec | abaa34acbcc8f82cc04f47ab566a1f34b55e66c5 | [
"MIT"
] | null | null | null | /**************************************************************************
layer2.cpp - MPEG-1/MPEG-2 LSF Layer II decoding subroutines.
Author(s): Juha Ojanpera
Copyright (c) 1998-1999 Juha Ojanpera.
*************************************************************************/
/**************************************************************************
External Objects Needed
*************************************************************************/
/*-- System Headers. --*/
#include <string.h>
/*-- Project Headers. --*/
#include "layer.h"
#include "mstream.h" // MP_Stream class
extern int16 sample_mask[];
extern uint32 sign_mask[];
extern FLOAT scale_factors[2 * SBLIMIT];
/**************************************************************************
Internal Objects
*************************************************************************/
/*
Purpose: Obtains the dequantized samples from precomputed tables.
Explanation: - */
#define USE_LAYER_II_TABLES
/*
Purpose: Computes the dequantization tables.
Explanation: No grouping tables included. */
//#define GENERATE_TABLES
/*
Purpose: Computes the dequantization tables for grouped samples.
Explanation: - */
//#define NO_GROUPING_SAMPLES
/*
Purpose: This table contains 3 requantized samples for each
legal codeword when grouped in 5 bits, i.e. 3 quantization
steps per sample.
Explanation: - */
static const FLOAT group3_samples[] = {
-0.6666666667, -0.6666666667, -0.6666666667, 0.0000000000, -0.6666666667, -0.6666666667,
0.6666666667, -0.6666666667, -0.6666666667, -0.6666666667, 0.0000000000, -0.6666666667,
0.0000000000, 0.0000000000, -0.6666666667, 0.6666666667, 0.0000000000, -0.6666666667,
-0.6666666667, 0.6666666667, -0.6666666667, 0.0000000000, 0.6666666667, -0.6666666667,
0.6666666667, 0.6666666667, -0.6666666667, -0.6666666667, -0.6666666667, 0.0000000000,
0.0000000000, -0.6666666667, 0.0000000000, 0.6666666667, -0.6666666667, 0.0000000000,
-0.6666666667, 0.0000000000, 0.0000000000, 0.0000000000, 0.0000000000, 0.0000000000,
0.6666666667, 0.0000000000, 0.0000000000, -0.6666666667, 0.6666666667, 0.0000000000,
0.0000000000, 0.6666666667, 0.0000000000, 0.6666666667, 0.6666666667, 0.0000000000,
-0.6666666667, -0.6666666667, 0.6666666667, 0.0000000000, -0.6666666667, 0.6666666667,
0.6666666667, -0.6666666667, 0.6666666667, -0.6666666667, 0.0000000000, 0.6666666667,
0.0000000000, 0.0000000000, 0.6666666667, 0.6666666667, 0.0000000000, 0.6666666667,
-0.6666666667, 0.6666666667, 0.6666666667, 0.0000000000, 0.6666666667, 0.6666666667,
0.6666666667, 0.6666666667, 0.6666666667, -0.6666666667, -0.6666666667, -0.6666666667,
0.0000000000, -0.6666666667, -0.6666666667, 0.6666666667, -0.6666666667, -0.6666666667,
-0.6666666667, 0.0000000000, -0.6666666667, 0.0000000000, 0.0000000000, -0.6666666667
};
/*
Purpose: This table contains 3 requantized samples for each
legal codeword when grouped in 7 bits, i.e. 5 quantization
steps per sample.
Explanation: - */
static const FLOAT group5_samples[] = {
-0.8, -0.8, -0.8, -0.4, -0.8, -0.8, 0.0, -0.8, -0.8, 0.4, -0.8, -0.8, 0.8, -0.8, -0.8,
-0.8, -0.4, -0.8, -0.4, -0.4, -0.8, 0.0, -0.4, -0.8, 0.4, -0.4, -0.8, 0.8, -0.4, -0.8,
-0.8, 0.0, -0.8, -0.4, 0.0, -0.8, 0.0, 0.0, -0.8, 0.4, 0.0, -0.8, 0.8, 0.0, -0.8,
-0.8, 0.4, -0.8, -0.4, 0.4, -0.8, 0.0, 0.4, -0.8, 0.4, 0.4, -0.8, 0.8, 0.4, -0.8,
-0.8, 0.8, -0.8, -0.4, 0.8, -0.8, 0.0, 0.8, -0.8, 0.4, 0.8, -0.8, 0.8, 0.8, -0.8,
-0.8, -0.8, -0.4, -0.4, -0.8, -0.4, 0.0, -0.8, -0.4, 0.4, -0.8, -0.4, 0.8, -0.8, -0.4,
-0.8, -0.4, -0.4, -0.4, -0.4, -0.4, 0.0, -0.4, -0.4, 0.4, -0.4, -0.4, 0.8, -0.4, -0.4,
-0.8, 0.0, -0.4, -0.4, 0.0, -0.4, 0.0, 0.0, -0.4, 0.4, 0.0, -0.4, 0.8, 0.0, -0.4,
-0.8, 0.4, -0.4, -0.4, 0.4, -0.4, 0.0, 0.4, -0.4, 0.4, 0.4, -0.4, 0.8, 0.4, -0.4,
-0.8, 0.8, -0.4, -0.4, 0.8, -0.4, 0.0, 0.8, -0.4, 0.4, 0.8, -0.4, 0.8, 0.8, -0.4,
-0.8, -0.8, 0.0, -0.4, -0.8, 0.0, 0.0, -0.8, 0.0, 0.4, -0.8, 0.0, 0.8, -0.8, 0.0,
-0.8, -0.4, 0.0, -0.4, -0.4, 0.0, 0.0, -0.4, 0.0, 0.4, -0.4, 0.0, 0.8, -0.4, 0.0,
-0.8, 0.0, 0.0, -0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.4, 0.0, 0.0, 0.8, 0.0, 0.0,
-0.8, 0.4, 0.0, -0.4, 0.4, 0.0, 0.0, 0.4, 0.0, 0.4, 0.4, 0.0, 0.8, 0.4, 0.0,
-0.8, 0.8, 0.0, -0.4, 0.8, 0.0, 0.0, 0.8, 0.0, 0.4, 0.8, 0.0, 0.8, 0.8, 0.0,
-0.8, -0.8, 0.4, -0.4, -0.8, 0.4, 0.0, -0.8, 0.4, 0.4, -0.8, 0.4, 0.8, -0.8, 0.4,
-0.8, -0.4, 0.4, -0.4, -0.4, 0.4, 0.0, -0.4, 0.4, 0.4, -0.4, 0.4, 0.8, -0.4, 0.4,
-0.8, 0.0, 0.4, -0.4, 0.0, 0.4, 0.0, 0.0, 0.4, 0.4, 0.0, 0.4, 0.8, 0.0, 0.4,
-0.8, 0.4, 0.4, -0.4, 0.4, 0.4, 0.0, 0.4, 0.4, 0.4, 0.4, 0.4, 0.8, 0.4, 0.4,
-0.8, 0.8, 0.4, -0.4, 0.8, 0.4, 0.0, 0.8, 0.4, 0.4, 0.8, 0.4, 0.8, 0.8, 0.4,
-0.8, -0.8, 0.8, -0.4, -0.8, 0.8, 0.0, -0.8, 0.8, 0.4, -0.8, 0.8, 0.8, -0.8, 0.8,
-0.8, -0.4, 0.8, -0.4, -0.4, 0.8, 0.0, -0.4, 0.8, 0.4, -0.4, 0.8, 0.8, -0.4, 0.8,
-0.8, 0.0, 0.8, -0.4, 0.0, 0.8, 0.0, 0.0, 0.8, 0.4, 0.0, 0.8, 0.8, 0.0, 0.8,
-0.8, 0.4, 0.8, -0.4, 0.4, 0.8, 0.0, 0.4, 0.8, 0.4, 0.4, 0.8, 0.8, 0.4, 0.8,
-0.8, 0.8, 0.8, -0.4, 0.8, 0.8, 0.0, 0.8, 0.8, 0.4, 0.8, 0.8, 0.8, 0.8, 0.8,
-0.8, -0.8, -0.8, -0.4, -0.8, -0.8, 0.0, -0.8, -0.8
};
/*
Purpose: This table contains 3 requantized samples for each
legal codeword when grouped in 10 bits, i.e. 9 quantization
steps per sample.
Explanation: - */
static const FLOAT group9_samples[] = {
-0.8888888889, -0.8888888889, -0.8888888889, -0.6666666667, -0.8888888889, -0.8888888889,
-0.4444444444, -0.8888888889, -0.8888888889, -0.2222222222, -0.8888888889, -0.8888888889,
0.0000000000, -0.8888888889, -0.8888888889, 0.2222222222, -0.8888888889, -0.8888888889,
0.4444444444, -0.8888888889, -0.8888888889, 0.6666666667, -0.8888888889, -0.8888888889,
0.8888888889, -0.8888888889, -0.8888888889, -0.8888888889, -0.6666666667, -0.8888888889,
-0.6666666667, -0.6666666667, -0.8888888889, -0.4444444444, -0.6666666667, -0.8888888889,
-0.2222222222, -0.6666666667, -0.8888888889, 0.0000000000, -0.6666666667, -0.8888888889,
0.2222222222, -0.6666666667, -0.8888888889, 0.4444444444, -0.6666666667, -0.8888888889,
0.6666666667, -0.6666666667, -0.8888888889, 0.8888888889, -0.6666666667, -0.8888888889,
-0.8888888889, -0.4444444444, -0.8888888889, -0.6666666667, -0.4444444444, -0.8888888889,
-0.4444444444, -0.4444444444, -0.8888888889, -0.2222222222, -0.4444444444, -0.8888888889,
0.0000000000, -0.4444444444, -0.8888888889, 0.2222222222, -0.4444444444, -0.8888888889,
0.4444444444, -0.4444444444, -0.8888888889, 0.6666666667, -0.4444444444, -0.8888888889,
0.8888888889, -0.4444444444, -0.8888888889, -0.8888888889, -0.2222222222, -0.8888888889,
-0.6666666667, -0.2222222222, -0.8888888889, -0.4444444444, -0.2222222222, -0.8888888889,
-0.2222222222, -0.2222222222, -0.8888888889, 0.0000000000, -0.2222222222, -0.8888888889,
0.2222222222, -0.2222222222, -0.8888888889, 0.4444444444, -0.2222222222, -0.8888888889,
0.6666666667, -0.2222222222, -0.8888888889, 0.8888888889, -0.2222222222, -0.8888888889,
-0.8888888889, 0.0000000000, -0.8888888889, -0.6666666667, 0.0000000000, -0.8888888889,
-0.4444444444, 0.0000000000, -0.8888888889, -0.2222222222, 0.0000000000, -0.8888888889,
0.0000000000, 0.0000000000, -0.8888888889, 0.2222222222, 0.0000000000, -0.8888888889,
0.4444444444, 0.0000000000, -0.8888888889, 0.6666666667, 0.0000000000, -0.8888888889,
0.8888888889, 0.0000000000, -0.8888888889, -0.8888888889, 0.2222222222, -0.8888888889,
-0.6666666667, 0.2222222222, -0.8888888889, -0.4444444444, 0.2222222222, -0.8888888889,
-0.2222222222, 0.2222222222, -0.8888888889, 0.0000000000, 0.2222222222, -0.8888888889,
0.2222222222, 0.2222222222, -0.8888888889, 0.4444444444, 0.2222222222, -0.8888888889,
0.6666666667, 0.2222222222, -0.8888888889, 0.8888888889, 0.2222222222, -0.8888888889,
-0.8888888889, 0.4444444444, -0.8888888889, -0.6666666667, 0.4444444444, -0.8888888889,
-0.4444444444, 0.4444444444, -0.8888888889, -0.2222222222, 0.4444444444, -0.8888888889,
0.0000000000, 0.4444444444, -0.8888888889, 0.2222222222, 0.4444444444, -0.8888888889,
0.4444444444, 0.4444444444, -0.8888888889, 0.6666666667, 0.4444444444, -0.8888888889,
0.8888888889, 0.4444444444, -0.8888888889, -0.8888888889, 0.6666666667, -0.8888888889,
-0.6666666667, 0.6666666667, -0.8888888889, -0.4444444444, 0.6666666667, -0.8888888889,
-0.2222222222, 0.6666666667, -0.8888888889, 0.0000000000, 0.6666666667, -0.8888888889,
0.2222222222, 0.6666666667, -0.8888888889, 0.4444444444, 0.6666666667, -0.8888888889,
0.6666666667, 0.6666666667, -0.8888888889, 0.8888888889, 0.6666666667, -0.8888888889,
-0.8888888889, 0.8888888889, -0.8888888889, -0.6666666667, 0.8888888889, -0.8888888889,
-0.4444444444, 0.8888888889, -0.8888888889, -0.2222222222, 0.8888888889, -0.8888888889,
0.0000000000, 0.8888888889, -0.8888888889, 0.2222222222, 0.8888888889, -0.8888888889,
0.4444444444, 0.8888888889, -0.8888888889, 0.6666666667, 0.8888888889, -0.8888888889,
0.8888888889, 0.8888888889, -0.8888888889, -0.8888888889, -0.8888888889, -0.6666666667,
-0.6666666667, -0.8888888889, -0.6666666667, -0.4444444444, -0.8888888889, -0.6666666667,
-0.2222222222, -0.8888888889, -0.6666666667, 0.0000000000, -0.8888888889, -0.6666666667,
0.2222222222, -0.8888888889, -0.6666666667, 0.4444444444, -0.8888888889, -0.6666666667,
0.6666666667, -0.8888888889, -0.6666666667, 0.8888888889, -0.8888888889, -0.6666666667,
-0.8888888889, -0.6666666667, -0.6666666667, -0.6666666667, -0.6666666667, -0.6666666667,
-0.4444444444, -0.6666666667, -0.6666666667, -0.2222222222, -0.6666666667, -0.6666666667,
0.0000000000, -0.6666666667, -0.6666666667, 0.2222222222, -0.6666666667, -0.6666666667,
0.4444444444, -0.6666666667, -0.6666666667, 0.6666666667, -0.6666666667, -0.6666666667,
0.8888888889, -0.6666666667, -0.6666666667, -0.8888888889, -0.4444444444, -0.6666666667,
-0.6666666667, -0.4444444444, -0.6666666667, -0.4444444444, -0.4444444444, -0.6666666667,
-0.2222222222, -0.4444444444, -0.6666666667, 0.0000000000, -0.4444444444, -0.6666666667,
0.2222222222, -0.4444444444, -0.6666666667, 0.4444444444, -0.4444444444, -0.6666666667,
0.6666666667, -0.4444444444, -0.6666666667, 0.8888888889, -0.4444444444, -0.6666666667,
-0.8888888889, -0.2222222222, -0.6666666667, -0.6666666667, -0.2222222222, -0.6666666667,
-0.4444444444, -0.2222222222, -0.6666666667, -0.2222222222, -0.2222222222, -0.6666666667,
0.0000000000, -0.2222222222, -0.6666666667, 0.2222222222, -0.2222222222, -0.6666666667,
0.4444444444, -0.2222222222, -0.6666666667, 0.6666666667, -0.2222222222, -0.6666666667,
0.8888888889, -0.2222222222, -0.6666666667, -0.8888888889, 0.0000000000, -0.6666666667,
-0.6666666667, 0.0000000000, -0.6666666667, -0.4444444444, 0.0000000000, -0.6666666667,
-0.2222222222, 0.0000000000, -0.6666666667, 0.0000000000, 0.0000000000, -0.6666666667,
0.2222222222, 0.0000000000, -0.6666666667, 0.4444444444, 0.0000000000, -0.6666666667,
0.6666666667, 0.0000000000, -0.6666666667, 0.8888888889, 0.0000000000, -0.6666666667,
-0.8888888889, 0.2222222222, -0.6666666667, -0.6666666667, 0.2222222222, -0.6666666667,
-0.4444444444, 0.2222222222, -0.6666666667, -0.2222222222, 0.2222222222, -0.6666666667,
0.0000000000, 0.2222222222, -0.6666666667, 0.2222222222, 0.2222222222, -0.6666666667,
0.4444444444, 0.2222222222, -0.6666666667, 0.6666666667, 0.2222222222, -0.6666666667,
0.8888888889, 0.2222222222, -0.6666666667, -0.8888888889, 0.4444444444, -0.6666666667,
-0.6666666667, 0.4444444444, -0.6666666667, -0.4444444444, 0.4444444444, -0.6666666667,
-0.2222222222, 0.4444444444, -0.6666666667, 0.0000000000, 0.4444444444, -0.6666666667,
0.2222222222, 0.4444444444, -0.6666666667, 0.4444444444, 0.4444444444, -0.6666666667,
0.6666666667, 0.4444444444, -0.6666666667, 0.8888888889, 0.4444444444, -0.6666666667,
-0.8888888889, 0.6666666667, -0.6666666667, -0.6666666667, 0.6666666667, -0.6666666667,
-0.4444444444, 0.6666666667, -0.6666666667, -0.2222222222, 0.6666666667, -0.6666666667,
0.0000000000, 0.6666666667, -0.6666666667, 0.2222222222, 0.6666666667, -0.6666666667,
0.4444444444, 0.6666666667, -0.6666666667, 0.6666666667, 0.6666666667, -0.6666666667,
0.8888888889, 0.6666666667, -0.6666666667, -0.8888888889, 0.8888888889, -0.6666666667,
-0.6666666667, 0.8888888889, -0.6666666667, -0.4444444444, 0.8888888889, -0.6666666667,
-0.2222222222, 0.8888888889, -0.6666666667, 0.0000000000, 0.8888888889, -0.6666666667,
0.2222222222, 0.8888888889, -0.6666666667, 0.4444444444, 0.8888888889, -0.6666666667,
0.6666666667, 0.8888888889, -0.6666666667, 0.8888888889, 0.8888888889, -0.6666666667,
-0.8888888889, -0.8888888889, -0.4444444444, -0.6666666667, -0.8888888889, -0.4444444444,
-0.4444444444, -0.8888888889, -0.4444444444, -0.2222222222, -0.8888888889, -0.4444444444,
0.0000000000, -0.8888888889, -0.4444444444, 0.2222222222, -0.8888888889, -0.4444444444,
0.4444444444, -0.8888888889, -0.4444444444, 0.6666666667, -0.8888888889, -0.4444444444,
0.8888888889, -0.8888888889, -0.4444444444, -0.8888888889, -0.6666666667, -0.4444444444,
-0.6666666667, -0.6666666667, -0.4444444444, -0.4444444444, -0.6666666667, -0.4444444444,
-0.2222222222, -0.6666666667, -0.4444444444, 0.0000000000, -0.6666666667, -0.4444444444,
0.2222222222, -0.6666666667, -0.4444444444, 0.4444444444, -0.6666666667, -0.4444444444,
0.6666666667, -0.6666666667, -0.4444444444, 0.8888888889, -0.6666666667, -0.4444444444,
-0.8888888889, -0.4444444444, -0.4444444444, -0.6666666667, -0.4444444444, -0.4444444444,
-0.4444444444, -0.4444444444, -0.4444444444, -0.2222222222, -0.4444444444, -0.4444444444,
0.0000000000, -0.4444444444, -0.4444444444, 0.2222222222, -0.4444444444, -0.4444444444,
0.4444444444, -0.4444444444, -0.4444444444, 0.6666666667, -0.4444444444, -0.4444444444,
0.8888888889, -0.4444444444, -0.4444444444, -0.8888888889, -0.2222222222, -0.4444444444,
-0.6666666667, -0.2222222222, -0.4444444444, -0.4444444444, -0.2222222222, -0.4444444444,
-0.2222222222, -0.2222222222, -0.4444444444, 0.0000000000, -0.2222222222, -0.4444444444,
0.2222222222, -0.2222222222, -0.4444444444, 0.4444444444, -0.2222222222, -0.4444444444,
0.6666666667, -0.2222222222, -0.4444444444, 0.8888888889, -0.2222222222, -0.4444444444,
-0.8888888889, 0.0000000000, -0.4444444444, -0.6666666667, 0.0000000000, -0.4444444444,
-0.4444444444, 0.0000000000, -0.4444444444, -0.2222222222, 0.0000000000, -0.4444444444,
0.0000000000, 0.0000000000, -0.4444444444, 0.2222222222, 0.0000000000, -0.4444444444,
0.4444444444, 0.0000000000, -0.4444444444, 0.6666666667, 0.0000000000, -0.4444444444,
0.8888888889, 0.0000000000, -0.4444444444, -0.8888888889, 0.2222222222, -0.4444444444,
-0.6666666667, 0.2222222222, -0.4444444444, -0.4444444444, 0.2222222222, -0.4444444444,
-0.2222222222, 0.2222222222, -0.4444444444, 0.0000000000, 0.2222222222, -0.4444444444,
0.2222222222, 0.2222222222, -0.4444444444, 0.4444444444, 0.2222222222, -0.4444444444,
0.6666666667, 0.2222222222, -0.4444444444, 0.8888888889, 0.2222222222, -0.4444444444,
-0.8888888889, 0.4444444444, -0.4444444444, -0.6666666667, 0.4444444444, -0.4444444444,
-0.4444444444, 0.4444444444, -0.4444444444, -0.2222222222, 0.4444444444, -0.4444444444,
0.0000000000, 0.4444444444, -0.4444444444, 0.2222222222, 0.4444444444, -0.4444444444,
0.4444444444, 0.4444444444, -0.4444444444, 0.6666666667, 0.4444444444, -0.4444444444,
0.8888888889, 0.4444444444, -0.4444444444, -0.8888888889, 0.6666666667, -0.4444444444,
-0.6666666667, 0.6666666667, -0.4444444444, -0.4444444444, 0.6666666667, -0.4444444444,
-0.2222222222, 0.6666666667, -0.4444444444, 0.0000000000, 0.6666666667, -0.4444444444,
0.2222222222, 0.6666666667, -0.4444444444, 0.4444444444, 0.6666666667, -0.4444444444,
0.6666666667, 0.6666666667, -0.4444444444, 0.8888888889, 0.6666666667, -0.4444444444,
-0.8888888889, 0.8888888889, -0.4444444444, -0.6666666667, 0.8888888889, -0.4444444444,
-0.4444444444, 0.8888888889, -0.4444444444, -0.2222222222, 0.8888888889, -0.4444444444,
0.0000000000, 0.8888888889, -0.4444444444, 0.2222222222, 0.8888888889, -0.4444444444,
0.4444444444, 0.8888888889, -0.4444444444, 0.6666666667, 0.8888888889, -0.4444444444,
0.8888888889, 0.8888888889, -0.4444444444, -0.8888888889, -0.8888888889, -0.2222222222,
-0.6666666667, -0.8888888889, -0.2222222222, -0.4444444444, -0.8888888889, -0.2222222222,
-0.2222222222, -0.8888888889, -0.2222222222, 0.0000000000, -0.8888888889, -0.2222222222,
0.2222222222, -0.8888888889, -0.2222222222, 0.4444444444, -0.8888888889, -0.2222222222,
0.6666666667, -0.8888888889, -0.2222222222, 0.8888888889, -0.8888888889, -0.2222222222,
-0.8888888889, -0.6666666667, -0.2222222222, -0.6666666667, -0.6666666667, -0.2222222222,
-0.4444444444, -0.6666666667, -0.2222222222, -0.2222222222, -0.6666666667, -0.2222222222,
0.0000000000, -0.6666666667, -0.2222222222, 0.2222222222, -0.6666666667, -0.2222222222,
0.4444444444, -0.6666666667, -0.2222222222, 0.6666666667, -0.6666666667, -0.2222222222,
0.8888888889, -0.6666666667, -0.2222222222, -0.8888888889, -0.4444444444, -0.2222222222,
-0.6666666667, -0.4444444444, -0.2222222222, -0.4444444444, -0.4444444444, -0.2222222222,
-0.2222222222, -0.4444444444, -0.2222222222, 0.0000000000, -0.4444444444, -0.2222222222,
0.2222222222, -0.4444444444, -0.2222222222, 0.4444444444, -0.4444444444, -0.2222222222,
0.6666666667, -0.4444444444, -0.2222222222, 0.8888888889, -0.4444444444, -0.2222222222,
-0.8888888889, -0.2222222222, -0.2222222222, -0.6666666667, -0.2222222222, -0.2222222222,
-0.4444444444, -0.2222222222, -0.2222222222, -0.2222222222, -0.2222222222, -0.2222222222,
0.0000000000, -0.2222222222, -0.2222222222, 0.2222222222, -0.2222222222, -0.2222222222,
0.4444444444, -0.2222222222, -0.2222222222, 0.6666666667, -0.2222222222, -0.2222222222,
0.8888888889, -0.2222222222, -0.2222222222, -0.8888888889, 0.0000000000, -0.2222222222,
-0.6666666667, 0.0000000000, -0.2222222222, -0.4444444444, 0.0000000000, -0.2222222222,
-0.2222222222, 0.0000000000, -0.2222222222, 0.0000000000, 0.0000000000, -0.2222222222,
0.2222222222, 0.0000000000, -0.2222222222, 0.4444444444, 0.0000000000, -0.2222222222,
0.6666666667, 0.0000000000, -0.2222222222, 0.8888888889, 0.0000000000, -0.2222222222,
-0.8888888889, 0.2222222222, -0.2222222222, -0.6666666667, 0.2222222222, -0.2222222222,
-0.4444444444, 0.2222222222, -0.2222222222, -0.2222222222, 0.2222222222, -0.2222222222,
0.0000000000, 0.2222222222, -0.2222222222, 0.2222222222, 0.2222222222, -0.2222222222,
0.4444444444, 0.2222222222, -0.2222222222, 0.6666666667, 0.2222222222, -0.2222222222,
0.8888888889, 0.2222222222, -0.2222222222, -0.8888888889, 0.4444444444, -0.2222222222,
-0.6666666667, 0.4444444444, -0.2222222222, -0.4444444444, 0.4444444444, -0.2222222222,
-0.2222222222, 0.4444444444, -0.2222222222, 0.0000000000, 0.4444444444, -0.2222222222,
0.2222222222, 0.4444444444, -0.2222222222, 0.4444444444, 0.4444444444, -0.2222222222,
0.6666666667, 0.4444444444, -0.2222222222, 0.8888888889, 0.4444444444, -0.2222222222,
-0.8888888889, 0.6666666667, -0.2222222222, -0.6666666667, 0.6666666667, -0.2222222222,
-0.4444444444, 0.6666666667, -0.2222222222, -0.2222222222, 0.6666666667, -0.2222222222,
0.0000000000, 0.6666666667, -0.2222222222, 0.2222222222, 0.6666666667, -0.2222222222,
0.4444444444, 0.6666666667, -0.2222222222, 0.6666666667, 0.6666666667, -0.2222222222,
0.8888888889, 0.6666666667, -0.2222222222, -0.8888888889, 0.8888888889, -0.2222222222,
-0.6666666667, 0.8888888889, -0.2222222222, -0.4444444444, 0.8888888889, -0.2222222222,
-0.2222222222, 0.8888888889, -0.2222222222, 0.0000000000, 0.8888888889, -0.2222222222,
0.2222222222, 0.8888888889, -0.2222222222, 0.4444444444, 0.8888888889, -0.2222222222,
0.6666666667, 0.8888888889, -0.2222222222, 0.8888888889, 0.8888888889, -0.2222222222,
-0.8888888889, -0.8888888889, 0.0000000000, -0.6666666667, -0.8888888889, 0.0000000000,
-0.4444444444, -0.8888888889, 0.0000000000, -0.2222222222, -0.8888888889, 0.0000000000,
0.0000000000, -0.8888888889, 0.0000000000, 0.2222222222, -0.8888888889, 0.0000000000,
0.4444444444, -0.8888888889, 0.0000000000, 0.6666666667, -0.8888888889, 0.0000000000,
0.8888888889, -0.8888888889, 0.0000000000, -0.8888888889, -0.6666666667, 0.0000000000,
-0.6666666667, -0.6666666667, 0.0000000000, -0.4444444444, -0.6666666667, 0.0000000000,
-0.2222222222, -0.6666666667, 0.0000000000, 0.0000000000, -0.6666666667, 0.0000000000,
0.2222222222, -0.6666666667, 0.0000000000, 0.4444444444, -0.6666666667, 0.0000000000,
0.6666666667, -0.6666666667, 0.0000000000, 0.8888888889, -0.6666666667, 0.0000000000,
-0.8888888889, -0.4444444444, 0.0000000000, -0.6666666667, -0.4444444444, 0.0000000000,
-0.4444444444, -0.4444444444, 0.0000000000, -0.2222222222, -0.4444444444, 0.0000000000,
0.0000000000, -0.4444444444, 0.0000000000, 0.2222222222, -0.4444444444, 0.0000000000,
0.4444444444, -0.4444444444, 0.0000000000, 0.6666666667, -0.4444444444, 0.0000000000,
0.8888888889, -0.4444444444, 0.0000000000, -0.8888888889, -0.2222222222, 0.0000000000,
-0.6666666667, -0.2222222222, 0.0000000000, -0.4444444444, -0.2222222222, 0.0000000000,
-0.2222222222, -0.2222222222, 0.0000000000, 0.0000000000, -0.2222222222, 0.0000000000,
0.2222222222, -0.2222222222, 0.0000000000, 0.4444444444, -0.2222222222, 0.0000000000,
0.6666666667, -0.2222222222, 0.0000000000, 0.8888888889, -0.2222222222, 0.0000000000,
-0.8888888889, 0.0000000000, 0.0000000000, -0.6666666667, 0.0000000000, 0.0000000000,
-0.4444444444, 0.0000000000, 0.0000000000, -0.2222222222, 0.0000000000, 0.0000000000,
0.0000000000, 0.0000000000, 0.0000000000, 0.2222222222, 0.0000000000, 0.0000000000,
0.4444444444, 0.0000000000, 0.0000000000, 0.6666666667, 0.0000000000, 0.0000000000,
0.8888888889, 0.0000000000, 0.0000000000, -0.8888888889, 0.2222222222, 0.0000000000,
-0.6666666667, 0.2222222222, 0.0000000000, -0.4444444444, 0.2222222222, 0.0000000000,
-0.2222222222, 0.2222222222, 0.0000000000, 0.0000000000, 0.2222222222, 0.0000000000,
0.2222222222, 0.2222222222, 0.0000000000, 0.4444444444, 0.2222222222, 0.0000000000,
0.6666666667, 0.2222222222, 0.0000000000, 0.8888888889, 0.2222222222, 0.0000000000,
-0.8888888889, 0.4444444444, 0.0000000000, -0.6666666667, 0.4444444444, 0.0000000000,
-0.4444444444, 0.4444444444, 0.0000000000, -0.2222222222, 0.4444444444, 0.0000000000,
0.0000000000, 0.4444444444, 0.0000000000, 0.2222222222, 0.4444444444, 0.0000000000,
0.4444444444, 0.4444444444, 0.0000000000, 0.6666666667, 0.4444444444, 0.0000000000,
0.8888888889, 0.4444444444, 0.0000000000, -0.8888888889, 0.6666666667, 0.0000000000,
-0.6666666667, 0.6666666667, 0.0000000000, -0.4444444444, 0.6666666667, 0.0000000000,
-0.2222222222, 0.6666666667, 0.0000000000, 0.0000000000, 0.6666666667, 0.0000000000,
0.2222222222, 0.6666666667, 0.0000000000, 0.4444444444, 0.6666666667, 0.0000000000,
0.6666666667, 0.6666666667, 0.0000000000, 0.8888888889, 0.6666666667, 0.0000000000,
-0.8888888889, 0.8888888889, 0.0000000000, -0.6666666667, 0.8888888889, 0.0000000000,
-0.4444444444, 0.8888888889, 0.0000000000, -0.2222222222, 0.8888888889, 0.0000000000,
0.0000000000, 0.8888888889, 0.0000000000, 0.2222222222, 0.8888888889, 0.0000000000,
0.4444444444, 0.8888888889, 0.0000000000, 0.6666666667, 0.8888888889, 0.0000000000,
0.8888888889, 0.8888888889, 0.0000000000, -0.8888888889, -0.8888888889, 0.2222222222,
-0.6666666667, -0.8888888889, 0.2222222222, -0.4444444444, -0.8888888889, 0.2222222222,
-0.2222222222, -0.8888888889, 0.2222222222, 0.0000000000, -0.8888888889, 0.2222222222,
0.2222222222, -0.8888888889, 0.2222222222, 0.4444444444, -0.8888888889, 0.2222222222,
0.6666666667, -0.8888888889, 0.2222222222, 0.8888888889, -0.8888888889, 0.2222222222,
-0.8888888889, -0.6666666667, 0.2222222222, -0.6666666667, -0.6666666667, 0.2222222222,
-0.4444444444, -0.6666666667, 0.2222222222, -0.2222222222, -0.6666666667, 0.2222222222,
0.0000000000, -0.6666666667, 0.2222222222, 0.2222222222, -0.6666666667, 0.2222222222,
0.4444444444, -0.6666666667, 0.2222222222, 0.6666666667, -0.6666666667, 0.2222222222,
0.8888888889, -0.6666666667, 0.2222222222, -0.8888888889, -0.4444444444, 0.2222222222,
-0.6666666667, -0.4444444444, 0.2222222222, -0.4444444444, -0.4444444444, 0.2222222222,
-0.2222222222, -0.4444444444, 0.2222222222, 0.0000000000, -0.4444444444, 0.2222222222,
0.2222222222, -0.4444444444, 0.2222222222, 0.4444444444, -0.4444444444, 0.2222222222,
0.6666666667, -0.4444444444, 0.2222222222, 0.8888888889, -0.4444444444, 0.2222222222,
-0.8888888889, -0.2222222222, 0.2222222222, -0.6666666667, -0.2222222222, 0.2222222222,
-0.4444444444, -0.2222222222, 0.2222222222, -0.2222222222, -0.2222222222, 0.2222222222,
0.0000000000, -0.2222222222, 0.2222222222, 0.2222222222, -0.2222222222, 0.2222222222,
0.4444444444, -0.2222222222, 0.2222222222, 0.6666666667, -0.2222222222, 0.2222222222,
0.8888888889, -0.2222222222, 0.2222222222, -0.8888888889, 0.0000000000, 0.2222222222,
-0.6666666667, 0.0000000000, 0.2222222222, -0.4444444444, 0.0000000000, 0.2222222222,
-0.2222222222, 0.0000000000, 0.2222222222, 0.0000000000, 0.0000000000, 0.2222222222,
0.2222222222, 0.0000000000, 0.2222222222, 0.4444444444, 0.0000000000, 0.2222222222,
0.6666666667, 0.0000000000, 0.2222222222, 0.8888888889, 0.0000000000, 0.2222222222,
-0.8888888889, 0.2222222222, 0.2222222222, -0.6666666667, 0.2222222222, 0.2222222222,
-0.4444444444, 0.2222222222, 0.2222222222, -0.2222222222, 0.2222222222, 0.2222222222,
0.0000000000, 0.2222222222, 0.2222222222, 0.2222222222, 0.2222222222, 0.2222222222,
0.4444444444, 0.2222222222, 0.2222222222, 0.6666666667, 0.2222222222, 0.2222222222,
0.8888888889, 0.2222222222, 0.2222222222, -0.8888888889, 0.4444444444, 0.2222222222,
-0.6666666667, 0.4444444444, 0.2222222222, -0.4444444444, 0.4444444444, 0.2222222222,
-0.2222222222, 0.4444444444, 0.2222222222, 0.0000000000, 0.4444444444, 0.2222222222,
0.2222222222, 0.4444444444, 0.2222222222, 0.4444444444, 0.4444444444, 0.2222222222,
0.6666666667, 0.4444444444, 0.2222222222, 0.8888888889, 0.4444444444, 0.2222222222,
-0.8888888889, 0.6666666667, 0.2222222222, -0.6666666667, 0.6666666667, 0.2222222222,
-0.4444444444, 0.6666666667, 0.2222222222, -0.2222222222, 0.6666666667, 0.2222222222,
0.0000000000, 0.6666666667, 0.2222222222, 0.2222222222, 0.6666666667, 0.2222222222,
0.4444444444, 0.6666666667, 0.2222222222, 0.6666666667, 0.6666666667, 0.2222222222,
0.8888888889, 0.6666666667, 0.2222222222, -0.8888888889, 0.8888888889, 0.2222222222,
-0.6666666667, 0.8888888889, 0.2222222222, -0.4444444444, 0.8888888889, 0.2222222222,
-0.2222222222, 0.8888888889, 0.2222222222, 0.0000000000, 0.8888888889, 0.2222222222,
0.2222222222, 0.8888888889, 0.2222222222, 0.4444444444, 0.8888888889, 0.2222222222,
0.6666666667, 0.8888888889, 0.2222222222, 0.8888888889, 0.8888888889, 0.2222222222,
-0.8888888889, -0.8888888889, 0.4444444444, -0.6666666667, -0.8888888889, 0.4444444444,
-0.4444444444, -0.8888888889, 0.4444444444, -0.2222222222, -0.8888888889, 0.4444444444,
0.0000000000, -0.8888888889, 0.4444444444, 0.2222222222, -0.8888888889, 0.4444444444,
0.4444444444, -0.8888888889, 0.4444444444, 0.6666666667, -0.8888888889, 0.4444444444,
0.8888888889, -0.8888888889, 0.4444444444, -0.8888888889, -0.6666666667, 0.4444444444,
-0.6666666667, -0.6666666667, 0.4444444444, -0.4444444444, -0.6666666667, 0.4444444444,
-0.2222222222, -0.6666666667, 0.4444444444, 0.0000000000, -0.6666666667, 0.4444444444,
0.2222222222, -0.6666666667, 0.4444444444, 0.4444444444, -0.6666666667, 0.4444444444,
0.6666666667, -0.6666666667, 0.4444444444, 0.8888888889, -0.6666666667, 0.4444444444,
-0.8888888889, -0.4444444444, 0.4444444444, -0.6666666667, -0.4444444444, 0.4444444444,
-0.4444444444, -0.4444444444, 0.4444444444, -0.2222222222, -0.4444444444, 0.4444444444,
0.0000000000, -0.4444444444, 0.4444444444, 0.2222222222, -0.4444444444, 0.4444444444,
0.4444444444, -0.4444444444, 0.4444444444, 0.6666666667, -0.4444444444, 0.4444444444,
0.8888888889, -0.4444444444, 0.4444444444, -0.8888888889, -0.2222222222, 0.4444444444,
-0.6666666667, -0.2222222222, 0.4444444444, -0.4444444444, -0.2222222222, 0.4444444444,
-0.2222222222, -0.2222222222, 0.4444444444, 0.0000000000, -0.2222222222, 0.4444444444,
0.2222222222, -0.2222222222, 0.4444444444, 0.4444444444, -0.2222222222, 0.4444444444,
0.6666666667, -0.2222222222, 0.4444444444, 0.8888888889, -0.2222222222, 0.4444444444,
-0.8888888889, 0.0000000000, 0.4444444444, -0.6666666667, 0.0000000000, 0.4444444444,
-0.4444444444, 0.0000000000, 0.4444444444, -0.2222222222, 0.0000000000, 0.4444444444,
0.0000000000, 0.0000000000, 0.4444444444, 0.2222222222, 0.0000000000, 0.4444444444,
0.4444444444, 0.0000000000, 0.4444444444, 0.6666666667, 0.0000000000, 0.4444444444,
0.8888888889, 0.0000000000, 0.4444444444, -0.8888888889, 0.2222222222, 0.4444444444,
-0.6666666667, 0.2222222222, 0.4444444444, -0.4444444444, 0.2222222222, 0.4444444444,
-0.2222222222, 0.2222222222, 0.4444444444, 0.0000000000, 0.2222222222, 0.4444444444,
0.2222222222, 0.2222222222, 0.4444444444, 0.4444444444, 0.2222222222, 0.4444444444,
0.6666666667, 0.2222222222, 0.4444444444, 0.8888888889, 0.2222222222, 0.4444444444,
-0.8888888889, 0.4444444444, 0.4444444444, -0.6666666667, 0.4444444444, 0.4444444444,
-0.4444444444, 0.4444444444, 0.4444444444, -0.2222222222, 0.4444444444, 0.4444444444,
0.0000000000, 0.4444444444, 0.4444444444, 0.2222222222, 0.4444444444, 0.4444444444,
0.4444444444, 0.4444444444, 0.4444444444, 0.6666666667, 0.4444444444, 0.4444444444,
0.8888888889, 0.4444444444, 0.4444444444, -0.8888888889, 0.6666666667, 0.4444444444,
-0.6666666667, 0.6666666667, 0.4444444444, -0.4444444444, 0.6666666667, 0.4444444444,
-0.2222222222, 0.6666666667, 0.4444444444, 0.0000000000, 0.6666666667, 0.4444444444,
0.2222222222, 0.6666666667, 0.4444444444, 0.4444444444, 0.6666666667, 0.4444444444,
0.6666666667, 0.6666666667, 0.4444444444, 0.8888888889, 0.6666666667, 0.4444444444,
-0.8888888889, 0.8888888889, 0.4444444444, -0.6666666667, 0.8888888889, 0.4444444444,
-0.4444444444, 0.8888888889, 0.4444444444, -0.2222222222, 0.8888888889, 0.4444444444,
0.0000000000, 0.8888888889, 0.4444444444, 0.2222222222, 0.8888888889, 0.4444444444,
0.4444444444, 0.8888888889, 0.4444444444, 0.6666666667, 0.8888888889, 0.4444444444,
0.8888888889, 0.8888888889, 0.4444444444, -0.8888888889, -0.8888888889, 0.6666666667,
-0.6666666667, -0.8888888889, 0.6666666667, -0.4444444444, -0.8888888889, 0.6666666667,
-0.2222222222, -0.8888888889, 0.6666666667, 0.0000000000, -0.8888888889, 0.6666666667,
0.2222222222, -0.8888888889, 0.6666666667, 0.4444444444, -0.8888888889, 0.6666666667,
0.6666666667, -0.8888888889, 0.6666666667, 0.8888888889, -0.8888888889, 0.6666666667,
-0.8888888889, -0.6666666667, 0.6666666667, -0.6666666667, -0.6666666667, 0.6666666667,
-0.4444444444, -0.6666666667, 0.6666666667, -0.2222222222, -0.6666666667, 0.6666666667,
0.0000000000, -0.6666666667, 0.6666666667, 0.2222222222, -0.6666666667, 0.6666666667,
0.4444444444, -0.6666666667, 0.6666666667, 0.6666666667, -0.6666666667, 0.6666666667,
0.8888888889, -0.6666666667, 0.6666666667, -0.8888888889, -0.4444444444, 0.6666666667,
-0.6666666667, -0.4444444444, 0.6666666667, -0.4444444444, -0.4444444444, 0.6666666667,
-0.2222222222, -0.4444444444, 0.6666666667, 0.0000000000, -0.4444444444, 0.6666666667,
0.2222222222, -0.4444444444, 0.6666666667, 0.4444444444, -0.4444444444, 0.6666666667,
0.6666666667, -0.4444444444, 0.6666666667, 0.8888888889, -0.4444444444, 0.6666666667,
-0.8888888889, -0.2222222222, 0.6666666667, -0.6666666667, -0.2222222222, 0.6666666667,
-0.4444444444, -0.2222222222, 0.6666666667, -0.2222222222, -0.2222222222, 0.6666666667,
0.0000000000, -0.2222222222, 0.6666666667, 0.2222222222, -0.2222222222, 0.6666666667,
0.4444444444, -0.2222222222, 0.6666666667, 0.6666666667, -0.2222222222, 0.6666666667,
0.8888888889, -0.2222222222, 0.6666666667, -0.8888888889, 0.0000000000, 0.6666666667,
-0.6666666667, 0.0000000000, 0.6666666667, -0.4444444444, 0.0000000000, 0.6666666667,
-0.2222222222, 0.0000000000, 0.6666666667, 0.0000000000, 0.0000000000, 0.6666666667,
0.2222222222, 0.0000000000, 0.6666666667, 0.4444444444, 0.0000000000, 0.6666666667,
0.6666666667, 0.0000000000, 0.6666666667, 0.8888888889, 0.0000000000, 0.6666666667,
-0.8888888889, 0.2222222222, 0.6666666667, -0.6666666667, 0.2222222222, 0.6666666667,
-0.4444444444, 0.2222222222, 0.6666666667, -0.2222222222, 0.2222222222, 0.6666666667,
0.0000000000, 0.2222222222, 0.6666666667, 0.2222222222, 0.2222222222, 0.6666666667,
0.4444444444, 0.2222222222, 0.6666666667, 0.6666666667, 0.2222222222, 0.6666666667,
0.8888888889, 0.2222222222, 0.6666666667, -0.8888888889, 0.4444444444, 0.6666666667,
-0.6666666667, 0.4444444444, 0.6666666667, -0.4444444444, 0.4444444444, 0.6666666667,
-0.2222222222, 0.4444444444, 0.6666666667, 0.0000000000, 0.4444444444, 0.6666666667,
0.2222222222, 0.4444444444, 0.6666666667, 0.4444444444, 0.4444444444, 0.6666666667,
0.6666666667, 0.4444444444, 0.6666666667, 0.8888888889, 0.4444444444, 0.6666666667,
-0.8888888889, 0.6666666667, 0.6666666667, -0.6666666667, 0.6666666667, 0.6666666667,
-0.4444444444, 0.6666666667, 0.6666666667, -0.2222222222, 0.6666666667, 0.6666666667,
0.0000000000, 0.6666666667, 0.6666666667, 0.2222222222, 0.6666666667, 0.6666666667,
0.4444444444, 0.6666666667, 0.6666666667, 0.6666666667, 0.6666666667, 0.6666666667,
0.8888888889, 0.6666666667, 0.6666666667, -0.8888888889, 0.8888888889, 0.6666666667,
-0.6666666667, 0.8888888889, 0.6666666667, -0.4444444444, 0.8888888889, 0.6666666667,
-0.2222222222, 0.8888888889, 0.6666666667, 0.0000000000, 0.8888888889, 0.6666666667,
0.2222222222, 0.8888888889, 0.6666666667, 0.4444444444, 0.8888888889, 0.6666666667,
0.6666666667, 0.8888888889, 0.6666666667, 0.8888888889, 0.8888888889, 0.6666666667,
-0.8888888889, -0.8888888889, 0.8888888889, -0.6666666667, -0.8888888889, 0.8888888889,
-0.4444444444, -0.8888888889, 0.8888888889, -0.2222222222, -0.8888888889, 0.8888888889,
0.0000000000, -0.8888888889, 0.8888888889, 0.2222222222, -0.8888888889, 0.8888888889,
0.4444444444, -0.8888888889, 0.8888888889, 0.6666666667, -0.8888888889, 0.8888888889,
0.8888888889, -0.8888888889, 0.8888888889, -0.8888888889, -0.6666666667, 0.8888888889,
-0.6666666667, -0.6666666667, 0.8888888889, -0.4444444444, -0.6666666667, 0.8888888889,
-0.2222222222, -0.6666666667, 0.8888888889, 0.0000000000, -0.6666666667, 0.8888888889,
0.2222222222, -0.6666666667, 0.8888888889, 0.4444444444, -0.6666666667, 0.8888888889,
0.6666666667, -0.6666666667, 0.8888888889, 0.8888888889, -0.6666666667, 0.8888888889,
-0.8888888889, -0.4444444444, 0.8888888889, -0.6666666667, -0.4444444444, 0.8888888889,
-0.4444444444, -0.4444444444, 0.8888888889, -0.2222222222, -0.4444444444, 0.8888888889,
0.0000000000, -0.4444444444, 0.8888888889, 0.2222222222, -0.4444444444, 0.8888888889,
0.4444444444, -0.4444444444, 0.8888888889, 0.6666666667, -0.4444444444, 0.8888888889,
0.8888888889, -0.4444444444, 0.8888888889, -0.8888888889, -0.2222222222, 0.8888888889,
-0.6666666667, -0.2222222222, 0.8888888889, -0.4444444444, -0.2222222222, 0.8888888889,
-0.2222222222, -0.2222222222, 0.8888888889, 0.0000000000, -0.2222222222, 0.8888888889,
0.2222222222, -0.2222222222, 0.8888888889, 0.4444444444, -0.2222222222, 0.8888888889,
0.6666666667, -0.2222222222, 0.8888888889, 0.8888888889, -0.2222222222, 0.8888888889,
-0.8888888889, 0.0000000000, 0.8888888889, -0.6666666667, 0.0000000000, 0.8888888889,
-0.4444444444, 0.0000000000, 0.8888888889, -0.2222222222, 0.0000000000, 0.8888888889,
0.0000000000, 0.0000000000, 0.8888888889, 0.2222222222, 0.0000000000, 0.8888888889,
0.4444444444, 0.0000000000, 0.8888888889, 0.6666666667, 0.0000000000, 0.8888888889,
0.8888888889, 0.0000000000, 0.8888888889, -0.8888888889, 0.2222222222, 0.8888888889,
-0.6666666667, 0.2222222222, 0.8888888889, -0.4444444444, 0.2222222222, 0.8888888889,
-0.2222222222, 0.2222222222, 0.8888888889, 0.0000000000, 0.2222222222, 0.8888888889,
0.2222222222, 0.2222222222, 0.8888888889, 0.4444444444, 0.2222222222, 0.8888888889,
0.6666666667, 0.2222222222, 0.8888888889, 0.8888888889, 0.2222222222, 0.8888888889,
-0.8888888889, 0.4444444444, 0.8888888889, -0.6666666667, 0.4444444444, 0.8888888889,
-0.4444444444, 0.4444444444, 0.8888888889, -0.2222222222, 0.4444444444, 0.8888888889,
0.0000000000, 0.4444444444, 0.8888888889, 0.2222222222, 0.4444444444, 0.8888888889,
0.4444444444, 0.4444444444, 0.8888888889, 0.6666666667, 0.4444444444, 0.8888888889,
0.8888888889, 0.4444444444, 0.8888888889, -0.8888888889, 0.6666666667, 0.8888888889,
-0.6666666667, 0.6666666667, 0.8888888889, -0.4444444444, 0.6666666667, 0.8888888889,
-0.2222222222, 0.6666666667, 0.8888888889, 0.0000000000, 0.6666666667, 0.8888888889,
0.2222222222, 0.6666666667, 0.8888888889, 0.4444444444, 0.6666666667, 0.8888888889,
0.6666666667, 0.6666666667, 0.8888888889, 0.8888888889, 0.6666666667, 0.8888888889,
-0.8888888889, 0.8888888889, 0.8888888889, -0.6666666667, 0.8888888889, 0.8888888889,
-0.4444444444, 0.8888888889, 0.8888888889, -0.2222222222, 0.8888888889, 0.8888888889,
0.0000000000, 0.8888888889, 0.8888888889, 0.2222222222, 0.8888888889, 0.8888888889,
0.4444444444, 0.8888888889, 0.8888888889, 0.6666666667, 0.8888888889, 0.8888888889,
0.8888888889, 0.8888888889, 0.8888888889, -0.8888888889, -0.8888888889, -0.8888888889,
-0.6666666667, -0.8888888889, -0.8888888889, -0.4444444444, -0.8888888889, -0.8888888889,
-0.2222222222, -0.8888888889, -0.8888888889, 0.0000000000, -0.8888888889, -0.8888888889,
0.2222222222, -0.8888888889, -0.8888888889, 0.4444444444, -0.8888888889, -0.8888888889,
0.6666666667, -0.8888888889, -0.8888888889, 0.8888888889, -0.8888888889, -0.8888888889,
-0.8888888889, -0.6666666667, -0.8888888889, -0.6666666667, -0.6666666667, -0.8888888889,
-0.4444444444, -0.6666666667, -0.8888888889, -0.2222222222, -0.6666666667, -0.8888888889,
0.0000000000, -0.6666666667, -0.8888888889, 0.2222222222, -0.6666666667, -0.8888888889,
0.4444444444, -0.6666666667, -0.8888888889, 0.6666666667, -0.6666666667, -0.8888888889,
0.8888888889, -0.6666666667, -0.8888888889, -0.8888888889, -0.4444444444, -0.8888888889,
-0.6666666667, -0.4444444444, -0.8888888889, -0.4444444444, -0.4444444444, -0.8888888889,
-0.2222222222, -0.4444444444, -0.8888888889, 0.0000000000, -0.4444444444, -0.8888888889,
0.2222222222, -0.4444444444, -0.8888888889, 0.4444444444, -0.4444444444, -0.8888888889,
0.6666666667, -0.4444444444, -0.8888888889, 0.8888888889, -0.4444444444, -0.8888888889,
-0.8888888889, -0.2222222222, -0.8888888889, -0.6666666667, -0.2222222222, -0.8888888889,
-0.4444444444, -0.2222222222, -0.8888888889, -0.2222222222, -0.2222222222, -0.8888888889,
0.0000000000, -0.2222222222, -0.8888888889, 0.2222222222, -0.2222222222, -0.8888888889,
0.4444444444, -0.2222222222, -0.8888888889, 0.6666666667, -0.2222222222, -0.8888888889,
0.8888888889, -0.2222222222, -0.8888888889, -0.8888888889, 0.0000000000, -0.8888888889,
-0.6666666667, 0.0000000000, -0.8888888889, -0.4444444444, 0.0000000000, -0.8888888889,
-0.2222222222, 0.0000000000, -0.8888888889, 0.0000000000, 0.0000000000, -0.8888888889,
0.2222222222, 0.0000000000, -0.8888888889, 0.4444444444, 0.0000000000, -0.8888888889,
0.6666666667, 0.0000000000, -0.8888888889, 0.8888888889, 0.0000000000, -0.8888888889,
-0.8888888889, 0.2222222222, -0.8888888889, -0.6666666667, 0.2222222222, -0.8888888889,
-0.4444444444, 0.2222222222, -0.8888888889, -0.2222222222, 0.2222222222, -0.8888888889,
0.0000000000, 0.2222222222, -0.8888888889, 0.2222222222, 0.2222222222, -0.8888888889,
0.4444444444, 0.2222222222, -0.8888888889, 0.6666666667, 0.2222222222, -0.8888888889,
0.8888888889, 0.2222222222, -0.8888888889, -0.8888888889, 0.4444444444, -0.8888888889,
-0.6666666667, 0.4444444444, -0.8888888889, -0.4444444444, 0.4444444444, -0.8888888889,
-0.2222222222, 0.4444444444, -0.8888888889, 0.0000000000, 0.4444444444, -0.8888888889,
0.2222222222, 0.4444444444, -0.8888888889, 0.4444444444, 0.4444444444, -0.8888888889,
0.6666666667, 0.4444444444, -0.8888888889, 0.8888888889, 0.4444444444, -0.8888888889,
-0.8888888889, 0.6666666667, -0.8888888889, -0.6666666667, 0.6666666667, -0.8888888889,
-0.4444444444, 0.6666666667, -0.8888888889, -0.2222222222, 0.6666666667, -0.8888888889,
0.0000000000, 0.6666666667, -0.8888888889, 0.2222222222, 0.6666666667, -0.8888888889,
0.4444444444, 0.6666666667, -0.8888888889, 0.6666666667, 0.6666666667, -0.8888888889,
0.8888888889, 0.6666666667, -0.8888888889, -0.8888888889, 0.8888888889, -0.8888888889,
-0.6666666667, 0.8888888889, -0.8888888889, -0.4444444444, 0.8888888889, -0.8888888889,
-0.2222222222, 0.8888888889, -0.8888888889, 0.0000000000, 0.8888888889, -0.8888888889,
0.2222222222, 0.8888888889, -0.8888888889, 0.4444444444, 0.8888888889, -0.8888888889,
0.6666666667, 0.8888888889, -0.8888888889, 0.8888888889, 0.8888888889, -0.8888888889,
-0.8888888889, -0.8888888889, -0.6666666667, -0.6666666667, -0.8888888889, -0.6666666667,
-0.4444444444, -0.8888888889, -0.6666666667, -0.2222222222, -0.8888888889, -0.6666666667,
0.0000000000, -0.8888888889, -0.6666666667, 0.2222222222, -0.8888888889, -0.6666666667,
0.4444444444, -0.8888888889, -0.6666666667, 0.6666666667, -0.8888888889, -0.6666666667,
0.8888888889, -0.8888888889, -0.6666666667, -0.8888888889, -0.6666666667, -0.6666666667,
-0.6666666667, -0.6666666667, -0.6666666667, -0.4444444444, -0.6666666667, -0.6666666667,
-0.2222222222, -0.6666666667, -0.6666666667, 0.0000000000, -0.6666666667, -0.6666666667,
0.2222222222, -0.6666666667, -0.6666666667, 0.4444444444, -0.6666666667, -0.6666666667,
0.6666666667, -0.6666666667, -0.6666666667, 0.8888888889, -0.6666666667, -0.6666666667,
-0.8888888889, -0.4444444444, -0.6666666667, -0.6666666667, -0.4444444444, -0.6666666667,
-0.4444444444, -0.4444444444, -0.6666666667, -0.2222222222, -0.4444444444, -0.6666666667,
0.0000000000, -0.4444444444, -0.6666666667, 0.2222222222, -0.4444444444, -0.6666666667,
0.4444444444, -0.4444444444, -0.6666666667, 0.6666666667, -0.4444444444, -0.6666666667,
0.8888888889, -0.4444444444, -0.6666666667, -0.8888888889, -0.2222222222, -0.6666666667,
-0.6666666667, -0.2222222222, -0.6666666667, -0.4444444444, -0.2222222222, -0.6666666667,
-0.2222222222, -0.2222222222, -0.6666666667, 0.0000000000, -0.2222222222, -0.6666666667,
0.2222222222, -0.2222222222, -0.6666666667, 0.4444444444, -0.2222222222, -0.6666666667,
0.6666666667, -0.2222222222, -0.6666666667, 0.8888888889, -0.2222222222, -0.6666666667,
-0.8888888889, 0.0000000000, -0.6666666667, -0.6666666667, 0.0000000000, -0.6666666667,
-0.4444444444, 0.0000000000, -0.6666666667, -0.2222222222, 0.0000000000, -0.6666666667,
0.0000000000, 0.0000000000, -0.6666666667, 0.2222222222, 0.0000000000, -0.6666666667,
0.4444444444, 0.0000000000, -0.6666666667, 0.6666666667, 0.0000000000, -0.6666666667,
0.8888888889, 0.0000000000, -0.6666666667, -0.8888888889, 0.2222222222, -0.6666666667,
-0.6666666667, 0.2222222222, -0.6666666667, -0.4444444444, 0.2222222222, -0.6666666667,
-0.2222222222, 0.2222222222, -0.6666666667, 0.0000000000, 0.2222222222, -0.6666666667,
0.2222222222, 0.2222222222, -0.6666666667, 0.4444444444, 0.2222222222, -0.6666666667,
0.6666666667, 0.2222222222, -0.6666666667, 0.8888888889, 0.2222222222, -0.6666666667,
-0.8888888889, 0.4444444444, -0.6666666667, -0.6666666667, 0.4444444444, -0.6666666667,
-0.4444444444, 0.4444444444, -0.6666666667, -0.2222222222, 0.4444444444, -0.6666666667,
0.0000000000, 0.4444444444, -0.6666666667, 0.2222222222, 0.4444444444, -0.6666666667,
0.4444444444, 0.4444444444, -0.6666666667, 0.6666666667, 0.4444444444, -0.6666666667,
0.8888888889, 0.4444444444, -0.6666666667, -0.8888888889, 0.6666666667, -0.6666666667,
-0.6666666667, 0.6666666667, -0.6666666667, -0.4444444444, 0.6666666667, -0.6666666667,
-0.2222222222, 0.6666666667, -0.6666666667, 0.0000000000, 0.6666666667, -0.6666666667,
0.2222222222, 0.6666666667, -0.6666666667, 0.4444444444, 0.6666666667, -0.6666666667,
0.6666666667, 0.6666666667, -0.6666666667, 0.8888888889, 0.6666666667, -0.6666666667,
-0.8888888889, 0.8888888889, -0.6666666667, -0.6666666667, 0.8888888889, -0.6666666667,
-0.4444444444, 0.8888888889, -0.6666666667, -0.2222222222, 0.8888888889, -0.6666666667,
0.0000000000, 0.8888888889, -0.6666666667, 0.2222222222, 0.8888888889, -0.6666666667,
0.4444444444, 0.8888888889, -0.6666666667, 0.6666666667, 0.8888888889, -0.6666666667,
0.8888888889, 0.8888888889, -0.6666666667, -0.8888888889, -0.8888888889, -0.4444444444,
-0.6666666667, -0.8888888889, -0.4444444444, -0.4444444444, -0.8888888889, -0.4444444444,
-0.2222222222, -0.8888888889, -0.4444444444, 0.0000000000, -0.8888888889, -0.4444444444,
0.2222222222, -0.8888888889, -0.4444444444, 0.4444444444, -0.8888888889, -0.4444444444,
0.6666666667, -0.8888888889, -0.4444444444, 0.8888888889, -0.8888888889, -0.4444444444,
-0.8888888889, -0.6666666667, -0.4444444444, -0.6666666667, -0.6666666667, -0.4444444444,
-0.4444444444, -0.6666666667, -0.4444444444, -0.2222222222, -0.6666666667, -0.4444444444,
0.0000000000, -0.6666666667, -0.4444444444, 0.2222222222, -0.6666666667, -0.4444444444,
0.4444444444, -0.6666666667, -0.4444444444, 0.6666666667, -0.6666666667, -0.4444444444,
0.8888888889, -0.6666666667, -0.4444444444, -0.8888888889, -0.4444444444, -0.4444444444,
-0.6666666667, -0.4444444444, -0.4444444444, -0.4444444444, -0.4444444444, -0.4444444444,
-0.2222222222, -0.4444444444, -0.4444444444, 0.0000000000, -0.4444444444, -0.4444444444,
0.2222222222, -0.4444444444, -0.4444444444, 0.4444444444, -0.4444444444, -0.4444444444,
0.6666666667, -0.4444444444, -0.4444444444, 0.8888888889, -0.4444444444, -0.4444444444,
-0.8888888889, -0.2222222222, -0.4444444444, -0.6666666667, -0.2222222222, -0.4444444444,
-0.4444444444, -0.2222222222, -0.4444444444, -0.2222222222, -0.2222222222, -0.4444444444,
0.0000000000, -0.2222222222, -0.4444444444, 0.2222222222, -0.2222222222, -0.4444444444,
0.4444444444, -0.2222222222, -0.4444444444, 0.6666666667, -0.2222222222, -0.4444444444,
0.8888888889, -0.2222222222, -0.4444444444, -0.8888888889, 0.0000000000, -0.4444444444,
-0.6666666667, 0.0000000000, -0.4444444444, -0.4444444444, 0.0000000000, -0.4444444444,
-0.2222222222, 0.0000000000, -0.4444444444, 0.0000000000, 0.0000000000, -0.4444444444,
0.2222222222, 0.0000000000, -0.4444444444, 0.4444444444, 0.0000000000, -0.4444444444,
0.6666666667, 0.0000000000, -0.4444444444, 0.8888888889, 0.0000000000, -0.4444444444,
-0.8888888889, 0.2222222222, -0.4444444444, -0.6666666667, 0.2222222222, -0.4444444444,
-0.4444444444, 0.2222222222, -0.4444444444, -0.2222222222, 0.2222222222, -0.4444444444,
0.0000000000, 0.2222222222, -0.4444444444, 0.2222222222, 0.2222222222, -0.4444444444,
0.4444444444, 0.2222222222, -0.4444444444, 0.6666666667, 0.2222222222, -0.4444444444,
0.8888888889, 0.2222222222, -0.4444444444, -0.8888888889, 0.4444444444, -0.4444444444,
-0.6666666667, 0.4444444444, -0.4444444444, -0.4444444444, 0.4444444444, -0.4444444444,
-0.2222222222, 0.4444444444, -0.4444444444, 0.0000000000, 0.4444444444, -0.4444444444,
0.2222222222, 0.4444444444, -0.4444444444, 0.4444444444, 0.4444444444, -0.4444444444,
0.6666666667, 0.4444444444, -0.4444444444, 0.8888888889, 0.4444444444, -0.4444444444,
-0.8888888889, 0.6666666667, -0.4444444444, -0.6666666667, 0.6666666667, -0.4444444444,
-0.4444444444, 0.6666666667, -0.4444444444, -0.2222222222, 0.6666666667, -0.4444444444,
0.0000000000, 0.6666666667, -0.4444444444, 0.2222222222, 0.6666666667, -0.4444444444,
0.4444444444, 0.6666666667, -0.4444444444, 0.6666666667, 0.6666666667, -0.4444444444,
0.8888888889, 0.6666666667, -0.4444444444, -0.8888888889, 0.8888888889, -0.4444444444,
-0.6666666667, 0.8888888889, -0.4444444444, -0.4444444444, 0.8888888889, -0.4444444444,
-0.2222222222, 0.8888888889, -0.4444444444, 0.0000000000, 0.8888888889, -0.4444444444,
0.2222222222, 0.8888888889, -0.4444444444, 0.4444444444, 0.8888888889, -0.4444444444,
0.6666666667, 0.8888888889, -0.4444444444, 0.8888888889, 0.8888888889, -0.4444444444,
-0.8888888889, -0.8888888889, -0.2222222222, -0.6666666667, -0.8888888889, -0.2222222222,
-0.4444444444, -0.8888888889, -0.2222222222, -0.2222222222, -0.8888888889, -0.2222222222,
0.0000000000, -0.8888888889, -0.2222222222, 0.2222222222, -0.8888888889, -0.2222222222,
0.4444444444, -0.8888888889, -0.2222222222, 0.6666666667, -0.8888888889, -0.2222222222,
0.8888888889, -0.8888888889, -0.2222222222, -0.8888888889, -0.6666666667, -0.2222222222,
-0.6666666667, -0.6666666667, -0.2222222222, -0.4444444444, -0.6666666667, -0.2222222222,
-0.2222222222, -0.6666666667, -0.2222222222, 0.0000000000, -0.6666666667, -0.2222222222,
0.2222222222, -0.6666666667, -0.2222222222, 0.4444444444, -0.6666666667, -0.2222222222,
0.6666666667, -0.6666666667, -0.2222222222, 0.8888888889, -0.6666666667, -0.2222222222,
-0.8888888889, -0.4444444444, -0.2222222222, -0.6666666667, -0.4444444444, -0.2222222222,
-0.4444444444, -0.4444444444, -0.2222222222, -0.2222222222, -0.4444444444, -0.2222222222,
0.0000000000, -0.4444444444, -0.2222222222, 0.2222222222, -0.4444444444, -0.2222222222,
0.4444444444, -0.4444444444, -0.2222222222, 0.6666666667, -0.4444444444, -0.2222222222,
0.8888888889, -0.4444444444, -0.2222222222, -0.8888888889, -0.2222222222, -0.2222222222,
-0.6666666667, -0.2222222222, -0.2222222222, -0.4444444444, -0.2222222222, -0.2222222222,
-0.2222222222, -0.2222222222, -0.2222222222, 0.0000000000, -0.2222222222, -0.2222222222,
0.2222222222, -0.2222222222, -0.2222222222, 0.4444444444, -0.2222222222, -0.2222222222,
0.6666666667, -0.2222222222, -0.2222222222, 0.8888888889, -0.2222222222, -0.2222222222,
-0.8888888889, 0.0000000000, -0.2222222222, -0.6666666667, 0.0000000000, -0.2222222222,
-0.4444444444, 0.0000000000, -0.2222222222, -0.2222222222, 0.0000000000, -0.2222222222,
0.0000000000, 0.0000000000, -0.2222222222, 0.2222222222, 0.0000000000, -0.2222222222,
0.4444444444, 0.0000000000, -0.2222222222, 0.6666666667, 0.0000000000, -0.2222222222,
0.8888888889, 0.0000000000, -0.2222222222, -0.8888888889, 0.2222222222, -0.2222222222,
-0.6666666667, 0.2222222222, -0.2222222222, -0.4444444444, 0.2222222222, -0.2222222222,
-0.2222222222, 0.2222222222, -0.2222222222, 0.0000000000, 0.2222222222, -0.2222222222,
0.2222222222, 0.2222222222, -0.2222222222, 0.4444444444, 0.2222222222, -0.2222222222
};
#ifdef USE_LAYER_II_TABLES
/*
Purpose: Following tables contain dequantized samples for
each legal codeword.
Explanation: Only bit allocations 3...8 are tabled. */
// Bit_Alloc : 3
static const FLOAT requant3[] = { -0.8571429253, -0.5714285970, -0.2857142985, 0.0000000000,
0.2857142985, 0.5714285970, 0.8571429253, 1.1428571939 };
// Bit_Alloc : 4
static const FLOAT requant4[] = { -0.9333333969, -0.8000000715, -0.6666666865, -0.5333333611,
-0.4000000358, -0.2666666806, -0.1333333403, 0.0000000000,
0.1333333403, 0.2666666806, 0.4000000358, 0.5333333611,
0.6666666865, 0.8000000715, 0.9333333969, 1.0666667223 };
// Bit_Alloc : 5
static const FLOAT requant5[] = { -0.9677419066, -0.9032257795, -0.8387096524, -0.7741935253,
-0.7096773982, -0.6451612711, -0.5806451440, -0.5161290169,
-0.4516128898, -0.3870967627, -0.3225806355, -0.2580645084,
-0.1935483813, -0.1290322542, -0.0645161271, 0.0000000000,
0.0645161271, 0.1290322542, 0.1935483813, 0.2580645084,
0.3225806355, 0.3870967627, 0.4516128898, 0.5161290169,
0.5806451440, 0.6451612711, 0.7096773982, 0.7741935253,
0.8387096524, 0.9032257795, 0.9677419066, 1.0322580338 };
// Bit_Alloc : 6
static const FLOAT requant6[] = {
-0.9841270447, -0.9523810148, -0.9206349850, -0.8888889551, -0.8571429253, -0.8253968954,
-0.7936508656, -0.7619048357, -0.7301587462, -0.6984127164, -0.6666666865, -0.6349206567,
-0.6031746268, -0.5714285970, -0.5396825671, -0.5079365373, -0.4761905074, -0.4444444776,
-0.4126984477, -0.3809524179, -0.3492063582, -0.3174603283, -0.2857142985, -0.2539682686,
-0.2222222388, -0.1904762089, -0.1587301642, -0.1269841343, -0.0952381045, -0.0634920672,
-0.0317460336, 0.0000000000, 0.0317460336, 0.0634920672, 0.0952381045, 0.1269841343,
0.1587301642, 0.1904762089, 0.2222222388, 0.2539682686, 0.2857142985, 0.3174603283,
0.3492063582, 0.3809524179, 0.4126984477, 0.4444444776, 0.4761905074, 0.5079365373,
0.5396825671, 0.5714285970, 0.6031746268, 0.6349206567, 0.6666666865, 0.6984127164,
0.7301587462, 0.7619048357, 0.7936508656, 0.8253968954, 0.8571429253, 0.8888889551,
0.9206349850, 0.9523810148, 0.9841270447, 1.0158730745
};
// Bit_Alloc : 7
static const FLOAT requant7[] = {
-0.9921259880, -0.9763779640, -0.9606299400, -0.9448819160, -0.9291338325, -0.9133858085,
-0.8976377845, -0.8818897605, -0.8661417365, -0.8503937125, -0.8346456885, -0.8188976049,
-0.8031495810, -0.7874015570, -0.7716535330, -0.7559055090, -0.7401574850, -0.7244094610,
-0.7086614370, -0.6929134130, -0.6771653295, -0.6614173055, -0.6456692815, -0.6299212575,
-0.6141732335, -0.5984252095, -0.5826771855, -0.5669291019, -0.5511810780, -0.5354330540,
-0.5196850300, -0.5039370060, -0.4881889820, -0.4724409580, -0.4566929042, -0.4409448802,
-0.4251968563, -0.4094488025, -0.3937007785, -0.3779527545, -0.3622047305, -0.3464567065,
-0.3307086527, -0.3149606287, -0.2992126048, -0.2834645510, -0.2677165270, -0.2519685030,
-0.2362204790, -0.2204724401, -0.2047244012, -0.1889763772, -0.1732283533, -0.1574803144,
-0.1417322755, -0.1259842515, -0.1102362201, -0.0944881886, -0.0787401572, -0.0629921257,
-0.0472440943, -0.0314960629, -0.0157480314, 0.0000000000, 0.0157480314, 0.0314960629,
0.0472440943, 0.0629921257, 0.0787401572, 0.0944881886, 0.1102362201, 0.1259842515,
0.1417322755, 0.1574803144, 0.1732283533, 0.1889763772, 0.2047244012, 0.2204724401,
0.2362204790, 0.2519685030, 0.2677165270, 0.2834645510, 0.2992126048, 0.3149606287,
0.3307086527, 0.3464567065, 0.3622047305, 0.3779527545, 0.3937007785, 0.4094488025,
0.4251968563, 0.4409448802, 0.4566929042, 0.4724409580, 0.4881889820, 0.5039370060,
0.5196850300, 0.5354330540, 0.5511810780, 0.5669291019, 0.5826771855, 0.5984252095,
0.6141732335, 0.6299212575, 0.6456692815, 0.6614173055, 0.6771653295, 0.6929134130,
0.7086614370, 0.7244094610, 0.7401574850, 0.7559055090, 0.7716535330, 0.7874015570,
0.8031495810, 0.8188976049, 0.8346456885, 0.8503937125, 0.8661417365, 0.8818897605,
0.8976377845, 0.9133858085, 0.9291338325, 0.9448819160, 0.9606299400, 0.9763779640,
0.9921259880, 1.0078740120
};
// Bit_Alloc : 8
static const FLOAT requant8[] = {
-0.9960784912, -0.9882353544, -0.9803922176, -0.9725490808, -0.9647059441, -0.9568628073,
-0.9490196705, -0.9411765337, -0.9333333969, -0.9254902601, -0.9176471233, -0.9098039865,
-0.9019608498, -0.8941177130, -0.8862745762, -0.8784314394, -0.8705883026, -0.8627451658,
-0.8549020290, -0.8470588923, -0.8392157555, -0.8313726187, -0.8235294819, -0.8156863451,
-0.8078432083, -0.8000000715, -0.7921569347, -0.7843137980, -0.7764706612, -0.7686275244,
-0.7607843876, -0.7529412508, -0.7450980544, -0.7372549176, -0.7294117808, -0.7215686440,
-0.7137255073, -0.7058823705, -0.6980392337, -0.6901960969, -0.6823529601, -0.6745098233,
-0.6666666865, -0.6588235497, -0.6509804130, -0.6431372762, -0.6352941394, -0.6274510026,
-0.6196078658, -0.6117647290, -0.6039215922, -0.5960784554, -0.5882353187, -0.5803921819,
-0.5725490451, -0.5647059083, -0.5568627715, -0.5490196347, -0.5411764979, -0.5333333611,
-0.5254902244, -0.5176470876, -0.5098039508, -0.5019608140, -0.4941176772, -0.4862745404,
-0.4784314036, -0.4705882668, -0.4627451301, -0.4549019933, -0.4470588565, -0.4392157197,
-0.4313725829, -0.4235294461, -0.4156863093, -0.4078431726, -0.4000000358, -0.3921568990,
-0.3843137622, -0.3764706254, -0.3686274588, -0.3607843220, -0.3529411852, -0.3450980484,
-0.3372549117, -0.3294117749, -0.3215686381, -0.3137255013, -0.3058823645, -0.2980392277,
-0.2901960909, -0.2823529541, -0.2745098174, -0.2666666806, -0.2588235438, -0.2509804070,
-0.2431372702, -0.2352941334, -0.2274509966, -0.2196078598, -0.2117647231, -0.2039215863,
-0.1960784495, -0.1882353127, -0.1803921610, -0.1725490242, -0.1647058874, -0.1568627506,
-0.1490196139, -0.1411764771, -0.1333333403, -0.1254902035, -0.1176470667, -0.1098039299,
-0.1019607931, -0.0941176564, -0.0862745121, -0.0784313753, -0.0705882385, -0.0627451017,
-0.0549019650, -0.0470588282, -0.0392156877, -0.0313725509, -0.0235294141, -0.0156862754,
-0.0078431377, 0.0000000000, 0.0078431377, 0.0156862754, 0.0235294141, 0.0313725509,
0.0392156877, 0.0470588282, 0.0549019650, 0.0627451017, 0.0705882385, 0.0784313753,
0.0862745121, 0.0941176564, 0.1019607931, 0.1098039299, 0.1176470667, 0.1254902035,
0.1333333403, 0.1411764771, 0.1490196139, 0.1568627506, 0.1647058874, 0.1725490242,
0.1803921610, 0.1882353127, 0.1960784495, 0.2039215863, 0.2117647231, 0.2196078598,
0.2274509966, 0.2352941334, 0.2431372702, 0.2509804070, 0.2588235438, 0.2666666806,
0.2745098174, 0.2823529541, 0.2901960909, 0.2980392277, 0.3058823645, 0.3137255013,
0.3215686381, 0.3294117749, 0.3372549117, 0.3450980484, 0.3529411852, 0.3607843220,
0.3686274588, 0.3764706254, 0.3843137622, 0.3921568990, 0.4000000358, 0.4078431726,
0.4156863093, 0.4235294461, 0.4313725829, 0.4392157197, 0.4470588565, 0.4549019933,
0.4627451301, 0.4705882668, 0.4784314036, 0.4862745404, 0.4941176772, 0.5019608140,
0.5098039508, 0.5176470876, 0.5254902244, 0.5333333611, 0.5411764979, 0.5490196347,
0.5568627715, 0.5647059083, 0.5725490451, 0.5803921819, 0.5882353187, 0.5960784554,
0.6039215922, 0.6117647290, 0.6196078658, 0.6274510026, 0.6352941394, 0.6431372762,
0.6509804130, 0.6588235497, 0.6666666865, 0.6745098233, 0.6823529601, 0.6901960969,
0.6980392337, 0.7058823705, 0.7137255073, 0.7215686440, 0.7294117808, 0.7372549176,
0.7450980544, 0.7529412508, 0.7607843876, 0.7686275244, 0.7764706612, 0.7843137980,
0.7921569347, 0.8000000715, 0.8078432083, 0.8156863451, 0.8235294819, 0.8313726187,
0.8392157555, 0.8470588923, 0.8549020290, 0.8627451658, 0.8705883026, 0.8784314394,
0.8862745762, 0.8941177130, 0.9019608498, 0.9098039865, 0.9176471233, 0.9254902601,
0.9333333969, 0.9411765337, 0.9490196705, 0.9568628073, 0.9647059441, 0.9725490808,
0.9803922176, 0.9882353544, 0.9960784912, 1.0039216280
};
#endif /* USE_LAYER_II_TABLES */
/*
Purpose: Layer II bit allocation table for each subband (Table B.2b).
Explanation: If the bitstream uses tables B.2a or B.2b, then subband 0 is
the first element in the array. Otherwise subband 0 is the 9th
element in the array. Note that the number of subbands varies
between different bit allocation tables. */
static const BYTE Layer_II_bit_alloc[] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3,
3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2 };
/*
Purpose: Corresponding row index of each subband in table
'bits_per_codeword_idx[][]'.
Explanation: If the bitstream uses tables B.2a row index should be 1.
For table B.2b use the indices in the second row.
Tables B.2c and B.2d use the last row. Subband number is
used when indexing columns. */
static const BYTE _idx[3][30] =
{
{ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3 },
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
};
/*
Purpose: Index to table 'bits_per_codeword[]'.
Explanation: Note that table '_idx[][]' will determine the row index,
bit allocation determines the column. */
static const BYTE bits_per_codeword_idx[5][16] = {
{ 0, 1, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17 },
{ 0, 1, 2, 3, 4, 5, 6, 17, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 2, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }
};
/*
Purpose: Number of bits for each legal codeword (Table B.4 : 6th column).
Explanation: - */
static const BYTE bits_per_codeword[] = { 0, 5, 7, 3, 10, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16 };
/*
Purpose: Grouping information for each legal codeword
(Table B.4 : 4th column).
Explanation: - */
static const BYTE grouping[] = { 2, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/*
Purpose: Number of levels when grouped in 3 samples per codeword.
Explanation: - */
static const int32 nlevels[] = { 0, 3, 5, 7, 9, 15, 31, 63, 127,
255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535L };
/*
Purpose: Number of bits needed to locate MSB-bit of each legal codeword.
Explanation: Obtained from Table B.4 by counting how many bits are needed
so that the value would be equal the value in the 1st column
of the table. */
static const BYTE msb_bit[] = { 0, 0, 0, 2, 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
/*
Purpose: Table to deinterleave left and right channel of
Layer II and III.
Explanation: - */
static const BYTE deinterleave_Layer_II[2][2 * 96] = {
// no deinterleaving needed for mono channel
{ 0, 32, 64, 1, 33, 65, 2, 34, 66, 3, 35, 67, 4, 36, 68, 5, 37, 69,
6, 38, 70, 7, 39, 71, 8, 40, 72, 9, 41, 73, 10, 42, 74, 11, 43, 75,
12, 44, 76, 13, 45, 77, 14, 46, 78, 15, 47, 79, 16, 48, 80, 17, 49, 81,
18, 50, 82, 19, 51, 83, 20, 52, 84, 21, 53, 85, 22, 54, 86, 23, 55, 87,
24, 56, 88, 25, 57, 89, 26, 58, 90, 27, 59, 91, 28, 60, 92, 29, 61, 93,
30, 62, 94, 31, 63, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125,
126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161,
162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191 },
// stereo channel
{ /*
0, 96, 32, 128, 64, 160, 1, 97, 33, 129, 65, 161, 2, 98, 34, 130,
66, 162, 3, 99, 35, 131, 67, 163, 4, 100, 36, 132, 68, 164, 5, 101,
37, 133, 69, 165, 6, 102, 38, 134, 70, 166, 7, 103, 39, 135, 71, 167,
8, 104, 40, 136, 72, 168, 9, 105, 41, 137, 73, 169, 10, 106, 42, 138,
74, 170, 11, 107, 43, 139, 75, 171, 12, 108, 44, 140, 76, 172, 13, 109,
45, 141, 77, 173, 14, 110, 46, 142, 78, 174, 15, 111, 47, 143, 79, 175,
16, 112, 48, 144, 80, 176, 17, 113, 49, 145, 81, 177, 18, 114, 50, 146,
82, 178, 19, 115, 51, 147, 83, 179, 20, 116, 52, 148, 84, 180, 21, 117,
53, 149, 85, 181, 22, 118, 54, 150, 86, 182, 23, 119, 55, 151, 87, 183,
24, 120, 56, 152, 88, 184, 25, 121, 57, 153, 89, 185, 26, 122, 58, 154,
90, 186, 27, 123, 59, 155, 91, 187, 28, 124, 60, 156, 92, 188, 29, 125,
61, 157, 93, 189, 30, 126, 62, 158, 94, 190, 31, 127, 63, 159, 95, 191
*/
0, 32, 64, 96, 128, 160, 1, 33, 65, 97, 129, 161, 2, 34, 66, 98, 130, 162,
3, 35, 67, 99, 131, 163, 4, 36, 68, 100, 132, 164, 5, 37, 69, 101, 133, 165,
6, 38, 70, 102, 134, 166, 7, 39, 71, 103, 135, 167, 8, 40, 72, 104, 136, 168,
9, 41, 73, 105, 137, 169, 10, 42, 74, 106, 138, 170, 11, 43, 75, 107, 139, 171,
12, 44, 76, 108, 140, 172, 13, 45, 77, 109, 141, 173, 14, 46, 78, 110, 142, 174,
15, 47, 79, 111, 143, 175, 16, 48, 80, 112, 144, 176, 17, 49, 81, 113, 145, 177,
18, 50, 82, 114, 146, 178, 19, 51, 83, 115, 147, 179, 20, 52, 84, 116, 148, 180,
21, 53, 85, 117, 149, 181, 22, 54, 86, 118, 150, 182, 23, 55, 87, 119, 151, 183,
24, 56, 88, 120, 152, 184, 25, 57, 89, 121, 153, 185, 26, 58, 90, 122, 154, 186,
27, 59, 91, 123, 155, 187, 28, 60, 92, 124, 156, 188, 29, 61, 93, 125, 157, 189,
30, 62, 94, 126, 158, 190, 31, 63, 95, 127, 159, 191 }
};
/*
Purpose: Factor C for dequantization from Table B.4 : 2nd column.
Explanation: - */
static const FLOAT c[] = { 0.00000000000, 1.33333333333, 1.60000000000, 1.14285714286,
1.77777777777, 1.06666666666, 1.03225806452, 1.01587301587,
1.00787401575, 1.00392156863, 1.00195694716, 1.00097751711,
1.00048851979, 1.00024420024, 1.00012208522, 1.00006103888,
1.00003051851, 1.00001525902 };
/*
Purpose: Factor D for dequantization from Table B.4 : 3rd column.
Explanation: - */
static const FLOAT d[] = { 0.00000000000, 0.50000000000, 0.50000000000, 0.25000000000,
0.50000000000, 0.12500000000, 0.06250000000, 0.03125000000,
0.01562500000, 0.00781250000, 0.00390625000, 0.00195312500,
0.00097656250, 0.00048828125, 0.00024414063, 0.00012207031,
0.00006103516, 0.00003051758 };
/*
Purpose: 1 / 2^b, b = 0,...,15
Explanation: - */
static const FLOAT scaleII[] = { 0, 1. / 2, 1. / 4, 1. / 8,
1. / 16, 1. / 32, 1. / 64, 1. / 128,
1. / 256, 1. / 512, 1. / 1024, 1. / 2048,
1. / 4096, 1. / 8192, 1. / 16384, 1. / 32768L };
/**************************************************************************
Title : seek_layerII
Purpose : Reads one frame without processing the decoded parameters.
Usage : y = seek_layerII(mp)
Input : mp - MP2 stream parameters
Explanation : This function can be used to implement seeking of layer II.
Author(s) : Juha Ojanpera
*************************************************************************/
void
seek_layerII(MP_Stream *mp)
{
II_decode_bit_alloc(mp);
II_decode_scale(mp);
for (int i = 0; i < SCALE_BLOCK; i++)
II_buffer_sample(mp);
}
/**************************************************************************
Title : II_decode_bit_alloc
Purpose : Decodes the bit allocation of layer II.
Usage : II_decode_bit_alloc(mp)
Input : mp - MP2 stream parameters
Explanation : The number of bits used per subband varies from 0 to 4
as a function of subband number as dictated by the
appropriate to the given sampling frequency and bit rate.
Author(s) : Juha Ojanpera
*************************************************************************/
void
II_decode_bit_alloc(MP_Stream *mp)
{
BYTE *bit_alloc;
const BYTE *alloc_bits;
int i, temp;
auto subbands = mp->header->subbands();
// printf("subbands = %i\n", mp->header->subbands());
// Get the bit allocation scheme used in this frame.
alloc_bits = &Layer_II_bit_alloc[mp->header->GetLayer2Alloc()];
// printf("alloc_bits = %i %i \n", *alloc_bits, mp->header->GetLayer2Alloc());
i = 0;
bit_alloc = mp->frame->bit_alloc;
while (i < mp->header->jsbound() << (mp->header->channels() - 1)) {
*bit_alloc++ = (BYTE) mp->bs->getBits(*alloc_bits);
// Left and right channel use the same number of bits
// for the corresponding subband.
if (mp->header->channels() == 2)
alloc_bits += (i & 1) ? 1 : 0;
else
alloc_bits++;
i++;
}
switch (mp->header->mode()) {
// Left and right channel use the same bit allocation.
case MPG_MD_JOINT_STEREO:
i = mp->header->jsbound();
while (i < subbands) {
temp = (BYTE) mp->bs->getBits(*alloc_bits++);
*bit_alloc++ = temp;
*bit_alloc++ = temp;
i++;
}
break;
}
}
/**************************************************************************
Title : II_decode_scale
Purpose : Decodes the scalefactors of layer II.
Usage : II_decode_scale(mp)
Input : mp - MP2 stream parameters
Explanation : Each frame consists of 36 samples per subband. The 36 samples
are divided into 3 groups/parts. Each part contains therefore
12 samples per subband. Each part and subband gets a
scalefactor which can be also shared by the other parts. This
is indicated by the scalefactor selection information.
Author(s) : Juha Ojanpera
*************************************************************************/
void
II_decode_scale(MP_Stream *mp)
{
BYTE scfi_alloc[2 * SBLIMIT];
BYTE *scfi, *bit_alloc, *sf_group1, *sf_group2, *sf_group3;
int i, num_of_scfi;
int16 temp;
scfi = &scfi_alloc[0];
bit_alloc = mp->frame->bit_alloc;
num_of_scfi = mp->header->subbands() << (mp->header->channels() - 1);
// Scalefactors for group 1.
sf_group1 = mp->frame->scale_factors;
// Scalefactors for group 2.
sf_group2 = mp->frame->scale_factors + num_of_scfi;
// Scalefactors for group 3.
sf_group3 = mp->frame->scale_factors + (num_of_scfi << 1);
// Get the scalefactor selection information.
i = 0;
while (i < num_of_scfi) {
*scfi++ = (BYTE)((*bit_alloc++) ? mp->bs->getBits(2) : 4);
i++;
}
// Get the actual scalefactors for each group.
i = 0;
scfi = &scfi_alloc[0];
while (i < num_of_scfi) {
switch (*scfi++) {
case 0:
// Each group have a separate scalefactor.
*sf_group1++ = mp->bs->getBits(6);
*sf_group2++ = mp->bs->getBits(6);
*sf_group3++ = mp->bs->getBits(6);
break;
case 1:
// Groups 1 and 2 share the scalefactor.
temp = mp->bs->getBits(6);
*sf_group1++ = temp;
*sf_group2++ = temp;
// Group 3 has separate scalefactor.
*sf_group3++ = mp->bs->getBits(6);
break;
case 2:
// Same scalefactor is used in all groups.
temp = (BYTE) mp->bs->getBits(6);
*sf_group1++ = temp;
*sf_group2++ = temp;
*sf_group3++ = temp;
break;
case 3:
// Group 1 has separate scalefactor.
*sf_group1++ = mp->bs->getBits(6);
// Groups 2 and 3 share the same scalefactor.
temp = (BYTE) mp->bs->getBits(6);
*sf_group2++ = temp;
*sf_group3++ = temp;
break;
case 4:
// No scalefactor present (bit allocation is zero).
*sf_group1++ = SCALE_RANGE - 1;
*sf_group2++ = SCALE_RANGE - 1;
*sf_group3++ = SCALE_RANGE - 1;
break;
}
i++;
}
}
/**************************************************************************
Title : II_buffer_sample
Purpose : Decodes the quantized samples of layer II.
Usage : II_buffer_sample(mp)
Input : mp - MP2 stream parameters
Explanation : The samples are decoded in a method similiar to that used in
layer I, however, now there is provision for packing three
consecutive samples in a single codeword for certain
quantizers.
Author(s) : Juha Ojanpera
*************************************************************************/
void
II_buffer_sample(MP_Stream *mp)
{
const BYTE *alloc_table;
BYTE grouping_idx, *bit_alloc;
int16 *quant, temp;
int i, bits_per_sample;
quant = mp->frame->quant;
bit_alloc = mp->frame->bit_alloc;
alloc_table = &_idx[mp->header->GetLayer2TableIdx()][0];
i = 0;
while (i < mp->header->jsbound() << (mp->header->channels() - 1)) {
grouping_idx = bits_per_codeword_idx[*alloc_table][*bit_alloc];
bits_per_sample = bits_per_codeword[grouping_idx];
// Check for grouping in subband.
switch (grouping[grouping_idx]) {
case 0:
*quant++ = mp->bs->getBits(bits_per_sample);
*quant++ = mp->bs->getBits(bits_per_sample);
*quant++ = mp->bs->getBits(bits_per_sample);
break;
case 1: // bit_alloc = 3, 5, 9
*quant++ = mp->bs->getBits(bits_per_sample);
break;
case 2: // For no sample transmitted.
*quant++ = 0;
*quant++ = 0;
*quant++ = 0;
break;
}
switch (mp->header->channels()) {
case 1:
alloc_table++;
break;
case 2:
alloc_table += (i & 1) ? 1 : 0;
break;
}
bit_alloc++;
i++;
}
switch (mp->header->mode()) {
// Left and right channel share the quantized sample.
case MPG_MD_JOINT_STEREO:
i = mp->header->jsbound();
while (i < mp->header->subbands()) {
i++;
grouping_idx = bits_per_codeword_idx[*alloc_table++][*bit_alloc];
bits_per_sample = bits_per_codeword[grouping_idx];
/* check for grouping in subband */
switch (grouping[grouping_idx]) {
case 0:
temp = mp->bs->getBits(bits_per_sample);
*quant++ = temp;
*quant++ = temp;
temp = mp->bs->getBits(bits_per_sample);
*quant++ = temp;
*quant++ = temp;
temp = mp->bs->getBits(bits_per_sample);
*quant++ = temp;
*quant++ = temp;
break;
case 1: // bit_alloc = 3, 5, 9
temp = mp->bs->getBits(bits_per_sample);
*quant++ = temp;
*quant++ = temp;
break;
case 2: // For no sample transmitted.
*quant++ = 0;
*quant++ = 0;
*quant++ = 0;
*quant++ = 0;
*quant++ = 0;
*quant++ = 0;
break;
}
bit_alloc += 2;
}
break;
}
}
/**************************************************************************
Title : II_dequantize_sample
Purpose : Obtains the reconstructed samples of layer II.
Usage : II_dequantize_sample(mp)
Input : mp - MP2 stream parameters
Explanation : -
Author(s) : Juha Ojanpera
*************************************************************************/
void
II_dequantize_sample(MP_Stream *mp, BYTE *scale_factor)
{
BYTE grouping_idx, mask_idx;
const BYTE *alloc_table, *de_table;
BYTE *bit_alloc;
int16 *quant;
int i, channels, num_of_samples, mask1, mask2;
FLOAT *fraction, *rec;
const FLOAT *q_table;
FLOAT sc, sf, c_factor, d_factor;
channels = mp->header->channels() - 1;
de_table = &deinterleave_Layer_II[channels][0];
quant = mp->frame->quant;
bit_alloc = mp->frame->bit_alloc;
rec = fraction = mp->buffer->reconstructed;
/*
* Since the maximum subband it not necessarily equal to 'SBLIMIT'
* initialize the reconstructed samples to zero before dequantization.
*/
num_of_samples = (SBLIMIT << channels);
memset(rec, 0, sizeof(FLOAT) * num_of_samples * 3);
i = 0;
num_of_samples = mp->header->subbands() << channels;
alloc_table = &_idx[mp->header->GetLayer2TableIdx()][0];
while (i < num_of_samples) {
grouping_idx = bits_per_codeword_idx[*alloc_table][*bit_alloc];
mask_idx = msb_bit[grouping_idx];
mask1 = sign_mask[mask_idx];
mask2 = sample_mask[mask_idx];
sc = scaleII[mask_idx];
sf = scale_factors[*scale_factor];
c_factor = c[grouping_idx];
d_factor = d[grouping_idx];
switch (nlevels[grouping_idx]) {
case 0: // For no sample transmitted.
quant += 3;
rec = &fraction[*de_table++];
*rec = 0.0;
rec = &fraction[*de_table++];
*rec = 0.0;
rec = &fraction[*de_table++];
*rec = 0.0;
break;
case 3: // Grouping, get the samples from the pre-defined tables.
q_table = &group3_samples[3 * *quant++];
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
break;
case 5: // Grouping, get the samples from the pre-defined tables.
q_table = &group5_samples[3 * *quant++];
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
break;
case 9: // Grouping, get the samples from the pre-defined tables.
q_table = &group9_samples[3 * *quant++];
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = *q_table++;
*rec *= sf;
break;
#ifdef USE_LAYER_II_TABLES
case 7:
rec = &fraction[*de_table++];
*rec = requant3[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant3[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant3[*quant++];
*rec *= sf;
break;
case 15:
rec = &fraction[*de_table++];
*rec = requant4[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant4[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant4[*quant++];
*rec *= sf;
break;
case 31:
rec = &fraction[*de_table++];
*rec = requant5[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant5[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant5[*quant++];
*rec *= sf;
break;
case 63:
rec = &fraction[*de_table++];
*rec = requant6[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant6[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant6[*quant++];
*rec *= sf;
break;
case 127:
rec = &fraction[*de_table++];
*rec = requant7[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant7[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant7[*quant++];
*rec *= sf;
break;
case 255:
rec = &fraction[*de_table++];
*rec = requant8[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant8[*quant++];
*rec *= sf;
rec = &fraction[*de_table++];
*rec = requant8[*quant++];
*rec *= sf;
break;
#else
case 7:
case 15:
case 31:
case 63:
case 127:
case 255:
#endif /* USE_LAYER_II_TABLES */
case 511:
case 1023:
case 2047:
case 4095:
case 8191:
case 16383:
case 32767:
case 65535L: // No grouping.
rec = &fraction[*de_table++];
*rec = (*quant & mask1) ? 0.0 : -1.0;
*rec += (*quant++ & mask2) * sc;
*rec += d_factor;
*rec *= c_factor;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = (*quant & mask1) ? 0.0 : -1.0;
*rec += (*quant++ & mask2) * sc;
*rec += d_factor;
*rec *= c_factor;
*rec *= sf;
rec = &fraction[*de_table++];
*rec = (*quant & mask1) ? 0.0 : -1.0;
*rec += (*quant++ & mask2) * sc;
*rec += d_factor;
*rec *= c_factor;
*rec *= sf;
break;
}
switch (mp->header->channels()) {
case 1:
alloc_table++;
break;
case 2:
alloc_table += (i & 1) ? 1 : 0;
break;
}
i++;
bit_alloc++;
scale_factor++;
}
}
#ifdef GENERATE_TABLES
#include <math.h>
#include <stdlib.h>
#ifdef NO_GROUPING_SAMPLES
/**************************************************************************
Title : main
Purpose : Creates Layer II dequantization tables (excluding grouping)
for the specified bit allocations.
Usage : main(argc, argv)
Input : argc - number of command line arguments
argv[0] - name of executable
argv[1] - number of tables (1-6) to generate
argv[2] - name output file
Author(s) : Juha Ojanpera
*************************************************************************/
void
main(void)
{
FILE *fp;
int i, j;
int bit_allocII[] = { 3, 4, 5, 6, 7, 8 };
int C_and_D_idx[] = { 2, 4, 5, 6, 7, 8 };
int bit_alloc_len = 6;
FLOAT foo;
if (argc != 3) {
fprintf(stderr, "usage : %s <num_tables> <output_file>\n", argv[0]);
exit(EXIT_FAILURE);
}
bit_alloc_len = atoi(argv[1]);
fp = fopen(argv[2], "w");
if (fp == NULL) {
fprintf(stderr, "Unable to open file %s.\n", argv[2]);
exit(EXIT_FAILURE);
}
for (i = 0; i < bit_alloc_len; i++) {
fprintf(fp, "Bit_Alloc : %i\n", bit_allocII[i]);
for (j = 0; j < (1 << bit_allocII[i]); j++) {
foo = (j & sign_mask[bit_allocII[i] - 1]) ? 0.0 : -1.0;
foo += (j & sample_mask[bit_allocII[i] - 1]) * scaleII[bit_allocII[i] - 1];
foo += d[C_and_D_idx[i]];
foo *= c[C_and_D_idx[i]];
if (j && ((j % 5) == 0))
fprintf(fp, "\n");
fprintf(fp, "%3.10f, ", foo);
}
fprintf(fp, "\n");
}
fclose(fp);
}
#else
/**************************************************************************
Title : main
Purpose : Creates Layer II dequantization tables for grouped samples.
Usage : main(argc, argv)
Input : argc - number of command line arguments
argv[0] - name of executable
argv[1] - name output file
Author(s) : Juha Ojanpera
*************************************************************************/
void
main(void)
{
int i, j, k, c, nlevels, sample, m;
int step[] = { 3, 5, 9 };
int len[] = { 32, 128, 1024 };
int mask[] = { 2, 3, 4 };
int bit[] = { 2, 4, 8 };
double cc[] = { 1.33333333333, 1.6, 1.77777777777 };
double dd[] = { 0.5, 0.5, 0.5 };
double rec;
FILE *fp;
if (argc != 2) {
fprintf(stderr, "usage : %s <output_file>\n", argv[0]);
exit(EXIT_FAILURE);
}
fp = fopen(argv[1], "w");
if (fp == NULL) {
fprintf(stderr, "Unable to open file %s.\n", argv[1]);
exit(EXIT_FAILURE);
}
m = 0;
for (i = 2; i < 3; i++) {
nlevels = step[i];
for (j = 0; j < len[i]; j++) {
c = j;
for (k = 0; k < 3; k++) {
sample = c % nlevels;
c /= nlevels;
if (((sample >> (mask[i] - 1)) & 1) == 0)
rec = -1.0;
else
rec = 0.0;
rec += (double) (sample & ((1L << (mask[i] - 1)) - 1)) / (double) bit[i];
rec += dd[i];
rec *= cc[i];
if (m && m % 5 == 0)
fprintf(fp, "\n");
m++;
if (rec >= 0)
fprintf(fp, " %4.10f, ", rec);
else
fprintf(fp, "%4.10f, ", rec);
}
}
fprintf(fp, "\n");
}
fclose(fp);
}
#endif /* NO_GROUPING_SAMPLES */
#endif /* GENERATE_TABLES */
| 58.537265 | 95 | 0.609723 | jojanper |
c1dd57ea43bc09c641029b6f8eb85f47470e1a4f | 5,337 | hpp | C++ | src/webots/nodes/WbConnector.hpp | yjf18340/webots | 60d441c362031ab8fde120cc0cd97bdb1a31a3d5 | [
"Apache-2.0"
] | 1 | 2019-11-13T08:12:02.000Z | 2019-11-13T08:12:02.000Z | src/webots/nodes/WbConnector.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | null | null | null | src/webots/nodes/WbConnector.hpp | chinakwy/webots | 7c35a359848bafe81fe0229ac2ed587528f4c73e | [
"Apache-2.0"
] | 1 | 2020-09-25T02:01:45.000Z | 2020-09-25T02:01:45.000Z | // Copyright 1996-2019 Cyberbotics 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.
#ifndef WB_CONNECTOR_HPP
#define WB_CONNECTOR_HPP
#include "WbSolidDevice.hpp"
class WbSensor;
class WbVector3;
typedef double dQuaternion[4];
struct WrRenderable;
struct WrMaterial;
struct WrStaticMesh;
struct WrTransform;
class WbConnector : public WbSolidDevice {
Q_OBJECT
public:
// constructors and destructor
explicit WbConnector(WbTokenizer *tokenizer = NULL);
WbConnector(const WbConnector &other);
explicit WbConnector(const WbNode &other);
virtual ~WbConnector();
// reimplemented public functions
int nodeType() const override { return WB_NODE_CONNECTOR; }
void preFinalize() override;
void postFinalize() override;
void handleMessage(QDataStream &stream) override;
void writeAnswer(QDataStream &stream) override;
void writeConfigure(QDataStream &) override;
void createWrenObjects() override;
void prePhysicsStep(double ms) override;
bool refreshSensorIfNeeded() override;
void reset() override;
void save() override;
enum FaceType { UNKNOWN, SYMMETRIC, ACTIVE, PASSIVE };
FaceType faceType() const { return mFaceType; }
// interface with auto-assembly mechanism
static bool isAllowingMouseMotion();
static void solidHasMoved(WbSolid *solid);
private:
// fields
WbSFString *mType; // connection type "symmetric", "active" or "passive"
WbSFBool *mIsLocked; // current locked state
WbSFBool *mAutoLock; // locks automatically in case of presence (but only when "isLocked")
WbSFBool *mUnilateralLock; // for "symmetric" type only: enable unilateral locking
WbSFBool *mUnilateralUnlock; // for "symmetric" type only: enable unilateral unlocking
WbSFDouble *mDistanceTolerance; // acceptable error in the distance between both Connectors
WbSFDouble *mAxisTolerance; // acceptable error angle between the two normals vectors
WbSFDouble *mRotationTolerance; // acceptable error in rotation angle
WbSFInt *mNumberOfRotations; // number of possible docking rotations
WbSFBool *mSnap; // should automatically snap with peer connector when locked
WbSFDouble *mTensileStrength; // max pull force that the connector can withstand without breaking (Newtons)
WbSFDouble *mShearStrength; // max shear force that the connector can withstand without breaking (Newtons)
// other stuff
FaceType mFaceType; // UNKNOWN, SYMMETRIC, ACTIVE or PASSIVE
double mMinDist2; // squared distanceTolerance
dJointID mFixedJoint; // ODE joint that does the connection
WbConnector *mPeer; // peer connector or NULL
bool mStartup; // do once flag
WbSensor *mSensor; // presence sensor
int mValue;
bool mIsJointInversed;
bool mIsInitiallyLocked;
WrTransform *mTransform;
WrTransform *mAxesTransform;
WrTransform *mRotationsTransform;
WrRenderable *mAxisRenderable[2];
WrRenderable *mRotationsRenderable;
WrMaterial *mMaterial[3];
WrStaticMesh *mAxisMesh[2];
WrStaticMesh *mRotationsMesh;
WbConnector &operator=(const WbConnector &); // non copyable
WbNode *clone() const override { return new WbConnector(*this); }
bool isReadyToAttachTo(const WbConnector *other) const;
void attachTo(WbConnector *other);
void detachFromPeer();
void createFixedJoint(WbConnector *other);
void destroyFixedJoint();
void lock();
void unlock();
void computeValue();
WbConnector *detectPresence() const;
bool isCompatibleWith(const WbConnector *other) const;
double getDistance2(const WbConnector *other) const;
bool isAlignedWith(const WbConnector *other) const;
bool isZAlignedWith(const WbConnector *other) const;
bool isYAlignedWith(const WbConnector *other) const;
void detachIfForceExceedStrength();
double findClosestRotationalAlignment(double alpha) const;
void snapZAxes(WbConnector *other, dQuaternion q);
void snapOrigins(WbConnector *other);
void snapRotation(WbConnector *other, const WbVector3 &y1, const WbVector3 &y2);
void rotateBodies(WbConnector *other, const dQuaternion q);
void getOriginInWorldCoordinates(double out[3]) const;
void snapNow(WbConnector *other);
double getEffectiveTensileStrength() const;
double getEffectiveShearStrength() const;
void init();
void hasMoved();
void assembleWith(WbConnector *other);
void assembleAxes(WbConnector *other);
void applyOptionalRenderingToWren();
void deleteWrenObjects();
private slots:
void updateType();
void updateIsLocked();
void updateNumberOfRotations();
void updateDistanceTolerance();
void updateAxisTolerance();
void updateRotationTolerance();
void updateTensileStrength();
void updateShearStrength();
void updateLineScale() override;
void updateOptionalRendering(int option);
};
#endif
| 36.806897 | 113 | 0.753794 | yjf18340 |
c1df72113b58732f01bd47e8eb6307510913a3db | 3,857 | cpp | C++ | plugins/logging/logging.cpp | rpastrana/HPCC-Platform | 489454bd326ed6a39228c81f5d837c276724c022 | [
"Apache-2.0"
] | null | null | null | plugins/logging/logging.cpp | rpastrana/HPCC-Platform | 489454bd326ed6a39228c81f5d837c276724c022 | [
"Apache-2.0"
] | null | null | null | plugins/logging/logging.cpp | rpastrana/HPCC-Platform | 489454bd326ed6a39228c81f5d837c276724c022 | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
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 <time.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "logging.hpp"
#include "jlog.hpp"
#define LOGGING_VERSION "LOGGING 1.0.1"
static const char * compatibleVersions[] = {
"LOGGING 1.0.0 [66aec3fb4911ceda247c99d6a2a5944c]", // linux version
LOGGING_VERSION,
NULL };
static const char * EclDefinition =
"export Logging := SERVICE : time\n"
" dbglog(const string src) : c,action,entrypoint='logDbgLog'; \n"
" addWorkunitInformation(const varstring txt, unsigned code=0, unsigned severity=0, const varstring source='user') : ctxmethod,action,entrypoint='addWuException'; \n"
" addWorkunitWarning(const varstring txt, unsigned code=0, unsigned severity=1, const varstring source='user') : ctxmethod,action,entrypoint='addWuException'; \n"
" addWorkunitError(const varstring txt, unsigned code=0, unsigned severity=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuException'; \n"
" addWorkunitInformationEx(const varstring txt, unsigned code=0, unsigned severity=0, unsigned audience=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuExceptionEx'; \n"
" addWorkunitWarningEx(const varstring txt, unsigned code=0, unsigned severity=1, unsigned audience=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuExceptionEx'; \n"
" addWorkunitErrorEx(const varstring txt, unsigned code=0, unsigned severity=2, unsigned audience=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuExceptionEx'; \n"
" varstring getGlobalId() : c,context,entrypoint='logGetGlobalId'; \n"
" varstring getLocalId() : c,context,entrypoint='logGetLocalId'; \n"
" varstring getCallerId() : c,context,entrypoint='logGetCallerId'; \n"
"END;";
LOGGING_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
{
if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
{
ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
pbx->compatibleVersions = compatibleVersions;
}
else if (pb->size != sizeof(ECLPluginDefinitionBlock))
return false;
pb->magicVersion = PLUGIN_VERSION;
pb->version = LOGGING_VERSION;
pb->moduleName = "lib_logging";
pb->ECL = EclDefinition;
pb->flags = PLUGIN_IMPLICIT_MODULE;
pb->description = "Logging library";
return true;
}
//-------------------------------------------------------------------------------------------------------------------------------------------
LOGGING_API void LOGGING_CALL logDbgLog(unsigned srcLen, const char * src)
{
DBGLOG("%.*s", srcLen, src);
}
LOGGING_API char * LOGGING_CALL logGetGlobalId(ICodeContext *ctx)
{
StringBuffer ret(ctx->queryContextLogger().queryGlobalId());
return ret.detach();
}
LOGGING_API char * LOGGING_CALL logGetLocalId(ICodeContext *ctx)
{
StringBuffer ret(ctx->queryContextLogger().queryLocalId());
return ret.detach();
}
LOGGING_API char * LOGGING_CALL logGetCallerId(ICodeContext *ctx)
{
StringBuffer ret(ctx->queryContextLogger().queryCallerId());
return ret.detach();
}
| 44.333333 | 192 | 0.681618 | rpastrana |
c1e2189d6678fd41854114655b875bbc1e69a708 | 6,916 | cc | C++ | media/cdm/cbcs_decryptor.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | media/cdm/cbcs_decryptor.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | media/cdm/cbcs_decryptor.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2018 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 "media/cdm/cbcs_decryptor.h"
#include <stdint.h>
#include <algorithm>
#include <string>
#include <vector>
#include "base/containers/span.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/checked_math.h"
#include "crypto/symmetric_key.h"
#include "media/base/decoder_buffer.h"
#include "media/base/decrypt_config.h"
#include "media/base/encryption_pattern.h"
#include "media/base/subsample_entry.h"
#include "media/cdm/aes_cbc_crypto.h"
namespace media {
namespace {
constexpr size_t kAesBlockSizeInBytes = 16;
// Decrypts |input_data| into |output_data|, using the pattern specified in
// |pattern|. |pattern| only applies to full blocks. Any partial block at
// the end is considered unencrypted. |output_data| must have enough room to
// hold |input_data|.size() bytes.
bool DecryptWithPattern(const crypto::SymmetricKey& key,
base::span<const uint8_t> iv,
const EncryptionPattern& pattern,
base::span<const uint8_t> input_data,
uint8_t* output_data) {
// The AES_CBC decryption is reset for each subsample.
AesCbcCrypto aes_cbc_crypto;
if (!aes_cbc_crypto.Initialize(key, iv))
return false;
// |total_blocks| is the number of blocks in the buffer, ignoring any
// partial block at the end. |remaining_bytes| is the number of bytes
// in the partial block at the end of the buffer, if any.
size_t total_blocks = input_data.size_bytes() / kAesBlockSizeInBytes;
size_t remaining_bytes = input_data.size_bytes() % kAesBlockSizeInBytes;
size_t crypt_byte_block =
base::strict_cast<size_t>(pattern.crypt_byte_block());
size_t skip_byte_block = base::strict_cast<size_t>(pattern.skip_byte_block());
// |crypt_byte_block| and |skip_byte_block| come from 4 bit values, so fail
// if these are too large.
if (crypt_byte_block >= 16 || skip_byte_block >= 16)
return false;
if (crypt_byte_block == 0 && skip_byte_block == 0) {
// From ISO/IEC 23001-7:2016(E), section 9.6.1:
// "When the fields default_crypt_byte_block and default_skip_byte_block
// in a version 1 Track Encryption Box ('tenc') are non-zero numbers,
// pattern encryption SHALL be applied."
// So for the pattern 0:0, assume that all blocks are encrypted.
crypt_byte_block = total_blocks;
}
// Apply the pattern to |input_data|.
// Example (using Pattern(2,3), Ex is encrypted, Ux unencrypted)
// input_data: |E1|E2|U3|U4|U5|E6|E7|U8|U9|U10|E11|
// We must decrypt 2 blocks, then simply copy the next 3 blocks, and
// repeat until the end. Note that the input does not have to contain
// a full pattern at the end (although see the comment below).
size_t blocks_processed = 0;
const uint8_t* src = input_data.data();
uint8_t* dest = output_data;
bool is_encrypted_blocks = false;
while (blocks_processed < total_blocks) {
is_encrypted_blocks = !is_encrypted_blocks;
size_t blocks_to_process =
std::min(is_encrypted_blocks ? crypt_byte_block : skip_byte_block,
total_blocks - blocks_processed);
if (blocks_to_process == 0)
continue;
size_t bytes_to_process = blocks_to_process * kAesBlockSizeInBytes;
// From ISO/IEC 23001-7:2016(E), section 9.6.1:
// "If the last Block pattern in a Subsample is incomplete, the partial
// pattern SHALL be followed until truncated by the BytesOfProtectedData
// size and any partial crypt_byte_block SHALL remain unencrypted."
// So if the last Block pattern is incomplete, it needs to have at least
// |crypt_byte_block| blocks to be considered encrypted. If it doesn't,
// it is treated as unencrypted and simply copied over.
if (is_encrypted_blocks && blocks_to_process == crypt_byte_block) {
if (!aes_cbc_crypto.Decrypt(base::make_span(src, bytes_to_process),
dest)) {
return false;
}
} else {
memcpy(dest, src, bytes_to_process);
}
blocks_processed += blocks_to_process;
src += bytes_to_process;
dest += bytes_to_process;
}
// Any partial block data remaining in this subsample is considered
// unencrypted so simply copy it into |dest|.
if (remaining_bytes > 0)
memcpy(dest, src, remaining_bytes);
return true;
}
} // namespace
scoped_refptr<DecoderBuffer> DecryptCbcsBuffer(
const DecoderBuffer& input,
const crypto::SymmetricKey& key) {
size_t sample_size = input.data_size();
DCHECK(sample_size) << "No data to decrypt.";
const DecryptConfig* decrypt_config = input.decrypt_config();
DCHECK(decrypt_config) << "No need to call Decrypt() on unencrypted buffer.";
DCHECK_EQ(EncryptionMode::kCbcs, decrypt_config->encryption_mode());
DCHECK(decrypt_config->HasPattern());
const EncryptionPattern pattern =
decrypt_config->encryption_pattern().value();
// Decrypted data will be the same size as |input| size.
auto buffer = base::MakeRefCounted<DecoderBuffer>(sample_size);
uint8_t* output_data = buffer->writable_data();
buffer->set_timestamp(input.timestamp());
buffer->set_duration(input.duration());
buffer->set_is_key_frame(input.is_key_frame());
buffer->CopySideDataFrom(input.side_data(), input.side_data_size());
const std::vector<SubsampleEntry>& subsamples = decrypt_config->subsamples();
if (subsamples.empty()) {
// Assume the whole buffer is encrypted.
return DecryptWithPattern(
key, base::as_bytes(base::make_span(decrypt_config->iv())),
pattern, base::make_span(input.data(), sample_size), output_data)
? buffer
: nullptr;
}
if (!VerifySubsamplesMatchSize(subsamples, sample_size)) {
DVLOG(1) << "Subsample sizes do not equal input size";
return nullptr;
}
const uint8_t* src = input.data();
uint8_t* dest = output_data;
for (const auto& subsample : subsamples) {
if (subsample.clear_bytes) {
DVLOG(4) << "Copying clear_bytes: " << subsample.clear_bytes;
memcpy(dest, src, subsample.clear_bytes);
src += subsample.clear_bytes;
dest += subsample.clear_bytes;
}
if (subsample.cypher_bytes) {
DVLOG(4) << "Processing cypher_bytes: " << subsample.cypher_bytes
<< ", pattern(" << pattern.crypt_byte_block() << ","
<< pattern.skip_byte_block() << ")";
if (!DecryptWithPattern(
key, base::as_bytes(base::make_span(decrypt_config->iv())),
pattern, base::make_span(src, subsample.cypher_bytes), dest)) {
return nullptr;
}
src += subsample.cypher_bytes;
dest += subsample.cypher_bytes;
}
}
return buffer;
}
} // namespace media
| 37.383784 | 80 | 0.691296 | zipated |
c1e40a0ff91577b0b279fbd5a76a1932fb55a497 | 2,277 | hpp | C++ | cppcache/src/StructSetImpl.hpp | mcmellawatt/geode-native | 53315985c4386e6781473c5713d638c8139e3e8e | [
"Apache-2.0"
] | null | null | null | cppcache/src/StructSetImpl.hpp | mcmellawatt/geode-native | 53315985c4386e6781473c5713d638c8139e3e8e | [
"Apache-2.0"
] | null | null | null | cppcache/src/StructSetImpl.hpp | mcmellawatt/geode-native | 53315985c4386e6781473c5713d638c8139e3e8e | [
"Apache-2.0"
] | null | null | null | #pragma once
#ifndef GEODE_STRUCTSETIMPL_H_
#define GEODE_STRUCTSETIMPL_H_
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <geode/internal/geode_globals.hpp>
#include <geode/StructSet.hpp>
#include <geode/Struct.hpp>
#include <geode/CacheableBuiltins.hpp>
#include <geode/SelectResultsIterator.hpp>
#include <string>
#include <map>
/**
* @file
*/
namespace apache {
namespace geode {
namespace client {
class APACHE_GEODE_EXPORT StructSetImpl
: public StructSet,
public std::enable_shared_from_this<StructSetImpl> {
public:
StructSetImpl(const std::shared_ptr<CacheableVector>& values,
const std::vector<std::string>& fieldNames);
bool isModifiable() const override;
size_t size() const override;
const std::shared_ptr<Serializable> operator[](size_t index) const override;
size_t getFieldIndex(const std::string& fieldname) override;
const std::string& getFieldName(int32_t index) override;
SelectResultsIterator getIterator() override;
/** Get an iterator pointing to the start of vector. */
virtual SelectResults::Iterator begin() const override;
/** Get an iterator pointing to the end of vector. */
virtual SelectResults::Iterator end() const override;
~StructSetImpl() noexcept override {}
private:
std::shared_ptr<CacheableVector> m_structVector;
std::map<std::string, int32_t> m_fieldNameIndexMap;
size_t m_nextIndex;
};
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_STRUCTSETIMPL_H_
| 28.111111 | 78 | 0.748353 | mcmellawatt |
c1e5064a0ad04d93a1763ea19ab0b1e454b7e797 | 6,049 | cpp | C++ | 01_Develop/libXMM3G/Source/M3GKeyframe.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2017-08-03T07:15:00.000Z | 2018-06-18T10:32:53.000Z | 01_Develop/libXMM3G/Source/M3GKeyframe.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | null | null | null | 01_Develop/libXMM3G/Source/M3GKeyframe.cpp | mcodegeeks/OpenKODE-Framework | d4382d781da7f488a0e7667362a89e8e389468dd | [
"MIT"
] | 2 | 2019-03-04T22:57:42.000Z | 2020-03-06T01:32:26.000Z | /* --------------------------------------------------------------------------
*
* File M3GKeyframe.cpp
* Author Y.H Mun
*
* --------------------------------------------------------------------------
*
* Copyright (C) 2010 UEDA.Takashi
* Copyright (C) 2010-2012 XMSoft. All rights reserved.
*
* Contact Email: xmsoft77@gmail.com
*
* --------------------------------------------------------------------------
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* -------------------------------------------------------------------------- */
#include "M3GInternal.h"
M3GKeyframe::M3GKeyframe ( KDvoid )
: m_nTime ( -1 )
, m_pValue ( KD_NULL )
{
}
M3GKeyframe::M3GKeyframe ( KDint time, KDfloat* value )
: m_nTime ( time )
, m_pValue ( value )
{
}
M3GKeyframe::~M3GKeyframe ( KDvoid )
{
}
KDvoid m3gStep ( KDfloat s, const M3GKeyframe& k0, const M3GKeyframe& k1, KDint componentCount, KDfloat* value )
{
if ( value == KD_NULL )
{
M3GException ( "NullPointerException", __FUNCTION__, "Value is NULL." );
}
if ( s < 0 || s > 1 )
{
M3GException ( "IllegalArgumentException", __FUNCTION__, "S is invalid, s = %f.", s );
}
for ( KDint i = 0; i < componentCount; i++ )
{
value [ i ] = ( s < 1 ) ? k0.m_pValue [ i ] : k1.m_pValue [ i ];
}
}
KDvoid m3gLinear ( KDfloat s, const M3GKeyframe& k0, const M3GKeyframe& k1, KDint componentCount, KDfloat* value )
{
if ( value == KD_NULL )
{
M3GException ( "NullPointerException", __FUNCTION__, "Value is NULL." );
}
if ( s < 0 || s > 1 )
{
M3GException ( "IllegalArgumentException", __FUNCTION__, "S is invalid, s = %f.", s );
}
for ( KDint i = 0; i < componentCount; i++ )
{
value [ i ] = k0.m_pValue [ i ] * ( 1 - s ) + k1.m_pValue [ i ] * ( s );
}
}
KDvoid m3gSlerp ( KDfloat s, const M3GKeyframe& k0, const M3GKeyframe& k1, KDint componentCount, KDfloat* value )
{
if ( value == KD_NULL )
{
M3GException ( "NullPointerException", __FUNCTION__, "Value is NULL." );
}
if ( s < 0 || s > 1 )
{
M3GException ( "IllegalArgumentException", __FUNCTION__, "S is invalid, s = %f.", s );
}
if ( componentCount != 4 )
{
M3GException ( "IllegalArgumentException", __FUNCTION__, "Component count must be 4, count = %d.", componentCount );
}
M3GQuaternion q0, q1, q2;
q0.set ( k0.m_pValue[0], k0.m_pValue[1], k0.m_pValue[2], k0.m_pValue[3] );
q1.set ( k1.m_pValue[0], k1.m_pValue[1], k1.m_pValue[2], k1.m_pValue[3] );
q2 = m3gSlerp ( q0, q1, s );
value[0] = q2.x;
value[1] = q2.y;
value[2] = q2.z;
value[3] = q2.w;
}
KDvoid m3gSpline ( KDfloat s, const M3GKeyframe& k0, const M3GKeyframe& k1, const M3GKeyframe& k2, const M3GKeyframe& k3, KDint componentCount, KDfloat* value )
{
if ( value == KD_NULL )
{
M3GException ( "NullPointerException", __FUNCTION__, "Value is NULL." );
}
if ( s < 0 || s > 1 )
{
M3GException ( "IllegalArgumentException", __FUNCTION__, "S is invalid, s = %f.", s );
}
KDfloat sh0 = 2*s*s*s - 3*s*s + 1;
KDfloat sh1 = -2*s*s*s + 3*s*s;
KDfloat sh2 = s*s*s - 2*s*s + s;
KDfloat sh3 = s*s*s - s*s;
for ( KDint i = 0; i < componentCount; i++ )
{
KDfloat tan1 = ( k0.m_nTime == -1 ) ? 0 : (k2.m_nTime - k1.m_nTime) / (KDfloat)( k2.m_nTime - k0.m_nTime ) * ( k2.m_pValue[i] - k0.m_pValue[i] );
KDfloat tan2 = ( k3.m_nTime == -1 ) ? 0 : (k2.m_nTime - k1.m_nTime) / (KDfloat)( k3.m_nTime - k1.m_nTime ) * ( k3.m_pValue[i] - k1.m_pValue[i] );
value[i] = sh0*k1.m_pValue[i] + sh1*k2.m_pValue[i] + sh2*tan1 + sh3*tan2;
}
}
KDvoid m3gSquad ( KDfloat s, const M3GKeyframe& k0, const M3GKeyframe& k1, const M3GKeyframe& k2, const M3GKeyframe& k3, KDint componentCount, KDfloat* value )
{
if ( value == KD_NULL )
{
M3GException ( "NullPointerException", __FUNCTION__, "Value is NULL." );
}
if ( s < 0 || s > 1 )
{
M3GException ( "IllegalArgumentException", __FUNCTION__, "S is invalid, s = %f.", s );
}
if ( componentCount != 4 )
{
M3GException ( "IllegalArgumentException", __FUNCTION__, "Component count must be 4, count = %d.", componentCount );
}
M3GQuaternion q0, q1, q2, q3;
if ( k0.m_nTime == -1 )
{
q0.set ( k1.m_pValue[0], k1.m_pValue[1], k1.m_pValue[2], k1.m_pValue[3] );
}
else
{
q0.set ( k0.m_pValue[0], k0.m_pValue[1], k0.m_pValue[2], k0.m_pValue[3] );
}
q1.set ( k1.m_pValue[0], k1.m_pValue[1], k1.m_pValue[2], k1.m_pValue[3] );
q2.set ( k2.m_pValue[0], k2.m_pValue[1], k2.m_pValue[2], k2.m_pValue[3] );
if ( k3.m_nTime == -1 )
{
q3.set ( k2.m_pValue[0], k2.m_pValue[1], k2.m_pValue[2], k2.m_pValue[3] );
}
else
{
q3.set ( k3.m_pValue[0], k3.m_pValue[1], k3.m_pValue[2], k3.m_pValue[3] );
}
KDfloat t0, t1, t2, t3;
t0 = (KDfloat) ( ( k0.m_nTime == -1 ) ? k1.m_nTime : k0.m_nTime );
t1 = (KDfloat) ( k1.m_nTime );
t2 = (KDfloat) ( k2.m_nTime );
t3 = (KDfloat) ( ( k3.m_nTime == -1 ) ? k2.m_nTime : k3.m_nTime );
M3GQuaternion q4 = m3gSquad ( q0, q1, q2, q3, t0, t1, t2, t3, s );
value[0] = q4.x;
value[1] = q4.y;
value[2] = q4.z;
value[3] = q4.w;
}
| 30.396985 | 160 | 0.564887 | mcodegeeks |
c1e6b68cfd2a5b1b7865dc38bb4c3d86c6f7081c | 15,578 | cpp | C++ | src/blockchain/blockchain_channel.cpp | gcbpay/R9-VRBcoinShares | 2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4 | [
"Unlicense"
] | 2 | 2016-10-21T22:54:50.000Z | 2017-11-08T07:06:46.000Z | src/blockchain/blockchain_channel.cpp | gcbpay/R9-VRBcoinShares | 2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4 | [
"Unlicense"
] | 7 | 2016-10-23T12:26:43.000Z | 2017-09-01T09:35:28.000Z | src/blockchain/blockchain_channel.cpp | gcbpay/R9-VRBcoinShares | 2b77f7a77b9254e20250cdcd99c7a289fd0c3ca4 | [
"Unlicense"
] | null | null | null | #include <bts/blockchain/blockchain_channel.hpp>
#include <bts/blockchain/blockchain_db.hpp>
#include <bts/blockchain/blockchain_messages.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/log/logger.hpp>
#include <map>
namespace bts { namespace blockchain {
using namespace network;
namespace detail
{
/**
* Blockchain Data Associated with each connection.
*/
class chan_data : public network::channel_data
{
public:
std::unordered_set<uint160> known_trx_inv;
std::unordered_set<fc::sha224> known_block_inv;
// fetches for which we have not yet received a reply...
// TODO: add a timestamp so we can time it out properly....
// Any connection that pushes data we didn't request is
// punished...
std::unordered_set<uint160> requested_trxs;
std::unordered_set<fc::sha224> requested_blocks;
// only one request at a time, null hash means nothing pending
fc::sha224 requested_full_block;
fc::sha224 requested_trx_block;
};
/**
* Tracks the trx indexes that we have not yet downloaded.
*/
struct block_download_state
{
std::unordered_map<uint160,uint16_t> missing_trx_idx;
full_block full_blk;
std::vector<signed_transaction> trxs;
};
class channel_impl : public bts::network::channel
{
public:
bts::peer::peer_channel_ptr _peers;
/* used to quickly filter out / prioritize trxs */
std::map<fc::time_point, uint160> _trx_time_index;
/** validated transactions that are sent out with get inv msgs */
std::unordered_map<uint160,signed_transaction> _pending_trx;
// full blocks that are awaiting verification, these should not be forwarded
std::unordered_map<fc::sha224,full_block> _pending_full_blocks;
// full blocks with their trxs as they are downloaded, these should not be forwarded
std::unordered_map<fc::sha224,trx_block> _pending_trx_blocks;
network::channel_id _chan_id;
blockchain_db_ptr _db;
channel_delegate* _del;
block_download_state _block_download;
/**
* When in the course of processing transactions we come across an invalid trx, store
* it here so we can quickly discard these trx or blocks that contain them. This should
* be cleared every time a block is successfully added.
*/
std::unordered_set<uint160> _recently_invalid_trx;
std::unordered_set<uint160> _trxs_pending_fetch;
std::unordered_set<fc::sha224> _blocks_pending_fetch;
std::vector<signed_transaction> _verify_queue;
chan_data& get_channel_data( const connection_ptr& c )
{
auto cd = c->get_channel_data( _chan_id );
if( !cd )
{
cd = std::make_shared<chan_data>();
c->set_channel_data( _chan_id, cd );
}
chan_data& cdat = cd->as<chan_data>();
return cdat;
}
void attempt_push_download_block()
{ try {
_db->push_block( trx_block( _block_download.full_blk, std::move( _block_download.trxs) ) );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
virtual void handle_subscribe( const connection_ptr& c )
{
get_channel_data(c); // creates it...
// request_latest_blocks();
}
virtual void handle_unsubscribe( const connection_ptr& c )
{
c->set_channel_data( _chan_id, nullptr );
}
virtual void handle_message( const connection_ptr& c, const bts::network::message& m )
{
try {
chan_data& cdat = get_channel_data(c);
ilog( "${msg_type}", ("msg_type", (blockchain::message_type)m.msg_type ) );
switch( (blockchain::message_type)m.msg_type )
{
case trx_inv_msg:
handle_trx_inv( c, cdat, m.as<trx_inv_message>() );
break;
case get_trx_inv_msg:
handle_get_trx_inv( c, cdat, m.as<get_trx_inv_message>() );
break;
case block_inv_msg:
handle_block_inv( c, cdat, m.as<block_inv_message>() );
break;
case get_block_inv_msg:
handle_get_block_inv( c, cdat, m.as<get_block_inv_message>() );
break;
case get_trxs_msg:
handle_get_trxs( c, cdat, m.as<get_trxs_message>() );
break;
case get_full_block_msg:
handle_get_full_block( c, cdat, m.as<get_full_block_message>() );
break;
case get_trx_block_msg:
handle_get_trx_block( c, cdat, m.as<get_trx_block_message>() );
break;
case trxs_msg:
handle_trxs( c, cdat, m.as<trxs_message>() );
break;
case full_block_msg:
handle_full_block( c, cdat, m.as<full_block_message>() );
break;
case trx_block_msg:
handle_trx_block( c, cdat, m.as<trx_block_message>() );
break;
default:
// TODO: figure out how to document this / punish the connection that sent us this
// message.
wlog( "unknown blockchain message type ${t}", ("t",uint64_t(m.msg_type)) );
}
}
catch ( const fc::exception& e )
{
wlog( "exception thrown while handling message\n${e}", ("e", e.to_detail_string() ) );
// TODO: punish the connection in some manner
}
}
/**
* @note inv_msg is passed by value so move semantics can be used.
*/
void handle_trx_inv( const connection_ptr& c, chan_data& cdat, trx_inv_message msg )
{ try {
for( auto itr = msg.items.begin(); itr != msg.items.end(); ++itr )
{
if( !cdat.known_trx_inv.insert( *itr ).second )
{
wlog( "received inventory item more than once from the same connection\n",
("item", *itr) );
// TODO: why is this connection sending things multiple times... punish it
}
_trxs_pending_fetch.insert( *itr );
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_get_trx_inv( const connection_ptr& c, chan_data& cdat, get_trx_inv_message msg )
{ try {
// TODO: only allow this request once every couple of minutes to prevent flood attacks
// TODO: make sure these inventory items are sorted by fees
trx_inv_message reply;
reply.items.reserve( TRX_INV_QUERY_LIMIT );
for( auto itr = _pending_trx.begin(); reply.items.size() < TRX_INV_QUERY_LIMIT && itr != _pending_trx.end(); ++itr )
{
reply.items.push_back( itr->first );
}
c->send( network::message( reply, _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_block_inv( const connection_ptr& c, chan_data& cdat, block_inv_message msg )
{ try {
for( auto itr = msg.items.begin(); itr != msg.items.end(); ++itr )
{
if( !cdat.known_block_inv.insert( *itr ).second )
{
wlog( "received inventory item more than once from the same connection\n",
("item", *itr) );
// TODO: why is this connection sending things multiple times... punish it
}
_blocks_pending_fetch.insert( *itr );
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_get_block_inv( const connection_ptr& c, chan_data& cdat, get_block_inv_message msg )
{ try {
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
void handle_get_trxs( const connection_ptr& c, chan_data& cdat, get_trxs_message msg )
{ try {
trxs_message reply;
FC_ASSERT( msg.items.size() < TRX_INV_QUERY_LIMIT );
reply.trxs.reserve( msg.items.size() );
for( auto itr = msg.items.begin(); itr != msg.items.end(); ++itr )
{
auto pending_itr = _pending_trx.find( *itr );
if( pending_itr == _pending_trx.end() )
{
// TODO DB queries are far more expensive, and therefore must be rationed and potentialy
// require a proof of work paying us to fetch them
auto tx_num = _db->fetch_trx_num( *itr );
reply.trxs.push_back( _db->fetch_trx(tx_num) );
}
else
{
reply.trxs.push_back( pending_itr->second );
}
}
c->send( network::message( reply, _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_get_full_block( const connection_ptr& c, chan_data& cdat, get_full_block_message msg )
{ try {
// TODO: throttle attempts to query blocks by a single connection
// this request must hit the DB... cost in proof of work is proportional to age to prevent
// cache thrashing attacks and allowing us to keep newer blocks in the cache
// penalize connections that request too many full blocks...
uint32_t blk_num = _db->fetch_block_num( msg.block_id );
full_block blk = _db->fetch_full_block( blk_num );
c->send( network::message(full_block_message( blk ), _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_get_trx_block( const connection_ptr& c, chan_data& cdat, get_trx_block_message msg )
{ try {
// TODO: throttle attempts to query blocks by a single connection
uint32_t blk_num = _db->fetch_block_num( msg.block_id );
trx_block blk = _db->fetch_trx_block( blk_num );
c->send( network::message(trx_block_message( blk ), _chan_id ) );
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_trxs( const connection_ptr& c, chan_data& cdat, trxs_message msg )
{ try {
for( auto itr = msg.trxs.begin(); itr != msg.trxs.end(); ++itr )
{
auto item_id = itr->id();
if( cdat.requested_trxs.find( item_id ) == cdat.requested_trxs.end() )
{
FC_THROW_EXCEPTION( exception, "unsolicited transaction ${trx_id}",
("trx_id", item_id)("trx", *itr) );
}
_verify_queue.push_back( *itr );
// is this trx part of a block download
auto trx_idx_itr = _block_download.missing_trx_idx.find( item_id );
if( trx_idx_itr != _block_download.missing_trx_idx.end() )
{
_block_download.trxs[trx_idx_itr->second] = *itr;
_block_download.missing_trx_idx.erase(trx_idx_itr);
if( _block_download.missing_trx_idx.size() == 0 )
{
attempt_push_download_block();
// TODO: attempt to push full block!
}
}
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_full_block( const connection_ptr& c, chan_data& cdat, full_block_message msg )
{ try {
fc::sha224 block_id = msg.block_data.id();
if( cdat.requested_full_block != block_id )
{
FC_THROW_EXCEPTION( exception, "unsolicited full block ${block_id}",
("block_id", block_id)("block", msg.block_data) );
}
// attempt to create a trx_block by looking up missing transactions
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
/**
*
*/
void handle_trx_block( const connection_ptr& c, chan_data& cdat, trx_block_message msg )
{ try {
fc::sha224 block_id = msg.block_data.id();
if( cdat.requested_trx_block != block_id )
{
FC_THROW_EXCEPTION( exception, "unsolicited trx block ${block_id}",
("block_id", block_id)("block", msg.block_data) );
}
// attempt to push it onto the block db... if successful broadcast a block inv
} FC_RETHROW_EXCEPTIONS( warn, "", ("msg",msg) ) } // provide stack trace for errors
};
} // namespace detail
channel::channel( const bts::peer::peer_channel_ptr& peers,
const blockchain_db_ptr& db,
channel_delegate* d,
const network::channel_id& c
)
:my( std::make_shared<detail::channel_impl>() )
{
my->_peers = peers;
my->_chan_id = c;
my->_db = db;
my->_del = d;
my->_peers->subscribe_to_channel( my->_chan_id, my );
}
channel::~channel()
{
}
network::channel_id channel::get_id()const
{
return my->_chan_id;
}
/**
* All transactions that are known but that have not been included in
* a block that has been added to the blockchain_db
*/
const std::unordered_map<uint160,signed_transaction>& channel::get_pending_pool()const
{
return my->_pending_trx;
}
/**
* Called when this node wishes to pubish a trx.
*/
void channel::broadcast( const signed_transaction& trx )
{
}
/**
* This is called when a new block is sloved by this node.
*/
void channel::broadcast( const trx_block& b )
{
}
} } // namespace bts::blockchain
| 39.739796 | 129 | 0.521184 | gcbpay |
c1e6dd448aa4d38f5b3151c626d05271bb339353 | 730 | cc | C++ | src/FillTheSkips.cc | DrScKAWAMOTO/cmdrecplay | f1191b455cb63460f1fd34e947fdb1474489b94c | [
"Apache-2.0"
] | null | null | null | src/FillTheSkips.cc | DrScKAWAMOTO/cmdrecplay | f1191b455cb63460f1fd34e947fdb1474489b94c | [
"Apache-2.0"
] | null | null | null | src/FillTheSkips.cc | DrScKAWAMOTO/cmdrecplay | f1191b455cb63460f1fd34e947fdb1474489b94c | [
"Apache-2.0"
] | null | null | null | /*
* Project: ifendif
* Version: 1.0
* Copyright: (C) 2017 Dr.Sc.KAWAMOTO,Takuji (Ext)
* Create: 2017/03/03 05:38:45 JST
*/
#include <string.h>
#include "FillTheSkips.h"
FillTheSkips::FillTheSkips(LineBuffer* parent)
: p_parent(parent)
{
p_parent->read_line();
}
FillTheSkips::~FillTheSkips()
{
}
bool FillTheSkips::read_line()
{
++p_line_no;
if (p_parent->is_eof())
{
strcpy(p_line_buffer, "\n");
return false;
}
if (p_parent->line_number() > p_line_no)
{
strcpy(p_line_buffer, "\n");
return false;
}
strcpy(p_line_buffer, p_parent->line());
p_parent->read_line();
return false;
}
/* Local Variables: */
/* mode: c++ */
/* End: */
| 16.976744 | 50 | 0.593151 | DrScKAWAMOTO |
c1e70362d7a6ad57ac8bfb6276711565c2041bd2 | 11,460 | cpp | C++ | libraries/smt/source/solver.cpp | Noxsense/mCRL2 | dd2fcdd6eb8b15af2729633041c2dbbd2216ad24 | [
"BSL-1.0"
] | 61 | 2018-05-24T13:14:05.000Z | 2022-03-29T11:35:03.000Z | libraries/smt/source/solver.cpp | Noxsense/mCRL2 | dd2fcdd6eb8b15af2729633041c2dbbd2216ad24 | [
"BSL-1.0"
] | 229 | 2018-05-28T08:31:09.000Z | 2022-03-21T11:02:41.000Z | libraries/smt/source/solver.cpp | Noxsense/mCRL2 | dd2fcdd6eb8b15af2729633041c2dbbd2216ad24 | [
"BSL-1.0"
] | 28 | 2018-04-11T14:09:39.000Z | 2022-02-25T15:57:39.000Z | // Author(s): Ruud Koolen, Thomas Neele
// Copyright: see the accompanying file COPYING or copy at
// https://github.com/mCRL2org/mCRL2/blob/master/COPYING
//
// 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)
//
/// \file solver.cpp
#include "mcrl2/data/list.h"
#include "mcrl2/smt/translate_specification.h"
#include "mcrl2/smt/solver.h"
#include "mcrl2/smt/unfold_pattern_matching.h"
namespace mcrl2
{
namespace smt
{
answer smt_solver::execute_and_check(const std::string& s, const std::chrono::microseconds& timeout) const
{
z3.write(s);
std::string result = timeout == std::chrono::microseconds::zero() ? z3.read() : z3.read(timeout);
if(result.compare(0, 3, "sat") == 0)
{
return answer::SAT;
}
else if(result.compare(0, 5, "unsat") == 0)
{
return answer::UNSAT;
}
else if(result.compare(0, 7, "unknown") == 0)
{
return answer::UNKNOWN;
}
else
{
mCRL2log(log::error) << "Error when checking satisfiability of \n" << s << std::endl;
throw mcrl2::runtime_error("Got unexpected response from SMT-solver:\n" + result);
}
}
smt_solver::smt_solver(const data::data_specification& dataspec)
: m_native(initialise_native_translation(dataspec))
, z3("Z3")
{
std::ostringstream out;
translate_data_specification(dataspec, out, m_cache, m_native);
z3.write(out.str());
}
answer smt_solver::solve(const data::variable_list& vars, const data::data_expression& expr, const std::chrono::microseconds& timeout)
{
z3.write("(push)\n");
std::ostringstream out;
translate_variable_declaration(vars, out, m_cache, m_native);
translate_assertion(expr, out, m_cache, m_native);
out << "(check-sat)\n";
answer result = execute_and_check(out.str(), timeout);
z3.write("(pop)\n");
return result;
}
namespace detail {
struct fixed_string_translation: public native_translation_t
{
std::string translation;
fixed_string_translation(const std::string& s)
: translation(s)
{}
void operator()(const data::data_expression& /*e*/,
const std::function<void(std::string)>& output_func,
const std::function<void(data::data_expression)>& /*translate_func*/) const
{
output_func(translation);
}
};
static const native_translation_t pp_translation = [](const data::data_expression& e,
const std::function<void(std::string)>& output_func,
const std::function<void(data::data_expression)>& /*translate_func*/)
{
output_func(data::pp(e));
};
static const native_translation_t pp_real_translation = [](const data::data_expression& e,
const std::function<void(std::string)>& output_func,
const std::function<void(data::data_expression)>& /*translate_func*/)
{
assert(data::sort_real::is_creal_application(e));
const data::application& a = atermpp::down_cast<data::application>(e);
output_func("(/ " + data::pp(a[0]) + ".0 " + data::pp(a[1]) + ".0)");
};
static const native_translation_t reconstruct_divmod = [](const data::data_expression& e,
const std::function<void(std::string)>& output_func,
const std::function<void(data::data_expression)>& translate_func)
{
assert(data::sort_nat::is_first_application(e) || data::sort_nat::is_last_application(e));
const data::application& a = atermpp::down_cast<data::application>(e);
if(data::sort_nat::is_divmod_application(a[0]))
{
const data::application& a2 = atermpp::down_cast<data::application>(a[0]);
output_func("(" + std::string(data::sort_nat::is_first_application(a2) ? "div" : "mod") + " ");
translate_func(a2[0]);
output_func(" ");
translate_func(a2[1]);
output_func(")");
}
else
{
throw translation_error("Cannot perform native translation of " + pp(e));
}
};
} // namespace detail
native_translations initialise_native_translation(const data::data_specification& dataspec)
{
using namespace detail;
using namespace data;
native_translations nt;
nt.sorts[sort_bool::bool_()] = "Bool";
nt.sorts[sort_pos::pos()] = "Int";
nt.sorts[sort_nat::nat()] = "Int";
nt.sorts[sort_int::int_()] = "Int";
nt.sorts[sort_real::real_()] = "Real";
std::vector<sort_expression> number_sorts({ sort_pos::pos(), sort_nat::nat(), sort_int::int_(), sort_real::real_() });
std::set<sort_expression> sorts = dataspec.sorts();
// Add native definitions for the left-hand side of every alias
for(const auto& alias: dataspec.sort_alias_map())
{
sorts.insert(alias.first);
}
for(const sort_expression& sort: sorts)
{
if(is_basic_sort(sort) || is_container_sort(sort))
{
nt.set_native_definition(equal_to(sort), "=");
nt.set_native_definition(not_equal_to(sort), "distinct");
nt.set_native_definition(if_(sort), "ite");
if(std::find(number_sorts.begin(), number_sorts.end(), sort) != number_sorts.end())
{
nt.set_native_definition(less(sort));
nt.set_native_definition(less_equal(sort));
nt.set_native_definition(greater(sort));
nt.set_native_definition(greater_equal(sort));
nt.set_alternative_name(sort_real::exp(sort, sort == sort_real::real_() ? sort_int::int_() : sort_nat::nat()), "^");
nt.set_alternative_name(sort_real::minus(sort, sort), "-");
nt.set_alternative_name(sort_real::negate(sort), "-");
}
else if(sort == basic_sort("@NatPair"))
{
// NatPair is not used and its equations upset Z3
nt.set_native_definition(less(sort));
nt.set_native_definition(less_equal(sort));
nt.set_native_definition(greater(sort));
nt.set_native_definition(greater_equal(sort));
}
else
{
// Functions <, <=, >, >= are already defined on Int/Real and cannot be overloaded
nt.set_alternative_name(less(sort), "@less");
nt.set_alternative_name(less_equal(sort), "@less_equal");
nt.set_alternative_name(greater(sort), "@greater");
nt.set_alternative_name(greater_equal(sort), "@greater_equal");
}
std::string printed_sort_name = nt.sorts.find(sort) != nt.sorts.end() ? nt.sorts.find(sort)->second : translate_identifier(pp(sort));
std::string list_sort_name = "(List " + printed_sort_name + ")";
nt.set_alternative_name(sort_list::count(sort), "@list_count");
nt.set_alternative_name(sort_list::snoc(sort), "@snoc");
nt.set_native_definition(sort_list::empty(sort), "nil");
nt.set_ambiguous(sort_list::empty(sort));
nt.set_native_definition(sort_list::cons_(sort), "insert");
nt.set_native_definition(sort_list::head(sort));
nt.set_native_definition(sort_list::tail(sort));
nt.sorts[sort_list::list(sort)] = list_sort_name;
}
}
std::vector<function_symbol_vector> fs_numbers(
{
sort_pos::pos_generate_functions_code(),
sort_nat::nat_generate_functions_code(),
sort_int::int_generate_functions_code(),
sort_real::real_generate_functions_code()
}
);
for(const auto& fsv: fs_numbers)
{
for(const auto& fs: fsv)
{
nt.set_native_definition(fs);
}
}
auto one = [](const sort_expression& s)
{
return s == sort_int::int_() ? sort_int::int_(1) : sort_real::real_(1);
};
for(const sort_expression& s: { sort_int::int_(), sort_real::real_() })
{
variable v1("v1", s);
variable v2("v2", s);
variable_list l1({v1});
variable_list l2({v1,v2});
nt.mappings[sort_real::minimum(s,s)] = data_equation(l2, sort_real::minimum(v1, v2), if_(less(v1,v2), v1, v2));
nt.mappings[sort_real::maximum(s,s)] = data_equation(l2, sort_real::maximum(v1, v2), if_(less(v1,v2), v2, v1));
nt.mappings[sort_real::succ(s)] = data_equation(l1, sort_real::succ(v1), sort_real::plus(v1, one(s)));
nt.mappings[sort_real::pred(s)] = data_equation(l1, sort_real::pred(v1), sort_real::minus(v1, one(s)));
nt.set_ambiguous(sort_real::minimum(s,s));
nt.set_ambiguous(sort_real::maximum(s,s));
nt.set_ambiguous(sort_real::succ(s));
nt.set_ambiguous(sort_real::pred(s));
}
nt.expressions[sort_nat::first()] = reconstruct_divmod;
nt.expressions[sort_nat::last()] = reconstruct_divmod;
// TODO come up with equations for these
// nt.mappings[sort_real::floor(s)]
// nt.mappings[sort_real::ceil(s)]
// nt.mappings[sort_real::round(s)]
nt.set_native_definition(sort_bool::not_(), "not");
nt.set_native_definition(sort_bool::and_(), "and");
nt.set_native_definition(sort_bool::or_(), "or");
nt.set_native_definition(sort_bool::implies());
nt.set_native_definition(sort_pos::c1(), pp(sort_pos::c1()));
nt.set_native_definition(sort_nat::c0(), pp(sort_nat::c0()));
nt.expressions[sort_pos::cdub()] = pp_translation;
nt.set_native_definition(sort_nat::cnat(), "@id");
nt.set_native_definition(sort_int::cneg(), "-");
nt.set_native_definition(sort_int::cint(), "@id");
nt.expressions[sort_real::creal()] = pp_real_translation;
nt.set_native_definition(sort_real::creal());
nt.special_recogniser[data::sort_bool::true_()] = "@id";
nt.special_recogniser[data::sort_bool::false_()] = "not";
nt.special_recogniser[data::sort_pos::c1()] = "= 1";
nt.special_recogniser[data::sort_pos::cdub()] = ">= 2";
nt.special_recogniser[data::sort_nat::c0()] = "= 0";
nt.special_recogniser[data::sort_nat::cnat()] = ">= 1";
nt.special_recogniser[data::sort_int::cneg()] = "< 0";
nt.special_recogniser[data::sort_int::cint()] = ">= 0";
nt.set_native_definition(sort_nat::pos2nat(), "@id");
nt.set_native_definition(sort_nat::nat2pos(), "@id");
nt.set_native_definition(sort_int::pos2int(), "@id");
nt.set_native_definition(sort_int::int2pos(), "@id");
nt.set_native_definition(sort_int::nat2int(), "@id");
nt.set_native_definition(sort_int::int2nat(), "@id");
nt.set_native_definition(sort_real::pos2real(), "to_real");
nt.set_native_definition(sort_real::real2pos(), "to_int");
nt.set_native_definition(sort_real::nat2real(), "to_real");
nt.set_native_definition(sort_real::real2nat(), "to_int");
nt.set_native_definition(sort_real::int2real(), "to_real");
nt.set_native_definition(sort_real::real2int(), "to_int");
function_symbol id_bool("@id", function_sort({sort_bool::bool_()}, sort_bool::bool_()));
function_symbol id_int("@id", function_sort({sort_int::int_()}, sort_int::int_()));
function_symbol id_real("@id", function_sort({sort_real::real_()}, sort_real::real_()));
variable vb("b", sort_bool::bool_());
variable vi("i", sort_int::int_());
variable vr("r", sort_real::real_());
nt.mappings[id_bool] = data_equation(variable_list({vb}), id_bool(vb), vb);
nt.mappings[id_int] = data_equation(variable_list({vi}), id_int(vi), vi);
nt.mappings[id_real] = data_equation(variable_list({vr}), id_real(vr), vr);
// necessary for translating the equations above
nt.set_native_definition(equal_to(sort_bool::bool_()), "=");
nt.set_native_definition(equal_to(sort_int::int_()), "=");
nt.set_native_definition(equal_to(sort_real::real_()), "=");
unfold_pattern_matching(dataspec, nt);
return nt;
}
} // namespace smt
} // namespace mcrl2
| 39.653979 | 139 | 0.665881 | Noxsense |
c1e73617decc695e5a1b03529cd19732911f8b03 | 4,663 | cpp | C++ | PSME/application/src/rest/endpoints/role.cpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 5 | 2021-10-07T15:36:37.000Z | 2022-03-01T07:21:49.000Z | PSME/application/src/rest/endpoints/role.cpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | null | null | null | PSME/application/src/rest/endpoints/role.cpp | opencomputeproject/HWMgmt-DeviceMgr-PSME | 2a00188aab6f4bef3776987f0842ef8a8ea972ac | [
"Apache-2.0"
] | 1 | 2022-03-01T07:21:51.000Z | 2022-03-01T07:21:51.000Z | /*
* Edgecore DeviceManager
* Copyright 2020-2021 Edgecore Networks, Inc.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "psme/rest/endpoints/role.hpp"
#include "psme/rest/endpoints/utils.hpp"
#include "psme/rest/account/config/role_config.hpp"
//#include "psme/rest/validators/schemas/role.hpp"
#include "psme/rest/validators/json_validator.hpp"
#include "psme/rest/constants/constants.hpp"
#include "json/json.hpp"
#include "psme/rest/server/error/error_factory.hpp"
#include "psme/rest/server/error/server_exception.hpp"
using namespace psme::rest;
using namespace psme::rest::constants;
using namespace psme::rest::server;
using namespace psme::rest::account::manager;
using namespace psme::rest::account::config;
using namespace psme::rest::endpoint::utils;
using namespace psme::rest::validators;
namespace {
json::Value make_prototype() {
json::Value r(json::Value::Type::OBJECT);
r[Common::ODATA_CONTEXT] = "/redfish/v1/$metadata#Role.Role";
r[Common::ODATA_ID] = json::Value::Type::NIL;
r[Common::ODATA_TYPE] = "#Role.v1_0_0.Role";
r[Common::ID] = json::Value::Type::NIL;
r[Common::NAME] = json::Value::Type::NIL;
r[Common::DESCRIPTION] = json::Value::Type::NIL;
// r[AccountRole::ROLEID] = json::Value::Type::NIL; //To pass DMTF Validator
r[AccountRole::ISPREDEFINED] = json::Value::Type::NIL;
r[AccountRole::PRIVILEGE_TYPES] = json::Value::Type::NIL;
return r;
}
void to_json(const Role& role, json::Value& json) {
json[Common::NAME] = role.get_name();
// json[AccountRole::ROLEID] = role.get_roleid(); //To pass DMTF Validator
json[AccountRole::ISPREDEFINED] = role.get_ispredefined();
json::Value priv_types_json(json::Value::Type::ARRAY);
for (const auto& priv_type : role.get_privilege_types().get()){
priv_types_json.push_back(priv_type.to_string());
}
json[AccountRole::PRIVILEGE_TYPES] = priv_types_json;
}
}
endpoint::Role::Role(const std::string& path) : EndpointBase(path) {}
endpoint::Role::~Role() {}
void endpoint::Role::get(const server::Request& request, server::Response& response) {
auto r = make_prototype();
r[Common::ODATA_ID] = request.get_url();
r[Common::ID] = request.params[PathParam::ROLE_ID];
const auto& role = AccountManager::get_instance()->getRole(request.params[PathParam::ROLE_ID]);
to_json(role, r);
set_response(response, r);
}
void endpoint::Role::del(const server::Request& request, server::Response& response) {
const auto& id = id_to_uint64(request.params[PathParam::ROLE_ID]);
AccountManager::get_instance()->delRole(id);
response.set_status(server::status_2XX::NO_CONTENT);
}
void endpoint::Role::patch(const server::Request &request, server::Response &response)
{
#if 0
using namespace psme::rest::account::model;
const auto& id = id_to_uint64(request.params[PathParam::ROLE_ID]);
account::model::Account account = AccountManager::get_instance()->getAccount(id);
const auto json = JsonValidator::validate_request_body<schema::AccountCollectionPostSchema>(request);
const auto& old_username = account.get_username();
const auto& enabled = json[AccountConst::ENABLED].as_bool();
const auto& locked = json[AccountConst::LOCKED].as_bool();
std::string new_username = json[AccountConst::USERNAME].as_string();
const auto& password = json[AccountConst::PASSWORD].as_string();
const auto& roleid = json[AccountConst::ROLEID].as_string();
account.set_username(new_username);
account.set_password(password, ? );
account.set_roleid(roleid);
account.set_enabled(enabled);
account.set_locked(locked);
AccountManager::get_instance()->modAccount(old_username,account);
AccountConfig::get_instance()->saveAccounts();
#endif
(void) (request);
response.set_status(server::status_4XX::METHOD_NOT_ALLOWED);
return;
} | 36.716535 | 105 | 0.719065 | opencomputeproject |
c1e811cc5876921134c52168170b4d40ce9876d5 | 303 | hpp | C++ | pythran/pythonic/__builtin__/RuntimeWarning.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | 1 | 2018-03-24T00:33:03.000Z | 2018-03-24T00:33:03.000Z | pythran/pythonic/__builtin__/RuntimeWarning.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/__builtin__/RuntimeWarning.hpp | SylvainCorlay/pythran | 908ec070d837baf77d828d01c3e35e2f4bfa2bfa | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_BUILTIN_RUNTIMEWARNING_HPP
#define PYTHONIC_BUILTIN_RUNTIMEWARNING_HPP
#include "pythonic/include/__builtin__/RuntimeWarning.hpp"
#include "pythonic/types/exceptions.hpp"
PYTHONIC_NS_BEGIN
namespace __builtin__
{
PYTHONIC_EXCEPTION_IMPL(RuntimeWarning)
}
PYTHONIC_NS_END
#endif
| 16.833333 | 58 | 0.854785 | SylvainCorlay |
c1e829fbbec0253f5c3221860b20d01f9018897a | 8,885 | cc | C++ | src/backend/quad/quadpass/adjust_expr.cc | zhongxinghong/sysyc | b3cde82c985dc40c2e564e82e4c41db76a992eb8 | [
"MIT"
] | 2 | 2021-11-16T09:46:20.000Z | 2022-03-24T11:49:34.000Z | src/backend/quad/quadpass/adjust_expr.cc | zhongxinghong/sysyc | b3cde82c985dc40c2e564e82e4c41db76a992eb8 | [
"MIT"
] | null | null | null | src/backend/quad/quadpass/adjust_expr.cc | zhongxinghong/sysyc | b3cde82c985dc40c2e564e82e4c41db76a992eb8 | [
"MIT"
] | 2 | 2022-02-23T06:34:52.000Z | 2022-03-13T04:05:40.000Z | //------------------------------------------------------------------------------
// A SysY Compiler for PKU Compiling Principles Practice Course (2021 Spring)
//------------------------------------------------------------------------------
// Project: sysyc
// File: adjust_expr.cc
// Created Date: 2021-05-26
// Author: Zhong Xinghong (1700012608)
// Email: zxh2017@pku.edu.cn
//------------------------------------------------------------------------------
// Copyright (c) 2021 Zhong Xinghong
//------------------------------------------------------------------------------
#include <cassert>
#include "backend/quad/quadpass/quadpass.h"
namespace sysyc
{
namespace backend
{
namespace quad
{
namespace pass
{
using namespace middle::quad;
namespace __impl
{
sysystd::int_t eval(Opcode op, sysystd::int_t val)
{
switch (op)
{
case Opcode::NEG: return -val;
case Opcode::LNOT: return sysystd::bool2int(!sysystd::int2bool(val));
case Opcode::JEQZ: return sysystd::bool2int(val == 0);
case Opcode::JNEZ: return sysystd::bool2int(val != 0);
default:
assert(false);
}
return 0;
}
sysystd::int_t eval(Opcode op, sysystd::int_t lhs, sysystd::int_t rhs)
{
switch (op)
{
case Opcode::ADD: return lhs + rhs;
case Opcode::SUB: return lhs - rhs;
case Opcode::MUL: return lhs * rhs;
case Opcode::DIV: return lhs / rhs;
case Opcode::MOD: return lhs % rhs;
case Opcode::NE: case Opcode::JNE: return sysystd::bool2int(lhs != rhs);
case Opcode::EQ: case Opcode::JEQ: return sysystd::bool2int(lhs == rhs);
case Opcode::GT: case Opcode::JGT: return sysystd::bool2int(lhs > rhs);
case Opcode::LT: case Opcode::JLT: return sysystd::bool2int(lhs < rhs);
case Opcode::GE: case Opcode::JGE: return sysystd::bool2int(lhs >= rhs);
case Opcode::LE: case Opcode::JLE: return sysystd::bool2int(lhs <= rhs);
case Opcode::LAND:
return sysystd::bool2int(sysystd::int2bool(lhs) && sysystd::int2bool(rhs));
case Opcode::LOR:
return sysystd::bool2int(sysystd::int2bool(lhs) || sysystd::int2bool(rhs));
default:
assert(false);
}
return 0;
}
inline Opcode inv_relop(const Opcode &op)
{
switch (op)
{
case Opcode::GT: return Opcode::LT;
case Opcode::LT: return Opcode::GT;
case Opcode::GE: return Opcode::LE;
case Opcode::LE: return Opcode::GE;
case Opcode::JGT: return Opcode::JLT;
case Opcode::JLT: return Opcode::JGT;
case Opcode::JGE: return Opcode::JLE;
case Opcode::JLE: return Opcode::JGE;
default:
assert(false);
}
return static_cast<Opcode>(0);
}
inline void swap_arg12(Instruction *inst)
{
auto opnd = inst->arg1;
inst->arg1 = inst->arg2;
inst->arg2 = opnd;
}
inline bool is_number(const Operand *opnd, sysystd::int_t num)
{
return opnd->is_num() && opnd->val == num;
}
} // namespace __impl
static bool binexpr_swap_argx(InstructionList &instseq, misc::Logger &logger)
{
auto &list = instseq.list;
for (auto it = list.begin(), e = list.end(); it != e; ++it)
{
auto &inst = *it;
switch (inst->op)
{
case Opcode::NE:
case Opcode::EQ:
case Opcode::JNE:
case Opcode::JEQ:
case Opcode::LAND:
case Opcode::LOR:
case Opcode::ADD:
case Opcode::MUL:
{
if (inst->arg1->is_num() && !inst->arg2->is_num())
__impl::swap_arg12(inst);
break;
}
case Opcode::GT:
case Opcode::LT:
case Opcode::GE:
case Opcode::LE:
case Opcode::JGT:
case Opcode::JLT:
case Opcode::JGE:
case Opcode::JLE:
{
if (inst->arg1->is_num() && !inst->arg2->is_num())
{
inst->op = __impl::inv_relop(inst->op);
__impl::swap_arg12(inst);
}
break;
}
case Opcode::SUB:
case Opcode::DIV:
case Opcode::MOD:
break;
default:
break;
}
}
return true;
}
static bool simplify_expr(InstructionList &instseq, misc::Logger &logger)
{
auto &list = instseq.list;
for (auto it = list.begin(), e = list.end(); it != e; )
{
auto &inst = *it;
switch (inst->op)
{
case Opcode::LNOT:
case Opcode::NEG:
{
if (inst->arg1->is_num())
{
auto ans = __impl::eval(inst->op, inst->arg1->val);
inst->op = Opcode::SWORD;
inst->arg1->val = ans;
}
break;
}
case Opcode::NE:
case Opcode::EQ:
case Opcode::GT:
case Opcode::LT:
case Opcode::GE:
case Opcode::LE:
case Opcode::LAND:
case Opcode::LOR:
case Opcode::ADD:
case Opcode::SUB:
case Opcode::MUL:
case Opcode::DIV:
case Opcode::MOD:
{
if (inst->arg1->is_num() && inst->arg2->is_num())
{
auto ans = __impl::eval(inst->op, inst->arg1->val, inst->arg2->val);
inst->op = Opcode::SWORD;
delete inst->arg2;
inst->arg1->val = ans;
inst->arg2 = nullptr;
}
else if (inst->op == Opcode::LAND)
{
if (inst->arg2->is_num() && !(sysystd::int2bool(inst->arg2->val)))
{
inst->op = Opcode::SWORD;
delete inst->arg1;
delete inst->arg2;
inst->arg1 = new Operand(Operand::Type::NUM, sysystd::bool2int(false));
inst->arg2 = nullptr;
}
}
else if (inst->op == Opcode::LOR)
{
if (inst->arg2->is_num() && sysystd::int2bool(inst->arg2->val))
{
inst->op = Opcode::SWORD;
delete inst->arg1;
delete inst->arg2;
inst->arg1 = new Operand(Operand::Type::NUM, sysystd::bool2int(true));
inst->arg2 = nullptr;
}
}
else if (inst->op == Opcode::ADD)
{
if (__impl::is_number(inst->arg2, 0))
{
inst->op = Opcode::SWORD;
delete inst->arg2;
inst->arg2 = nullptr;
}
}
else if (inst->op == Opcode::SUB)
{
if (__impl::is_number(inst->arg2, 0))
{
inst->op = Opcode::SWORD;
delete inst->arg2;
inst->arg2 = nullptr;
}
}
else if (inst->op == Opcode::MUL)
{
if (__impl::is_number(inst->arg2, 0))
{
inst->op = Opcode::SWORD;
delete inst->arg1;
delete inst->arg2;
inst->arg1 = new Operand(Operand::Type::NUM, 0);
inst->arg2 = nullptr;
}
else if (__impl::is_number(inst->arg2, 1))
{
inst->op = Opcode::SWORD;
delete inst->arg2;
inst->arg2 = nullptr;
}
else if (__impl::is_number(inst->arg2, -1))
{
inst->op = Opcode::NEG;
delete inst->arg2;
inst->arg2 = nullptr;
}
// else if (__impl::is_number(inst->arg2, 2))
// {
// inst->op = Opcode::ADD;
// delete inst->arg2;
// inst->arg2 = new Operand(inst->arg1);
// }
}
else if (inst->op == Opcode::DIV)
{
if (__impl::is_number(inst->arg1, 0))
{
inst->op = Opcode::SWORD;
delete inst->arg2;
inst->arg2 = nullptr;
}
else if (__impl::is_number(inst->arg2, 1))
{
inst->op = Opcode::SWORD;
delete inst->arg2;
inst->arg2 = nullptr;
}
else if (__impl::is_number(inst->arg2, -1))
{
inst->op = Opcode::NEG;
delete inst->arg2;
inst->arg2 = nullptr;
}
}
break;
}
case Opcode::JNE:
case Opcode::JEQ:
case Opcode::JGT:
case Opcode::JLT:
case Opcode::JGE:
case Opcode::JLE:
{
if (inst->arg1->is_num() && inst->arg2->is_num())
{
auto ans = __impl::eval(inst->op, inst->arg1->val, inst->arg2->val);
if (sysystd::int2bool(ans))
{
inst->op = Opcode::JMP;
delete inst->arg1;
delete inst->arg2;
inst->arg1 = nullptr;
inst->arg2 = nullptr;
}
else
{
delete inst;
it = list.erase(it);
continue;
}
}
break;
}
case Opcode::JEQZ:
case Opcode::JNEZ:
{
if (inst->arg1->is_num())
{
auto ans = __impl::eval(inst->op, inst->arg1->val);
if (sysystd::int2bool(ans))
{
inst->op = Opcode::JMP;
delete inst->arg1;
inst->arg1 = nullptr;
}
else
{
delete inst;
it = list.erase(it);
continue;
}
}
break;
}
default:
break;
}
it++;
}
return true;
}
bool adjust_expr(InstructionList &instseq, misc::Logger &logger)
{
if (!binexpr_swap_argx(instseq, logger))
return false;
if (!simplify_expr(instseq, logger))
return false;
return true;
}
} // namespace pass
} // namespace quad
} // namespace backend
} // namespace sysyc
| 22.723785 | 81 | 0.520878 | zhongxinghong |
c1ea4f480b12eda6b000d01d3c2b8a3f6e09de4c | 53,483 | cpp | C++ | meta/source/app/App.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | meta/source/app/App.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | meta/source/app/App.cpp | congweitao/congfs | 54cedf484f8a2cacab567fe182cc1f6413c25cf2 | [
"BSD-3-Clause"
] | null | null | null | #include <common/app/log/LogContext.h>
#include <common/components/worker/queue/UserWorkContainer.h>
#include <common/components/worker/DummyWork.h>
#include <common/components/ComponentInitException.h>
#include <common/components/RegistrationDatagramListener.h>
#include <common/net/message/nodes/RegisterNodeMsg.h>
#include <common/net/message/nodes/RegisterNodeRespMsg.h>
#include <common/net/sock/RDMASocket.h>
#include <common/nodes/LocalNode.h>
#include <common/storage/striping/Raid0Pattern.h>
#include <common/toolkit/NodesTk.h>
#include <components/FileEventLogger.h>
#include <components/ModificationEventFlusher.h>
#include <components/DisposalGarbageCollector.h>
#include <program/Program.h>
#include <session/SessionStore.h>
#include <storage/MetadataEx.h>
#include <toolkit/BuddyCommTk.h>
#include <toolkit/StorageTkEx.h>
#include <boost/format.hpp>
#include "App.h"
#include <array>
#include <mntent.h>
#include <csignal>
#include <fstream>
#include <sstream>
#include <syslog.h>
#include <sys/resource.h>
#include <sys/statfs.h>
#include <blkid/blkid.h>
#include <uuid/uuid.h>
// this magic number is not available on all supported platforms. specifically, rhel5 does not have
// linux/magic.h (which is where this constant is found).
#ifndef EXT3_SUPER_MAGIC
#define EXT3_SUPER_MAGIC 0xEF53
#endif
#define APP_WORKERS_DIRECT_NUM 1
#define APP_SYSLOG_IDENTIFIER "congfs-meta"
App::App(int argc, char** argv)
{
this->argc = argc;
this->argv = argv;
this->appResult = APPCODE_NO_ERROR;
this->cfg = NULL;
this->netFilter = NULL;
this->tcpOnlyFilter = NULL;
this->log = NULL;
this->mgmtNodes = NULL;
this->metaNodes = NULL;
this->storageNodes = NULL;
this->clientNodes = NULL;
this->metaCapacityPools = NULL;
this->targetMapper = NULL;
this->storageBuddyGroupMapper = NULL;
this->metaBuddyGroupMapper = NULL;
this->targetStateStore = NULL;
this->metaStateStore = NULL;
this->metaBuddyCapacityPools = NULL;
this->workQueue = NULL;
this->commSlaveQueue = NULL;
this->disposalDir = NULL;
this->buddyMirrorDisposalDir = NULL;
this->rootDir = NULL;
this->metaStore = NULL;
this->ackStore = NULL;
this->sessions = NULL;
this->mirroredSessions = NULL;
this->nodeOperationStats = NULL;
this->netMessageFactory = NULL;
this->inodesPath = NULL;
this->dentriesPath = NULL;
this->buddyMirrorInodesPath = NULL;
this->buddyMirrorDentriesPath = NULL;
this->dgramListener = NULL;
this->connAcceptor = NULL;
this->statsCollector = NULL;
this->internodeSyncer = NULL;
this->modificationEventFlusher = NULL;
this->timerQueue = new TimerQueue(1, 1);
this->gcQueue = new TimerQueue(1, 1);
this->buddyResyncer = NULL;
this->nextNumaBindTarget = 0;
}
App::~App()
{
// Note: Logging of the common lib classes is not working here, because this is called
// from class Program (so the thread-specific app-pointer isn't set in this context).
commSlavesDelete();
workersDelete();
SAFE_DELETE(this->buddyResyncer);
SAFE_DELETE(this->timerQueue);
SAFE_DELETE(this->modificationEventFlusher);
SAFE_DELETE(this->internodeSyncer);
SAFE_DELETE(this->statsCollector);
SAFE_DELETE(this->connAcceptor);
streamListenersDelete();
SAFE_DELETE(this->dgramListener);
SAFE_DELETE(this->dentriesPath);
SAFE_DELETE(this->inodesPath);
SAFE_DELETE(this->buddyMirrorDentriesPath);
SAFE_DELETE(this->buddyMirrorInodesPath);
SAFE_DELETE(this->netMessageFactory);
SAFE_DELETE(this->nodeOperationStats);
SAFE_DELETE(this->sessions);
SAFE_DELETE(this->mirroredSessions);
SAFE_DELETE(this->ackStore);
if(this->disposalDir && this->metaStore)
this->metaStore->releaseDir(this->disposalDir->getID() );
if(this->buddyMirrorDisposalDir && this->metaStore)
this->metaStore->releaseDir(this->buddyMirrorDisposalDir->getID() );
if(this->rootDir && this->metaStore)
this->metaStore->releaseDir(this->rootDir->getID() );
SAFE_DELETE(this->metaStore);
SAFE_DELETE(this->commSlaveQueue);
SAFE_DELETE(this->workQueue);
SAFE_DELETE(this->clientNodes);
SAFE_DELETE(this->storageNodes);
SAFE_DELETE(this->metaNodes);
SAFE_DELETE(this->mgmtNodes);
this->localNode.reset();
SAFE_DELETE(this->metaBuddyCapacityPools);
SAFE_DELETE(this->storageBuddyGroupMapper);
SAFE_DELETE(this->metaBuddyGroupMapper);
SAFE_DELETE(this->targetMapper);
SAFE_DELETE(this->metaStateStore);
SAFE_DELETE(this->targetStateStore);
SAFE_DELETE(this->metaCapacityPools);
SAFE_DELETE(this->log);
SAFE_DELETE(this->tcpOnlyFilter);
SAFE_DELETE(this->netFilter);
SAFE_DELETE(this->cfg);
delete timerQueue;
Logger::destroyLogger();
closelog();
}
/**
* Initialize config and run app either in normal mode or in special unit tests mode.
*/
void App::run()
{
try
{
openlog(APP_SYSLOG_IDENTIFIER, LOG_NDELAY | LOG_PID | LOG_CONS, LOG_DAEMON);
this->cfg = new Config(argc, argv);
runNormal();
}
catch (InvalidConfigException& e)
{
std::cerr << std::endl;
std::cerr << "Error: " << e.what() << std::endl;
std::cerr << std::endl;
std::cerr << "[ConGFS Metadata Node Version: " << CONGFS_VERSION << std::endl;
std::cerr << "Refer to the default config file (/etc/congfs/congfs-meta.conf)" << std::endl;
std::cerr << "or visit http://www.congfs.com to find out about configuration options.]"
<< std::endl;
std::cerr << std::endl;
if(this->log)
log->logErr(e.what() );
appResult = APPCODE_INVALID_CONFIG;
return;
}
catch (std::exception& e)
{
std::cerr << std::endl;
std::cerr << "Unrecoverable error: " << e.what() << std::endl;
std::cerr << std::endl;
if(this->log)
log->logErr(e.what() );
appResult = APPCODE_RUNTIME_ERROR;
return;
}
}
/**
* @throw InvalidConfigException on error
*/
void App::runNormal()
{
// numa binding (as early as possible)
if(cfg->getTuneBindToNumaZone() != -1) // -1 means disable binding
{
bool bindRes = System::bindToNumaNode(cfg->getTuneBindToNumaZone() );
if(!bindRes)
throw InvalidConfigException("Unable to bind to this NUMA zone: " +
StringTk::intToStr(cfg->getTuneBindToNumaZone() ) );
}
// init basic data objects & storage
NumNodeID localNodeNumID;
std::string localNodeID;
// locks working dir => call before anything else that accesses the disk
const bool targetNew = preinitStorage();
initLogging();
checkTargetUUID();
initLocalNodeIDs(localNodeID, localNodeNumID);
initDataObjects();
initBasicNetwork();
initStorage();
initXAttrLimit();
initRootDir(localNodeNumID);
initDisposalDir();
registerSignalHandler();
// prepare ibverbs for forking
RDMASocket::rdmaForkInitOnce();
// ACLs need enabled client side XAttrs in order to work.
if (cfg->getStoreClientACLs() && !cfg->getStoreClientXAttrs() )
throw InvalidConfigException(
"Client ACLs are enabled in config file, but extended attributes are not. "
"ACLs cannot be stored without extended attributes.");
// detach process
if(cfg->getRunDaemonized() )
daemonize();
// find RDMA interfaces (based on TCP/IP interfaces)
// note: we do this here, because when we first create an RDMASocket (and this is done in this
// check), the process opens the verbs device. Recent OFED versions have a check if the
// credentials of the opening process match those of the calling process (not only the values
// are compared, but the pointer is checked for equality). Thus, the first open needs to happen
// after the fork, because we need to access the device in the child process.
if(cfg->getConnUseRDMA() && RDMASocket::rdmaDevicesExist() )
{
bool foundRdmaInterfaces = NetworkInterfaceCard::checkAndAddRdmaCapability(localNicList);
if (foundRdmaInterfaces)
localNicList.sort(NetworkInterfaceCard::NicAddrComp{&allowedInterfaces}); // re-sort the niclist
}
// Find MgmtNode
bool mgmtWaitRes = waitForMgmtNode();
if(!mgmtWaitRes)
{ // typically user just pressed ctrl+c in this case
log->logErr("Waiting for congfs-mgmtd canceled");
appResult = APPCODE_RUNTIME_ERROR;
return;
}
// retrieve localNodeNumID from management node (if we don't have it yet)
if(!localNodeNumID)
{ // no local num ID yet => try to retrieve one from mgmt
bool preregisterRes = preregisterNode(localNodeID, localNodeNumID);
if(!preregisterRes)
throw InvalidConfigException("Pre-registration at management node canceled");
}
if (!localNodeNumID) // just a sanity check that should never fail
throw InvalidConfigException("Failed to retrieve numeric local node ID from mgmt");
// we have all local node data now => init localNode
initLocalNode(localNodeID, localNodeNumID);
initLocalNodeNumIDFile(localNodeNumID);
// Keeps the local node state from the static call to the InternodeSyncer method so we can pass
// it when we construct the actual object.
TargetConsistencyState initialConsistencyState;
bool downloadRes = downloadMgmtInfo(initialConsistencyState);
if (!downloadRes)
{
log->log(1, "Downloading target states from management node failed. Shutting down...");
appResult = APPCODE_INITIALIZATION_ERROR;
return;
}
// Check for the sessions file. If there is none, it's either the first run, or we crashed so we
// need a resync.
bool sessionFilePresent = StorageTk::checkSessionFileExists(metaPathStr);
if (!targetNew && !sessionFilePresent)
initialConsistencyState = TargetConsistencyState_NEEDS_RESYNC;
// init components
BuddyCommTk::prepareBuddyNeedsResyncState(*mgmtNodes->referenceFirstNode(),
*metaBuddyGroupMapper, *timerQueue, localNode->getNumID());
try
{
initComponents(initialConsistencyState);
}
catch(ComponentInitException& e)
{
log->logErr(e.what() );
log->log(Log_CRITICAL, "A hard error occurred. Shutting down...");
appResult = APPCODE_INITIALIZATION_ERROR;
return;
}
// restore sessions from last clean shut down
restoreSessions();
// log system and configuration info
logInfos();
// start component threads and join them
startComponents();
// session restore is finished so delete old session files
// clean shutdown will generate a new session file
deleteSessionFiles();
// wait for termination
joinComponents();
// clean shutdown (at least no cache loss) => generate a new session file
if(sessions)
storeSessions();
// close all client sessions
InternodeSyncer::syncClients({}, false);
log->log(Log_CRITICAL, "All components stopped. Exiting now!");
}
void App::initLogging()
{
// check absolute log path to avoid chdir() problems
Path logStdPath(cfg->getLogStdFile() );
if(!logStdPath.empty() && !logStdPath.absolute())
{
throw InvalidConfigException("Path to log file must be absolute");
}
Logger::createLogger(cfg->getLogLevel(), cfg->getLogType(), cfg->getLogNoDate(),
cfg->getLogStdFile(), cfg->getLogNumLines(), cfg->getLogNumRotatedFiles());
this->log = new LogContext("App");
if (!cfg->getFileEventLogTarget().empty())
fileEventLogger.reset(new FileEventLogger(cfg->getFileEventLogTarget()));
}
/**
* Init basic shared objects like work queues, node stores etc.
*/
void App::initDataObjects()
{
this->mgmtNodes = new NodeStoreServers(NODETYPE_Mgmt, true);
this->metaNodes = new NodeStoreServers(NODETYPE_Meta, true);
this->storageNodes = new NodeStoreServers(NODETYPE_Storage, false);
this->clientNodes = new NodeStoreClients();
NicAddressList nicList;
this->targetMapper = new TargetMapper();
this->storageNodes->attachTargetMapper(targetMapper);
this->storageBuddyGroupMapper = new MirrorBuddyGroupMapper(targetMapper);
this->metaBuddyGroupMapper = new MirrorBuddyGroupMapper();
this->metaCapacityPools = new NodeCapacityPools(
false, DynamicPoolLimits(0, 0, 0, 0, 0, 0), DynamicPoolLimits(0, 0, 0, 0, 0, 0) );
this->metaNodes->attachCapacityPools(metaCapacityPools);
this->metaBuddyCapacityPools = new NodeCapacityPools(
false, DynamicPoolLimits(0, 0, 0, 0, 0, 0), DynamicPoolLimits(0, 0, 0, 0, 0, 0) );
this->metaBuddyGroupMapper->attachMetaCapacityPools(metaBuddyCapacityPools);
this->targetStateStore = new TargetStateStore(NODETYPE_Storage);
this->targetMapper->attachStateStore(targetStateStore);
this->metaStateStore = new TargetStateStore(NODETYPE_Meta);
this->metaNodes->attachStateStore(metaStateStore);
this->storagePoolStore = boost::make_unique<StoragePoolStore>(storageBuddyGroupMapper,
targetMapper);
// add newly mapped targets and buddy groups to storage pool store
this->targetMapper->attachStoragePoolStore(storagePoolStore.get());
this->storageBuddyGroupMapper->attachStoragePoolStore(storagePoolStore.get());
this->targetMapper->attachExceededQuotaStores(&exceededQuotaStores);
this->workQueue = new MultiWorkQueue();
this->commSlaveQueue = new MultiWorkQueue();
if(cfg->getTuneUsePerUserMsgQueues() )
workQueue->setIndirectWorkList(new UserWorkContainer() );
this->ackStore = new AcknowledgmentStore();
this->sessions = new SessionStore();
this->mirroredSessions = new SessionStore();
this->nodeOperationStats = new MetaNodeOpStats();
this->isRootBuddyMirrored = false;
}
/**
* Init basic networking data structures.
*
* Note: no RDMA is detected here, because this needs to be done later
*/
void App::initBasicNetwork()
{
// check if management host is defined
if(!cfg->getSysMgmtdHost().length() )
throw InvalidConfigException("Management host undefined");
// prepare filter for outgoing packets/connections
this->netFilter = new NetFilter(cfg->getConnNetFilterFile() );
this->tcpOnlyFilter = new NetFilter(cfg->getConnTcpOnlyFilterFile() );
// prepare filter for interfaces
std::string interfacesList = cfg->getConnInterfacesList();
if(!interfacesList.empty() )
{
log->log(Log_DEBUG, "Allowed interfaces: " + interfacesList);
StringTk::explodeEx(interfacesList, ',', true, &allowedInterfaces);
}
// discover local NICs and filter them
NetworkInterfaceCard::findAllInterfaces(allowedInterfaces, localNicList);
if(localNicList.empty() )
throw InvalidConfigException("Couldn't find any usable NIC");
localNicList.sort(NetworkInterfaceCard::NicAddrComp{&allowedInterfaces});
// prepare factory for incoming messages
this->netMessageFactory = new NetMessageFactory();
}
/**
* Load node IDs from disk or generate string ID.
*/
void App::initLocalNodeIDs(std::string& outLocalID, NumNodeID& outLocalNumID)
{
// load (or generate) nodeID and compare to original nodeID
Path metaPath(metaPathStr);
Path nodeIDPath = metaPath / STORAGETK_NODEID_FILENAME;
StringList nodeIDList; // actually contains only a single line
bool idPathExists = StorageTk::pathExists(nodeIDPath.str());
if(idPathExists)
ICommonConfig::loadStringListFile(nodeIDPath.str().c_str(), nodeIDList);
if(!nodeIDList.empty() )
outLocalID = *nodeIDList.begin();
// auto-generate nodeID if it wasn't loaded
if(outLocalID.empty() )
outLocalID = System::getHostname();
// check for nodeID changes
StorageTk::checkOrCreateOrigNodeIDFile(metaPathStr, outLocalID);
// load nodeNumID file
StorageTk::readNumIDFile(metaPath.str(), STORAGETK_NODENUMID_FILENAME, &outLocalNumID);
// note: localNodeNumID is still 0 here if it wasn't loaded from the file
}
/**
* create and attach the localNode object, store numID in storage dir
*/
void App::initLocalNode(std::string& localNodeID, NumNodeID localNodeNumID)
{
unsigned portUDP = cfg->getConnMetaPortUDP();
unsigned portTCP = cfg->getConnMetaPortTCP();
// create localNode object
localNode = std::make_shared<LocalNode>(NODETYPE_Meta, localNodeID, localNodeNumID, portUDP,
portTCP, localNicList);
// attach to metaNodes store
metaNodes->setLocalNode(this->localNode);
}
/**
* Store numID file in storage directory
*/
void App::initLocalNodeNumIDFile(NumNodeID localNodeNumID)
{
StorageTk::createNumIDFile(metaPathStr, STORAGETK_NODENUMID_FILENAME, localNodeNumID.val());
}
/**
* this contains things that would actually live inside initStorage() but need to be
* done at an earlier stage (like working dir locking before log file creation).
*
* note: keep in mind that we don't have the logger here yet, because logging can only be
* initialized after the working dir has conn locked within this method.
*
* @returns true if there was no storageFormatFile before (target was uninitialized)
*/
bool App::preinitStorage()
{
Path metaPath(cfg->getStoreMetaDirectory() );
this->metaPathStr = metaPath.str(); // normalize
if(metaPath.empty() )
throw InvalidConfigException("No metadata storage directory specified");
if(!metaPath.absolute() ) /* (check to avoid problems after chdir later) */
throw InvalidConfigException("Path to storage directory must be absolute: " + metaPathStr);
const bool formatFileExists = StorageTk::checkStorageFormatFileExists(metaPathStr);
if(!cfg->getStoreAllowFirstRunInit() &&
!formatFileExists)
throw InvalidConfigException("Storage directory not initialized and "
"initialization has conn disabled: " + metaPathStr);
this->pidFileLockFD = createAndLockPIDFile(cfg->getPIDFile() ); // ignored if pidFile not defined
if(!StorageTk::createPathOnDisk(metaPath, false) )
throw InvalidConfigException("Unable to create metadata directory: " + metaPathStr +
" (" + System::getErrString(errno) + ")" );
this->workingDirLockFD = StorageTk::lockWorkingDirectory(cfg->getStoreMetaDirectory() );
if (!workingDirLockFD.valid())
throw InvalidConfigException("Unable to lock working directory: " + metaPathStr);
return !formatFileExists;
}
void App::initStorage()
{
// change working dir to meta directory
int changeDirRes = chdir(metaPathStr.c_str() );
if(changeDirRes)
{ // unable to change working directory
throw InvalidConfigException("Unable to change working directory to: " + metaPathStr + " "
"(SysErr: " + System::getErrString() + ")");
}
// storage format file
if(!StorageTkEx::createStorageFormatFile(metaPathStr) )
throw InvalidConfigException("Unable to create storage format file in: " +
cfg->getStoreMetaDirectory() );
StorageTkEx::checkStorageFormatFile(metaPathStr);
// dentries directory
dentriesPath = new Path(META_DENTRIES_SUBDIR_NAME);
StorageTk::initHashPaths(*dentriesPath,
META_DENTRIES_LEVEL1_SUBDIR_NUM, META_DENTRIES_LEVEL2_SUBDIR_NUM);
// buddy mirrored dentries directory
buddyMirrorDentriesPath = new Path(META_BUDDYMIRROR_SUBDIR_NAME "/" META_DENTRIES_SUBDIR_NAME);
StorageTk::initHashPaths(*buddyMirrorDentriesPath,
META_DENTRIES_LEVEL1_SUBDIR_NUM, META_DENTRIES_LEVEL2_SUBDIR_NUM);
// inodes directory
inodesPath = new Path(META_INODES_SUBDIR_NAME);
if(!StorageTk::createPathOnDisk(*this->inodesPath, false) )
throw InvalidConfigException("Unable to create directory: " + inodesPath->str() );
StorageTk::initHashPaths(*inodesPath,
META_INODES_LEVEL1_SUBDIR_NUM, META_INODES_LEVEL2_SUBDIR_NUM);
// buddy mirrored inodes directory
buddyMirrorInodesPath = new Path(META_BUDDYMIRROR_SUBDIR_NAME "/" META_INODES_SUBDIR_NAME);
if(!StorageTk::createPathOnDisk(*this->buddyMirrorInodesPath, false) )
throw InvalidConfigException(
"Unable to create directory: " + buddyMirrorInodesPath->str());
StorageTk::initHashPaths(*buddyMirrorInodesPath,
META_INODES_LEVEL1_SUBDIR_NUM, META_INODES_LEVEL2_SUBDIR_NUM);
// raise file descriptor limit
if(cfg->getTuneProcessFDLimit() )
{
uint64_t oldLimit;
bool setFDLimitRes = System::incProcessFDLimit(cfg->getTuneProcessFDLimit(), &oldLimit);
if(!setFDLimitRes)
log->log(Log_CRITICAL, std::string("Unable to increase process resource limit for "
"number of file handles. Proceeding with default limit: ") +
StringTk::uintToStr(oldLimit) + " " +
"(SysErr: " + System::getErrString() + ")");
}
}
void App::initXAttrLimit()
{
// check whether the filesystem supports overly many amounts of xattrs (>64kb list size).
// of the filesystems we support, this is currently only xfs.
// also check for filesystems mounted beneath the metadata root dir, if any are found, limit the
// xattrs too (it's probably not worth it to check the fs types here, since the setup should be
// rare.)
if (!cfg->getStoreUseExtendedAttribs())
return;
cfg->setLimitXAttrListLength(true);
struct statfs metaRootStat;
if (::statfs(cfg->getStoreMetaDirectory().c_str(), &metaRootStat))
{
LOG(GENERAL, CRITICAL, "Could not statfs() meta root directory.", sysErr);
throw InvalidConfigException("Could not statfs() meta root directory.");
}
// ext3 and ext4 have the same magic, and are currently the only "safe" filesystems officially
// supported.
if (metaRootStat.f_type == EXT3_SUPER_MAGIC)
cfg->setLimitXAttrListLength(false);
else
{
LOG(GENERAL, NOTICE, "Limiting number of xattrs per inode.");
return;
}
// the metadata root directory does not support overly long xattrs. check for filesystems mounted
// beneath the metadata root, and enable xattrs limiting if any are found.
std::string metaRootPath(PATH_MAX, '\0');
if (!realpath(cfg->getStoreMetaDirectory().c_str(), &metaRootPath[0]))
{
LOG(GENERAL, CRITICAL, "Could not check meta root dir for xattr compatibility.", sysErr);
throw InvalidConfigException("Could not check meta root dir for xattr compatibility.");
}
metaRootPath.resize(strlen(metaRootPath.c_str()));
metaRootPath += '/';
FILE* mounts = setmntent("/etc/mtab", "r");
if (!mounts)
{
LOG(GENERAL, CRITICAL, "Could not open mtab.", sysErr);
throw InvalidConfigException("Could not open mtab.");
}
struct mntent mountBuf;
char buf[PATH_MAX * 4];
struct mntent* mount;
errno = 0;
while ((mount = getmntent_r(mounts, &mountBuf, buf, sizeof(buf))))
{
if (strstr(mount->mnt_dir, metaRootPath.c_str()) == mount->mnt_dir)
{
cfg->setLimitXAttrListLength(true);
break;
}
}
endmntent(mounts);
if (errno)
{
LOG(GENERAL, ERR, "Could not read mtab.", sysErr);
throw InvalidConfigException("Could not read mtab.");
}
if (cfg->getLimitXAttrListLength())
LOG(GENERAL, NOTICE, "Limiting number of xattrs per inode.");
}
void App::initRootDir(NumNodeID localNodeNumID)
{
// try to load root dir from disk (through metaStore) or create a new one
this->metaStore = new MetaStore();
// try to reference root directory with buddy mirroring
rootDir = this->metaStore->referenceDir(META_ROOTDIR_ID_STR, true, true);
// if that didn't work try to reference non-buddy-mirrored root dir
if (!rootDir)
{
rootDir = this->metaStore->referenceDir(META_ROOTDIR_ID_STR, false, true);
}
if(rootDir)
{ // loading succeeded (either with or without mirroring => init rootNodeID
this->log->log(Log_NOTICE, "Root directory loaded.");
NumNodeID rootDirOwner = rootDir->getOwnerNodeID();
bool rootIsBuddyMirrored = rootDir->getIsBuddyMirrored();
// try to set rootDirOwner as root node
if (rootDirOwner && metaRoot.setIfDefault(rootDirOwner, rootIsBuddyMirrored))
{ // new root node accepted (check if rootNode is localNode)
NumNodeID primaryRootDirOwner;
if (rootIsBuddyMirrored)
primaryRootDirOwner = NumNodeID(
metaBuddyGroupMapper->getPrimaryTargetID(rootDirOwner.val() ) );
else
primaryRootDirOwner = rootDirOwner;
if(localNodeNumID == primaryRootDirOwner)
{
log->log(Log_CRITICAL, "I got root (by possession of root directory)");
if (rootIsBuddyMirrored)
log->log(Log_CRITICAL, "Root directory is mirrored");
}
else
log->log(Log_CRITICAL,
"Root metadata server (by possession of root directory): " + rootDirOwner.str());
}
}
else
{ // failed to load root directory => create a new rootDir (not mirrored)
this->log->log(Log_CRITICAL,
"This appears to be a new storage directory. Creating a new root dir.");
UInt16Vector stripeTargets;
unsigned defaultChunkSize = this->cfg->getTuneDefaultChunkSize();
unsigned defaultNumStripeTargets = this->cfg->getTuneDefaultNumStripeTargets();
Raid0Pattern stripePattern(defaultChunkSize, stripeTargets, defaultNumStripeTargets);
DirInode newRootDir(META_ROOTDIR_ID_STR,
S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO, 0, 0, NumNodeID(), stripePattern, false);
this->metaStore->makeDirInode(newRootDir);
this->rootDir = this->metaStore->referenceDir(META_ROOTDIR_ID_STR, false, true);
if(!this->rootDir)
{ // error
this->log->logErr("Failed to store root directory. Unable to proceed.");
throw InvalidConfigException("Failed to store root directory");
}
}
}
void App::initDisposalDir()
{
// try to load disposal dir from disk (through metaStore) or create a new one
this->disposalDir = this->metaStore->referenceDir(META_DISPOSALDIR_ID_STR, false, true);
if(this->disposalDir)
{ // loading succeeded
this->log->log(Log_DEBUG, "Disposal directory loaded.");
}
else
{ // failed to load disposal directory => create a new one
this->log->log(Log_DEBUG, "Creating a new disposal directory.");
UInt16Vector stripeTargets;
unsigned defaultChunkSize = this->cfg->getTuneDefaultChunkSize();
unsigned defaultNumStripeTargets = this->cfg->getTuneDefaultNumStripeTargets();
Raid0Pattern stripePattern(defaultChunkSize, stripeTargets, defaultNumStripeTargets);
DirInode newDisposalDir(META_DISPOSALDIR_ID_STR,
S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO, 0, 0, NumNodeID(), stripePattern, false);
this->metaStore->makeDirInode(newDisposalDir);
this->disposalDir = this->metaStore->referenceDir(META_DISPOSALDIR_ID_STR, false, true);
if(!this->disposalDir)
{ // error
this->log->logErr("Failed to store disposal directory. Unable to proceed.");
throw InvalidConfigException("Failed to store disposal directory");
}
}
buddyMirrorDisposalDir = metaStore->referenceDir(META_MIRRORDISPOSALDIR_ID_STR, true, true);
if(buddyMirrorDisposalDir)
{ // loading succeeded
log->log(Log_DEBUG, "Mirrored disposal directory loaded.");
}
else
{ // failed to load disposal directory => create a new one
log->log(Log_DEBUG, "Creating a new mirrored disposal directory.");
UInt16Vector stripeTargets;
unsigned defaultChunkSize = cfg->getTuneDefaultChunkSize();
unsigned defaultNumStripeTargets = cfg->getTuneDefaultNumStripeTargets();
Raid0Pattern stripePattern(defaultChunkSize, stripeTargets, defaultNumStripeTargets);
DirInode newDisposalDir(META_MIRRORDISPOSALDIR_ID_STR,
S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO, 0, 0, NumNodeID(), stripePattern, true);
metaStore->makeDirInode(newDisposalDir);
buddyMirrorDisposalDir = metaStore->referenceDir(META_MIRRORDISPOSALDIR_ID_STR, true, true);
if(!buddyMirrorDisposalDir)
{ // error
log->logErr("Failed to store mirrored disposal directory. Unable to proceed.");
throw InvalidConfigException("Failed to store mirrored disposal directory");
}
}
}
void App::initComponents(TargetConsistencyState initialConsistencyState)
{
this->log->log(Log_DEBUG, "Initializing components...");
this->dgramListener = new DatagramListener(
netFilter, localNicList, ackStore, cfg->getConnMetaPortUDP() );
if(cfg->getTuneListenerPrioShift() )
dgramListener->setPriorityShift(cfg->getTuneListenerPrioShift() );
streamListenersInit();
unsigned short listenPort = cfg->getConnMetaPortTCP();
this->connAcceptor = new ConnAcceptor(this, localNicList, listenPort);
this->statsCollector = new StatsCollector(workQueue, STATSCOLLECTOR_COLLECT_INTERVAL_MS,
STATSCOLLECTOR_HISTORY_LENGTH);
this->buddyResyncer = new BuddyResyncer();
this->internodeSyncer = new InternodeSyncer(initialConsistencyState);
this->modificationEventFlusher = new ModificationEventFlusher();
workersInit();
commSlavesInit();
this->log->log(Log_DEBUG, "Components initialized.");
}
void App::startComponents()
{
log->log(Log_DEBUG, "Starting up components...");
// make sure child threads don't receive SIGINT/SIGTERM (blocked signals are inherited)
PThread::blockInterruptSignals();
timerQueue->start();
gcQueue->start();
this->dgramListener->start();
// wait for nodes list download before we start handling client requests
PThread::unblockInterruptSignals(); // temporarily unblock interrupt, so user can cancel waiting
PThread::blockInterruptSignals(); // reblock signals for next child threads
streamListenersStart();
this->connAcceptor->start();
this->statsCollector->start();
this->internodeSyncer->start();
timerQueue->enqueue(std::chrono::minutes(5),
[] { InternodeSyncer::downloadAndSyncClients(true); });
this->modificationEventFlusher->start();
if(const auto wait = getConfig()->getTuneDisposalGCPeriod()) {
this->gcQueue->enqueue(std::chrono::seconds(wait), disposalGarbageCollector);
}
workersStart();
commSlavesStart();
PThread::unblockInterruptSignals(); // main app thread may receive SIGINT/SIGTERM
log->log(Log_DEBUG, "Components running.");
}
void App::stopComponents()
{
SAFE_DELETE(this->gcQueue);
// note: this method may not wait for termination of the components, because that could
// lead to a deadlock (when calling from signal handler)
// note: no commslave stop here, because that would keep workers from terminating
if(modificationEventFlusher) // The modificationEventFlusher has to be stopped before the
// workers, because it tries to notify all the workers about the
// changed modification state.
modificationEventFlusher->selfTerminate();
// resyncer wants to control the workers, so any running resync must be finished or aborted
// before the workers are stopped.
if(buddyResyncer)
buddyResyncer->shutdown();
workersStop();
if(internodeSyncer)
internodeSyncer->selfTerminate();
if(statsCollector)
statsCollector->selfTerminate();
if(connAcceptor)
connAcceptor->selfTerminate();
streamListenersStop();
if(dgramListener)
{
dgramListener->selfTerminate();
dgramListener->sendDummyToSelfUDP(); // for faster termination
}
this->selfTerminate(); /* this flag can be noticed by thread-independent methods and is also
required e.g. to let App::waitForMgmtNode() know that it should cancel */
}
/**
* Handles expections that lead to the termination of a component.
* Initiates an application shutdown.
*/
void App::handleComponentException(std::exception& e)
{
const char* logContext = "App (component exception handler)";
LogContext log(logContext);
const auto componentName = PThread::getCurrentThreadName();
log.logErr(
"The component [" + componentName + "] encountered an unrecoverable error. " +
std::string("[SysErr: ") + System::getErrString() + "] " +
std::string("Exception message: ") + e.what() );
log.log(Log_WARNING, "Shutting down...");
stopComponents();
}
void App::joinComponents()
{
log->log(Log_DEBUG, "Joining component threads...");
/* (note: we need one thread for which we do an untimed join, so this should be a quite reliably
terminating thread) */
statsCollector->join();
workersJoin();
waitForComponentTermination(modificationEventFlusher);
waitForComponentTermination(dgramListener);
waitForComponentTermination(connAcceptor);
streamListenersJoin();
waitForComponentTermination(internodeSyncer);
commSlavesStop(); // placed here because otherwise it would keep workers from terminating
commSlavesJoin();
}
void App::streamListenersInit()
{
this->numStreamListeners = cfg->getTuneNumStreamListeners();
for(unsigned i=0; i < numStreamListeners; i++)
{
StreamListenerV2* listener = new StreamListenerV2(
std::string("StreamLis") + StringTk::uintToStr(i+1), this, workQueue);
if(cfg->getTuneListenerPrioShift() )
listener->setPriorityShift(cfg->getTuneListenerPrioShift() );
if(cfg->getTuneUseAggressiveStreamPoll() )
listener->setUseAggressivePoll();
streamLisVec.push_back(listener);
}
}
void App::workersInit()
{
unsigned numWorkers = cfg->getTuneNumWorkers();
for(unsigned i=0; i < numWorkers; i++)
{
Worker* worker = new Worker(
std::string("Worker") + StringTk::uintToStr(i+1), workQueue, QueueWorkType_INDIRECT);
worker->setBufLens(cfg->getTuneWorkerBufSize(), cfg->getTuneWorkerBufSize() );
workerList.push_back(worker);
}
for(unsigned i=0; i < APP_WORKERS_DIRECT_NUM; i++)
{
Worker* worker = new Worker(
std::string("DirectWorker") + StringTk::uintToStr(i+1), workQueue, QueueWorkType_DIRECT);
worker->setBufLens(cfg->getTuneWorkerBufSize(), cfg->getTuneWorkerBufSize() );
workerList.push_back(worker);
}
}
void App::commSlavesInit()
{
unsigned numCommSlaves = cfg->getTuneNumCommSlaves();
for(unsigned i=0; i < numCommSlaves; i++)
{
Worker* worker = new Worker(
std::string("CommSlave") + StringTk::uintToStr(i+1), commSlaveQueue, QueueWorkType_DIRECT);
worker->setBufLens(cfg->getTuneCommSlaveBufSize(), cfg->getTuneCommSlaveBufSize() );
commSlaveList.push_back(worker);
}
}
void App::streamListenersStart()
{
unsigned numNumaNodes = System::getNumNumaNodes();
for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++)
{
if(cfg->getTuneListenerNumaAffinity() )
(*iter)->startOnNumaNode( (++nextNumaBindTarget) % numNumaNodes);
else
(*iter)->start();
}
}
void App::workersStart()
{
unsigned numNumaNodes = System::getNumNumaNodes();
for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++)
{
if(cfg->getTuneWorkerNumaAffinity() )
(*iter)->startOnNumaNode( (++nextNumaBindTarget) % numNumaNodes);
else
(*iter)->start();
}
}
void App::commSlavesStart()
{
unsigned numNumaNodes = System::getNumNumaNodes();
for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++)
{
if(cfg->getTuneWorkerNumaAffinity() )
(*iter)->startOnNumaNode( (++nextNumaBindTarget) % numNumaNodes);
else
(*iter)->start();
}
}
void App::streamListenersStop()
{
for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++)
{
(*iter)->selfTerminate();
}
}
void App::workersStop()
{
for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++)
{
(*iter)->selfTerminate();
// add dummy work to wake up the worker immediately for faster self termination
PersonalWorkQueue* personalQ = (*iter)->getPersonalWorkQueue();
workQueue->addPersonalWork(new DummyWork(), personalQ);
}
}
void App::commSlavesStop()
{
// need two loops because we don't know if the worker that handles the work will be the same that
// received the self-terminate-request
for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++)
{
(*iter)->selfTerminate();
}
for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++)
{
commSlaveQueue->addDirectWork(new DummyWork() );
}
}
void App::streamListenersDelete()
{
for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++)
{
delete(*iter);
}
streamLisVec.clear();
}
void App::workersDelete()
{
for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++)
{
delete(*iter);
}
workerList.clear();
}
void App::commSlavesDelete()
{
for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++)
{
delete(*iter);
}
commSlaveList.clear();
}
void App::streamListenersJoin()
{
for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++)
{
waitForComponentTermination(*iter);
}
}
void App::workersJoin()
{
for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++)
{
waitForComponentTermination(*iter);
}
}
void App::commSlavesJoin()
{
for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++)
{
waitForComponentTermination(*iter);
}
}
void App::logInfos()
{
// print software version (CONGFS_VERSION)
log->log(Log_CRITICAL, std::string("Version: ") + CONGFS_VERSION);
// print debug version info
LOG_DEBUG_CONTEXT(*log, Log_CRITICAL, "--DEBUG VERSION--");
// print local nodeIDs
log->log(Log_WARNING, "LocalNode: " + localNode->getNodeIDWithTypeStr() );
// list usable network interfaces
NicAddressList nicList(localNode->getNicList() );
std::string nicListStr;
std::string extendedNicListStr;
for (NicAddressListIter nicIter = nicList.begin(); nicIter != nicList.end(); nicIter++)
{
std::string nicTypeStr;
if (nicIter->nicType == NICADDRTYPE_RDMA)
nicTypeStr = "RDMA";
else if (nicIter->nicType == NICADDRTYPE_SDP)
nicTypeStr = "SDP";
else if (nicIter->nicType == NICADDRTYPE_STANDARD)
nicTypeStr = "TCP";
else
nicTypeStr = "Unknown";
nicListStr += " " + std::string(nicIter->name) + "(" + nicTypeStr + ")";
extendedNicListStr += "\n+ " + NetworkInterfaceCard::nicAddrToString(&(*nicIter) );
}
log->log(Log_WARNING, std::string("Usable NICs:") + nicListStr);
log->log(Log_DEBUG, std::string("Extended list of usable NICs:") + extendedNicListStr);
// print net filters
if(netFilter->getNumFilterEntries() )
{
log->log(Log_WARNING, std::string("Net filters: ") +
StringTk::uintToStr(netFilter->getNumFilterEntries() ) );
}
if(tcpOnlyFilter->getNumFilterEntries() )
{
this->log->log(Log_WARNING, std::string("TCP-only filters: ") +
StringTk::uintToStr(tcpOnlyFilter->getNumFilterEntries() ) );
}
// print numa info
// (getTuneBindToNumaZone==-1 means disable binding)
if(cfg->getTuneListenerNumaAffinity() || cfg->getTuneWorkerNumaAffinity() ||
(cfg->getTuneBindToNumaZone() != -1) )
{
unsigned numNumaNodes = System::getNumNumaNodes();
/* note: we use the term "numa areas" instead of "numa nodes" in log messages to avoid
confusion with cluster "nodes" */
log->log(Log_NOTICE, std::string("NUMA areas: ") + StringTk::uintToStr(numNumaNodes) );
for(unsigned nodeNum=0; nodeNum < numNumaNodes; nodeNum++)
{ // print core list for each numa node
cpu_set_t cpuSet;
System::getNumaCoresByNode(nodeNum, &cpuSet);
// create core list for current numa node
std::string coreListStr;
for(unsigned coreNum = 0; coreNum < CPU_SETSIZE; coreNum++)
{
if(CPU_ISSET(coreNum, &cpuSet) )
coreListStr += StringTk::uintToStr(coreNum) + " ";
}
log->log(Log_SPAM, "NUMA area " + StringTk::uintToStr(nodeNum) + " cores: " + coreListStr);
}
}
}
void App::daemonize()
{
int nochdir = 1; // 1 to keep working directory
int noclose = 0; // 1 to keep stdin/-out/-err open
log->log(Log_DEBUG, std::string("Detaching process...") );
int detachRes = daemon(nochdir, noclose);
if(detachRes == -1)
throw InvalidConfigException(std::string("Unable to detach process. SysErr: ") +
System::getErrString() );
updateLockedPIDFile(pidFileLockFD); // ignored if pidFileFD is -1
}
void App::registerSignalHandler()
{
signal(SIGINT, App::signalHandler);
signal(SIGTERM, App::signalHandler);
}
void App::signalHandler(int sig)
{
App* app = Program::getApp();
Logger* log = Logger::getLogger();
const char* logContext = "App::signalHandler";
// note: this might deadlock if the signal was thrown while the logger mutex is locked by the
// application thread (depending on whether the default mutex style is recursive). but
// even recursive mutexes are not acceptable in this case.
// we need something like a timed lock for the log mutex. if it succeeds within a
// few seconds, we know that we didn't hold the mutex lock. otherwise we simply skip the
// log message. this will only work if the mutex is non-recusive (which is unknown for
// the default mutex style).
// but it is very unlikely that the application thread holds the log mutex, because it
// joins the component threads and so it doesn't do anything else but sleeping!
switch(sig)
{
case SIGINT:
{
signal(sig, SIG_DFL); // reset the handler to its default
log->log(Log_CRITICAL, logContext, "Received a SIGINT. Shutting down...");
} break;
case SIGTERM:
{
signal(sig, SIG_DFL); // reset the handler to its default
log->log(Log_CRITICAL, logContext, "Received a SIGTERM. Shutting down...");
} break;
default:
{
signal(sig, SIG_DFL); // reset the handler to its default
log->log(Log_CRITICAL, logContext, "Received an unknown signal. Shutting down...");
} break;
}
app->stopComponents();
}
/**
* Request mgmt heartbeat and wait for the mgmt node to appear in nodestore.
*
* @return true if mgmt heartbeat received, false on error or thread selftermination order
*/
bool App::waitForMgmtNode()
{
const unsigned waitTimeoutMS = 0; // infinite wait
const unsigned nameResolutionRetries = 3;
unsigned udpListenPort = cfg->getConnMetaPortUDP();
unsigned udpMgmtdPort = cfg->getConnMgmtdPortUDP();
std::string mgmtdHost = cfg->getSysMgmtdHost();
RegistrationDatagramListener regDGramLis(netFilter, localNicList, ackStore, udpListenPort);
regDGramLis.start();
log->log(Log_CRITICAL, "Waiting for congfs-mgmtd@" +
mgmtdHost + ":" + StringTk::uintToStr(udpMgmtdPort) + "...");
bool gotMgmtd = NodesTk::waitForMgmtHeartbeat(
this, ®DGramLis, mgmtNodes, mgmtdHost, udpMgmtdPort, waitTimeoutMS, nameResolutionRetries);
regDGramLis.selfTerminate();
regDGramLis.sendDummyToSelfUDP(); // for faster termination
regDGramLis.join();
return gotMgmtd;
}
/**
* Pre-register node to get a numeric ID from mgmt.
*
* @return true if pre-registration successful and localNodeNumID set.
*/
bool App::preregisterNode(std::string& localNodeID, NumNodeID& outLocalNodeNumID)
{
static bool registrationFailureLogged = false; // to avoid log spamming
auto mgmtNode = mgmtNodes->referenceFirstNode();
if(!mgmtNode)
{
log->logErr("Unexpected: No management node found in store during node pre-registration.");
return false;
}
NumNodeID rootNodeID = metaRoot.getID();
RegisterNodeMsg msg(localNodeID, outLocalNodeNumID, NODETYPE_Meta, &localNicList,
cfg->getConnMetaPortUDP(), cfg->getConnMetaPortTCP() );
msg.setRootNumID(rootNodeID);
Time startTime;
Time lastRetryTime;
unsigned nextRetryDelayMS = 0;
// wait for mgmt node to appear and periodically resend request
/* note: we usually expect not to loop here, because we already waited for mgmtd in
waitForMgmtNode(), so mgmt should respond immediately. */
while(!outLocalNodeNumID && !getSelfTerminate() )
{
if(lastRetryTime.elapsedMS() < nextRetryDelayMS)
{ // wait some time between retries
waitForSelfTerminateOrder(nextRetryDelayMS);
if(getSelfTerminate() )
break;
}
const auto respMsg = MessagingTk::requestResponse(*mgmtNode, msg,
NETMSGTYPE_RegisterNodeResp);
if (respMsg)
{ // communication successful
RegisterNodeRespMsg* respMsgCast = (RegisterNodeRespMsg*)respMsg.get();
outLocalNodeNumID = respMsgCast->getNodeNumID();
if(!outLocalNodeNumID)
{ // mgmt rejected our registration
log->logErr("ID reservation request was rejected by this mgmt node: " +
mgmtNode->getTypedNodeID() );
}
else
log->log(Log_WARNING, "Node ID reservation successful.");
break;
}
// comm failed => log status message
if(!registrationFailureLogged)
{
log->log(Log_CRITICAL, "Node ID reservation failed. Management node offline? "
"Will keep on trying...");
registrationFailureLogged = true;
}
// calculate next retry wait time
lastRetryTime.setToNow();
nextRetryDelayMS = NodesTk::getRetryDelayMS(startTime.elapsedMS() );
}
return bool(outLocalNodeNumID);
}
/**
* Downloads the list of nodes, targets and buddy groups (for meta and storage servers) from the
* mgmtd.
*
* @param outInitialConsistencyState The consistency state the local meta node has on the mgmtd
* before any state reports are sent.
*/
bool App::downloadMgmtInfo(TargetConsistencyState& outInitialConsistencyState)
{
Config* cfg = this->getConfig();
int retrySleepTimeMS = 10000; // 10sec
unsigned udpListenPort = cfg->getConnMetaPortUDP();
bool allSuccessful = false;
// start temporary registration datagram listener
RegistrationDatagramListener regDGramLis(netFilter, localNicList, ackStore, udpListenPort);
regDGramLis.start();
// loop until we're registered and everything is downloaded (or until we got interrupted)
do
{
// register ourselves
// (note: node registration needs to be done before downloads to get notified of updates)
if (!InternodeSyncer::registerNode(®DGramLis) )
continue;
// download all mgmt info the HBM cares for
if (!InternodeSyncer::downloadAndSyncNodes() ||
!InternodeSyncer::downloadAndSyncTargetMappings() ||
!InternodeSyncer::downloadAndSyncStoragePools() ||
!InternodeSyncer::downloadAndSyncTargetStatesAndBuddyGroups() ||
!InternodeSyncer::updateMetaCapacityPools() ||
!InternodeSyncer::updateMetaBuddyCapacityPools())
continue;
InternodeSyncer::downloadAndSyncClients(false);
// ...and then the InternodeSyncer's part.
if (!InternodeSyncer::updateMetaStatesAndBuddyGroups(outInitialConsistencyState, false) )
continue;
if(!InternodeSyncer::downloadAllExceededQuotaLists(storagePoolStore->getPoolsAsVec()))
continue;
allSuccessful = true;
break;
} while(!waitForSelfTerminateOrder(retrySleepTimeMS) );
// stop temporary registration datagram listener
regDGramLis.selfTerminate();
regDGramLis.sendDummyToSelfUDP(); // for faster termination
regDGramLis.join();
if(allSuccessful)
log->log(Log_NOTICE, "Registration and management info download complete.");
return allSuccessful;
}
bool App::restoreSessions()
{
bool retVal = true;
std::string path = this->metaPathStr + "/" + std::string(STORAGETK_SESSIONS_BACKUP_FILE_NAME);
std::string mpath = this->metaPathStr + "/" + std::string(STORAGETK_MSESSIONS_BACKUP_FILE_NAME);
bool pathRes = StorageTk::pathExists(path);
bool mpathRes = StorageTk::pathExists(mpath);
if (!pathRes && !mpathRes)
return false;
if (pathRes)
{
bool loadRes = this->sessions->loadFromFile(path, *metaStore);
if (!loadRes)
{
log->logErr("Could not restore all sessions");
retVal = false;
}
}
if (mpathRes)
{
bool loadRes = this->mirroredSessions->loadFromFile(mpath, *metaStore);
if (!loadRes)
{
log->logErr("Could not restore all mirrored sessions");
retVal = false;
}
}
log->log(Log_NOTICE, "Restored "
+ StringTk::uintToStr(sessions->getSize()) + " sessions and "
+ StringTk::uintToStr(mirroredSessions->getSize()) + " mirrored sessions");
return retVal;
}
bool App::storeSessions()
{
bool retVal = true;
std::string path = this->metaPathStr + "/" + std::string(STORAGETK_SESSIONS_BACKUP_FILE_NAME);
std::string mpath = this->metaPathStr + "/" + std::string(STORAGETK_MSESSIONS_BACKUP_FILE_NAME);
if (StorageTk::pathExists(path))
log->log(Log_WARNING, "Overwriting existing session file");
bool saveRes = this->sessions->saveToFile(path);
if(!saveRes)
{
this->log->logErr("Could not store all sessions to file " + path);
retVal = false;
}
if (StorageTk::pathExists(mpath))
log->log(Log_WARNING, "Overwriting existing mirror session file");
saveRes = this->mirroredSessions->saveToFile(mpath);
if(!saveRes)
{
this->log->logErr("Could not store all mirror sessions to file " + mpath);
retVal = false;
}
if (retVal)
log->log(Log_NOTICE, "Stored "
+ StringTk::uintToStr(sessions->getSize()) + " sessions and "
+ StringTk::uintToStr(mirroredSessions->getSize()) + " mirrored sessions");
return retVal;
}
bool App::deleteSessionFiles()
{
bool retVal = true;
std::string path = this->metaPathStr + "/" + std::string(STORAGETK_SESSIONS_BACKUP_FILE_NAME);
std::string mpath = this->metaPathStr + "/" + std::string(STORAGETK_MSESSIONS_BACKUP_FILE_NAME);
bool pathRes = StorageTk::pathExists(path);
bool mpathRes = StorageTk::pathExists(mpath);
if (!pathRes && !mpathRes)
return retVal;
if (pathRes && remove(path.c_str()))
{
log->logErr("Could not remove sessions file");
retVal = false;
}
if (mpathRes && remove(mpath.c_str()))
{
log->logErr("Could not remove mirrored sessions file");
retVal = false;
}
return retVal;
}
void App::checkTargetUUID()
{
if (!cfg->getStoreFsUUID().empty())
{
Path metaPath(cfg->getStoreMetaDirectory() );
// Find out device numbers of underlying device
struct stat st;
if (stat(metaPath.str().c_str(), &st)) {
throw InvalidConfigException("Could not stat metadata directory: " + metaPathStr);
}
// look for the device path
std::ifstream mountInfo("/proc/self/mountinfo");
if (!mountInfo) {
throw InvalidConfigException("Could not open /proc/self/mountinfo");
}
std::string line, device_path, device_majmin;
while (std::getline(mountInfo, line)) {
std::istringstream is(line);
std::string dummy;
is >> dummy >> dummy >> device_majmin >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> device_path;
auto majmin_f = boost::format("%1%:%2%") % (st.st_dev >> 8) % (st.st_dev & 0xFF);
if (majmin_f.str() == device_majmin)
break;
device_path = "";
}
if (device_path.empty()) {
throw InvalidConfigException("Could not find a device path that belongs to device " + device_majmin);
}
// Lookup the fs UUID
std::unique_ptr<blkid_struct_probe, void(*)(blkid_struct_probe*)>
probe(blkid_new_probe_from_filename(device_path.data()), blkid_free_probe);
if (!probe) {
throw InvalidConfigException("Failed to open device for probing: " + device_path);
}
if (blkid_probe_enable_superblocks(probe.get(), 1) < 0) {
throw InvalidConfigException("Failed to enable superblock probing");
}
if (blkid_do_fullprobe(probe.get()) < 0) {
throw InvalidConfigException("Failed to probe device");
}
const char* uuid = nullptr; // gets released automatically
if (blkid_probe_lookup_value(probe.get(), "UUID", &uuid, nullptr) < 0) {
throw InvalidConfigException("Failed to lookup file system UUID");
}
std::string uuid_str(uuid);
if (cfg->getStoreFsUUID() != uuid_str)
{
throw InvalidConfigException("UUID of the metadata file system (" + uuid_str
+ ") does not match the one configured (" + cfg->getStoreFsUUID() + ")");
}
}
else
{
LOG(GENERAL, WARNING, "UUID of underlying file system has not conn configured and will "
"therefore not be checked. To prevent starting the server accidentally with the wrong "
"data, it is strongly recommended to set the storeFsUUID config parameter to "
"the appropriate UUID.");
}
}
| 32.179904 | 116 | 0.687116 | congweitao |
c1ea541864e67d3598c7f0f9c36cdd7ca95d8c4f | 10,990 | cpp | C++ | interface/src/ui/HMDToolsDialog.cpp | stojce/hifi | 8e6c860a243131859c0706424097db56e6a604bd | [
"Apache-2.0"
] | null | null | null | interface/src/ui/HMDToolsDialog.cpp | stojce/hifi | 8e6c860a243131859c0706424097db56e6a604bd | [
"Apache-2.0"
] | null | null | null | interface/src/ui/HMDToolsDialog.cpp | stojce/hifi | 8e6c860a243131859c0706424097db56e6a604bd | [
"Apache-2.0"
] | null | null | null | //
// HMDToolsDialog.cpp
// interface/src/ui
//
// Created by Brad Hefta-Gaub on 7/19/13.
// Copyright 2013 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <QDesktopWidget>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QGuiApplication>
#include <QLabel>
#include <QPushButton>
#include <QString>
#include <QScreen>
#include <QWindow>
#include <plugins/PluginManager.h>
#include <display-plugins/DisplayPlugin.h>
#include "Application.h"
#include "MainWindow.h"
#include "Menu.h"
#include "ui/DialogsManager.h"
#include "ui/HMDToolsDialog.h"
static const int WIDTH = 350;
static const int HEIGHT = 100;
HMDToolsDialog::HMDToolsDialog(QWidget* parent) :
QDialog(parent, Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint)
{
// FIXME do we want to support more than one connected HMD? It seems like a pretty corner case
foreach(auto displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) {
// The first plugin is always the standard 2D display, by convention
if (_defaultPluginName.isEmpty()) {
_defaultPluginName = displayPlugin->getName();
continue;
}
if (displayPlugin->isHmd()) {
// Not all HMD's have corresponding screens
if (displayPlugin->getHmdScreen() >= 0) {
_hmdScreenNumber = displayPlugin->getHmdScreen();
}
_hmdPluginName = displayPlugin->getName();
break;
}
}
setWindowTitle("HMD Tools");
// Create layouter
{
QFormLayout* form = new QFormLayout();
// Add a button to enter
_switchModeButton = new QPushButton("Toggle HMD Mode");
if (_hmdPluginName.isEmpty()) {
_switchModeButton->setEnabled(false);
}
// Add a button to enter
_switchModeButton->setFixedWidth(WIDTH);
form->addRow("", _switchModeButton);
// Create a label with debug details...
_debugDetails = new QLabel();
_debugDetails->setFixedSize(WIDTH, HEIGHT);
form->addRow("", _debugDetails);
setLayout(form);
}
qApp->getWindow()->activateWindow();
// watch for our dialog window moving screens. If it does we want to enforce our rules about
// what screens we're allowed on
watchWindow(windowHandle());
auto dialogsManager = DependencyManager::get<DialogsManager>();
if (qApp->getRunningScriptsWidget()) {
watchWindow(qApp->getRunningScriptsWidget()->windowHandle());
}
if (qApp->getToolWindow()) {
watchWindow(qApp->getToolWindow()->windowHandle());
}
if (dialogsManager->getBandwidthDialog()) {
watchWindow(dialogsManager->getBandwidthDialog()->windowHandle());
}
if (dialogsManager->getOctreeStatsDialog()) {
watchWindow(dialogsManager->getOctreeStatsDialog()->windowHandle());
}
if (dialogsManager->getLodToolsDialog()) {
watchWindow(dialogsManager->getLodToolsDialog()->windowHandle());
}
connect(_switchModeButton, &QPushButton::clicked, [this]{
toggleHMDMode();
});
// when the application is about to quit, leave HDM mode
connect(qApp, &Application::beforeAboutToQuit, [this]{
// FIXME this is ineffective because it doesn't trigger the menu to
// save the fact that VR Mode is not checked.
leaveHMDMode();
});
connect(qApp, &Application::activeDisplayPluginChanged, [this]{
updateUi();
});
// watch for our application window moving screens. If it does we want to update our screen details
QWindow* mainWindow = qApp->getWindow()->windowHandle();
connect(mainWindow, &QWindow::screenChanged, [this]{
updateUi();
});
// keep track of changes to the number of screens
connect(QApplication::desktop(), &QDesktopWidget::screenCountChanged, this, &HMDToolsDialog::screenCountChanged);
updateUi();
}
HMDToolsDialog::~HMDToolsDialog() {
foreach(HMDWindowWatcher* watcher, _windowWatchers) {
delete watcher;
}
_windowWatchers.clear();
}
QString HMDToolsDialog::getDebugDetails() const {
QString results;
if (_hmdScreenNumber >= 0) {
results += "HMD Screen: " + QGuiApplication::screens()[_hmdScreenNumber]->name() + "\n";
} else {
results += "HMD Screen Name: N/A\n";
}
int desktopPrimaryScreenNumber = QApplication::desktop()->primaryScreen();
QScreen* desktopPrimaryScreen = QGuiApplication::screens()[desktopPrimaryScreenNumber];
results += "Desktop's Primary Screen: " + desktopPrimaryScreen->name() + "\n";
results += "Application Primary Screen: " + QGuiApplication::primaryScreen()->name() + "\n";
QScreen* mainWindowScreen = qApp->getWindow()->windowHandle()->screen();
results += "Application Main Window Screen: " + mainWindowScreen->name() + "\n";
results += "Total Screens: " + QString::number(QApplication::desktop()->screenCount()) + "\n";
return results;
}
void HMDToolsDialog::toggleHMDMode() {
if (!qApp->isHMDMode()) {
enterHMDMode();
} else {
leaveHMDMode();
}
}
void HMDToolsDialog::enterHMDMode() {
if (!qApp->isHMDMode()) {
qApp->setActiveDisplayPlugin(_hmdPluginName);
qApp->getWindow()->activateWindow();
}
}
void HMDToolsDialog::leaveHMDMode() {
if (qApp->isHMDMode()) {
qApp->setActiveDisplayPlugin(_defaultPluginName);
qApp->getWindow()->activateWindow();
}
}
void HMDToolsDialog::reject() {
// We don't want this window to be closable from a close icon, just from our "Leave HMD Mode" button
}
void HMDToolsDialog::closeEvent(QCloseEvent* event) {
// We don't want this window to be closable from a close icon, just from our "Leave HMD Mode" button
event->ignore();
}
void HMDToolsDialog::centerCursorOnWidget(QWidget* widget) {
QWindow* window = widget->windowHandle();
QScreen* screen = window->screen();
QPoint windowCenter = window->geometry().center();
QCursor::setPos(screen, windowCenter);
}
void HMDToolsDialog::updateUi() {
_switchModeButton->setText(qApp->isHMDMode() ? "Leave HMD Mode" : "Enter HMD Mode");
_debugDetails->setText(getDebugDetails());
}
void HMDToolsDialog::showEvent(QShowEvent* event) {
// center the cursor on the hmd tools dialog
centerCursorOnWidget(this);
updateUi();
}
void HMDToolsDialog::hideEvent(QHideEvent* event) {
// center the cursor on the main application window
centerCursorOnWidget(qApp->getWindow());
}
void HMDToolsDialog::screenCountChanged(int newCount) {
int hmdScreenNumber = -1;
auto displayPlugins = PluginManager::getInstance()->getDisplayPlugins();
foreach(auto dp, displayPlugins) {
if (dp->isHmd()) {
if (dp->getHmdScreen() >= 0) {
hmdScreenNumber = dp->getHmdScreen();
}
break;
}
}
if (qApp->isHMDMode() && _hmdScreenNumber != hmdScreenNumber) {
qDebug() << "HMD Display changed WHILE IN HMD MODE";
leaveHMDMode();
// if there is a new best HDM screen then go back into HDM mode after done leaving
if (hmdScreenNumber >= 0) {
qDebug() << "Trying to go back into HMD Mode";
const int SLIGHT_DELAY = 2000;
QTimer::singleShot(SLIGHT_DELAY, [this]{
enterHMDMode();
});
}
}
}
void HMDToolsDialog::watchWindow(QWindow* window) {
qDebug() << "HMDToolsDialog::watchWindow() window:" << window;
if (window && !_windowWatchers.contains(window)) {
HMDWindowWatcher* watcher = new HMDWindowWatcher(window, this);
_windowWatchers[window] = watcher;
}
}
HMDWindowWatcher::HMDWindowWatcher(QWindow* window, HMDToolsDialog* hmdTools) :
_window(window),
_hmdTools(hmdTools),
_previousScreen(NULL)
{
connect(window, &QWindow::screenChanged, this, &HMDWindowWatcher::windowScreenChanged);
connect(window, &QWindow::xChanged, this, &HMDWindowWatcher::windowGeometryChanged);
connect(window, &QWindow::yChanged, this, &HMDWindowWatcher::windowGeometryChanged);
connect(window, &QWindow::widthChanged, this, &HMDWindowWatcher::windowGeometryChanged);
connect(window, &QWindow::heightChanged, this, &HMDWindowWatcher::windowGeometryChanged);
}
HMDWindowWatcher::~HMDWindowWatcher() {
}
void HMDWindowWatcher::windowGeometryChanged(int arg) {
_previousRect = _window->geometry();
_previousScreen = _window->screen();
}
void HMDWindowWatcher::windowScreenChanged(QScreen* screen) {
// if we have more than one screen, and a known hmdScreen then try to
// keep our dialog off of the hmdScreen
if (QApplication::desktop()->screenCount() > 1) {
int hmdScreenNumber = _hmdTools->_hmdScreenNumber;
// we want to use a local variable here because we are not necesarily in HMD mode
if (hmdScreenNumber >= 0) {
QScreen* hmdScreen = QGuiApplication::screens()[hmdScreenNumber];
if (screen == hmdScreen) {
qDebug() << "HMD Tools: Whoa! What are you doing? You don't want to move me to the HMD Screen!";
// try to pick a better screen
QScreen* betterScreen = NULL;
QScreen* lastApplicationScreen = _hmdTools->getLastApplicationScreen();
QWindow* appWindow = qApp->getWindow()->windowHandle();
QScreen* appScreen = appWindow->screen();
if (_previousScreen && _previousScreen != hmdScreen) {
// first, if the previous dialog screen is not the HMD screen, then move it there.
betterScreen = _previousScreen;
} else if (appScreen != hmdScreen) {
// second, if the application screen is not the HMD screen, then move it there.
betterScreen = appScreen;
} else if (lastApplicationScreen && lastApplicationScreen != hmdScreen) {
// third, if the application screen is the HMD screen, we want to move it to
// the previous screen
betterScreen = lastApplicationScreen;
} else {
// last, if we can't use the previous screen the use the primary desktop screen
int desktopPrimaryScreenNumber = QApplication::desktop()->primaryScreen();
QScreen* desktopPrimaryScreen = QGuiApplication::screens()[desktopPrimaryScreenNumber];
betterScreen = desktopPrimaryScreen;
}
if (betterScreen) {
_window->setScreen(betterScreen);
_window->setGeometry(_previousRect);
}
}
}
}
}
| 35.566343 | 117 | 0.643494 | stojce |
c1eba672963c36e8552c0fe8c60afb71af5652cc | 1,423 | hpp | C++ | contrib/libboost/boost_1_62_0/boost/container/pmr/string.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 34,359 | 2019-05-06T21:04:42.000Z | 2019-05-14T22:06:43.000Z | contrib/libboost/boost_1_62_0/boost/container/pmr/string.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | contrib/libboost/boost_1_62_0/boost/container/pmr/string.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 3,164 | 2019-05-06T21:06:01.000Z | 2019-05-14T20:25:52.000Z | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2015-2015. 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)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_PMR_STRING_HPP
#define BOOST_CONTAINER_PMR_STRING_HPP
#if defined (_MSC_VER)
# pragma once
#endif
#include <boost/container/string.hpp>
#include <boost/container/pmr/polymorphic_allocator.hpp>
namespace boost {
namespace container {
namespace pmr {
#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
template <class CharT, class Traits = std::char_traits<CharT> >
using basic_string =
boost::container::basic_string<CharT, Traits, polymorphic_allocator<CharT> >;
#endif
//! A portable metafunction to obtain a basic_string
//! that uses a polymorphic allocator
template <class CharT, class Traits = std::char_traits<CharT> >
struct basic_string_of
{
typedef boost::container::basic_string
<CharT, Traits, polymorphic_allocator<CharT> > type;
};
typedef basic_string_of<char>::type string;
typedef basic_string_of<wchar_t>::type wstring;
} //namespace pmr {
} //namespace container {
} //namespace boost {
#endif //BOOST_CONTAINER_PMR_STRING_HPP
| 27.901961 | 80 | 0.676739 | 189569400 |
c1ebb858399d6f1bc45ed8a3474fa112d4477bf5 | 3,443 | cpp | C++ | Viewer/libViewer/src/IconProvider.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | Viewer/libViewer/src/IconProvider.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | Viewer/libViewer/src/IconProvider.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | //============================================================================
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
//============================================================================
#include "IconProvider.hpp"
#include <QDebug>
#include <QImage>
#include <QImageReader>
#include <QPainter>
#include "UiLog.hpp"
static UnknownIconItem unknownIcon(":/desktop/unknown.svg");
static IconItem linkIcon(":/desktop/link.svg");
static IconItem linkBrokenIcon(":/desktop/link_broken.svg");
static IconItem lockIcon(":/viewer/padlock.svg");
static IconItem warningIcon(":/viewer/warning.svg");
static IconItem errorIcon(":/viewer/error.svg");
static IconItem bookmarkGroupIcon(":/desktop/bookmark_group.svg");
static IconItem embeddedIcon(":/desktop/embedded.svg");
static IconItem infoIcon(":/viewer/info.svg");
std::map<QString,IconItem*> IconProvider::icons_;
std::map<int,IconItem*> IconProvider::iconsById_;
static int idCnt=0;
//===========================================
//
// IconItem
//
//===========================================
IconItem::IconItem(QString path) : path_(path), id_(idCnt++)
{
}
QPixmap IconItem::pixmap(int size)
{
auto it=pixmaps_.find(size);
if(it != pixmaps_.end())
return it->second;
else
{
QPixmap pix;
QImageReader imgR(path_);
if(imgR.canRead())
{
imgR.setScaledSize(QSize(size,size));
QImage img=imgR.read();
pix=QPixmap::fromImage(img);
}
else
{
pix=unknown(size);
}
pixmaps_[size]=pix;
return pix;
}
return QPixmap();
}
QPixmap IconItem::unknown(int size)
{
return unknownIcon.pixmap(size);
}
UnknownIconItem::UnknownIconItem(QString path) : IconItem(path)
{
}
QPixmap UnknownIconItem::unknown(int size)
{
return QPixmap();
}
//===========================================
//
// IconProvider
//
//===========================================
IconProvider::IconProvider()
= default;
QString IconProvider::path(int id)
{
auto it=iconsById_.find(id);
if(it != iconsById_.end())
return it->second->path();
return QString();
}
int IconProvider::add(QString path,QString name)
{
auto it=icons_.find(name);
if(it == icons_.end())
{
auto *p=new IconItem(path);
icons_[name]=p;
iconsById_[p->id()]=p;
return p->id();
}
return it->second->id();
}
IconItem* IconProvider::icon(QString name)
{
auto it=icons_.find(name);
if(it != icons_.end())
return it->second;
return &unknownIcon;
}
IconItem* IconProvider::icon(int id)
{
auto it=iconsById_.find(id);
if(it != iconsById_.end())
return it->second;
return &unknownIcon;
}
QPixmap IconProvider::pixmap(QString name,int size)
{
return icon(name)->pixmap(size);
}
QPixmap IconProvider::pixmap(int id,int size)
{
return icon(id)->pixmap(size);
}
QPixmap IconProvider::lockPixmap(int size)
{
return lockIcon.pixmap(size);
}
QPixmap IconProvider::warningPixmap(int size)
{
return warningIcon.pixmap(size);
}
QPixmap IconProvider::errorPixmap(int size)
{
return errorIcon.pixmap(size);
}
QPixmap IconProvider::infoPixmap(int size)
{
return infoIcon.pixmap(size);
}
static IconProvider iconProvider;
| 20.494048 | 79 | 0.642753 | mpartio |
c1ebfb23512465db06b60845b07042767282b761 | 2,067 | cpp | C++ | CommonLexer/Src/CommonLexer/Source.cpp | MarcasRealAccount/CommonLexer | b42f334043b6fe1d0559602590ec95ccad10903e | [
"MIT"
] | null | null | null | CommonLexer/Src/CommonLexer/Source.cpp | MarcasRealAccount/CommonLexer | b42f334043b6fe1d0559602590ec95ccad10903e | [
"MIT"
] | null | null | null | CommonLexer/Src/CommonLexer/Source.cpp | MarcasRealAccount/CommonLexer | b42f334043b6fe1d0559602590ec95ccad10903e | [
"MIT"
] | null | null | null | #include "CommonLexer/Source.h"
namespace CommonLexer
{
StringSource::StringSource(const std::string& str)
: m_Str(str)
{
setupLineToIndex();
}
StringSource::StringSource(std::string&& str)
: m_Str(std::move(str))
{
setupLineToIndex();
}
std::size_t StringSource::getSize()
{
return m_Str.size();
}
std::size_t StringSource::getNumLines()
{
return m_LineToIndex.size();
}
std::size_t StringSource::getIndexFromLine(std::size_t line)
{
return line > 0 && line <= m_LineToIndex.size() ? m_LineToIndex[line - 1] : ~0ULL;
}
std::size_t StringSource::getLineFromIndex(std::size_t index)
{
for (std::size_t i = m_LineToIndex.size(); i > 0; --i)
if (m_LineToIndex[i - 1] <= index)
return i;
return ~0ULL;
}
std::size_t StringSource::getColumnFromIndex(std::size_t index)
{
std::size_t line = getLineFromIndex(index);
if (line == ~0ULL)
return 1;
std::size_t lineStart = getIndexFromLine(line);
if (lineStart == ~0ULL)
return 1;
return index - lineStart + 1;
}
std::string StringSource::getSpan(std::size_t index, std::size_t length)
{
if (index >= m_Str.size())
return {};
if ((index + length) >= m_Str.size())
length = m_Str.size() - index;
return m_Str.substr(index, length);
}
std::string StringSource::getLine(std::size_t line)
{
std::size_t lineStart = getIndexFromLine(line);
if (lineStart == ~0ULL)
return {};
std::size_t lineEnd = getIndexFromLine(line + 1);
if (lineStart == ~0ULL)
return {};
return m_Str.substr(lineStart, lineEnd - lineStart - 1);
}
std::vector<std::string> StringSource::getLines(std::size_t startLine, std::size_t lines)
{
std::vector<std::string> lns;
lns.reserve(lines);
for (std::size_t line = startLine, end = startLine + lines; line != end; ++line)
lns.push_back(getLine(line));
return lns;
}
void StringSource::setupLineToIndex()
{
m_LineToIndex.emplace_back(0);
for (std::size_t i = 0; i < m_Str.size(); ++i)
if (m_Str[i] == '\n')
m_LineToIndex.emplace_back(i + 1);
}
} // namespace CommonLexer | 23.224719 | 90 | 0.661345 | MarcasRealAccount |
c1ec3c57e46722eccc5fd273c4183b50f4f3aff1 | 1,804 | hpp | C++ | shared/src/single_application.hpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | shared/src/single_application.hpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | shared/src/single_application.hpp | amazingidiot/qastools | 6e3b0532ebc353c79d6df0628ed375e3d3c09d12 | [
"MIT"
] | null | null | null | /// QasTools: Desktop toolset for the Linux sound system ALSA.
/// \copyright See COPYING file.
#ifndef __INC_single_application_hpp__
#define __INC_single_application_hpp__
#include <QApplication>
#include <QList>
#include <QLocalServer>
#include <QPointer>
class Single_Application : public QApplication
{
Q_OBJECT
// Public methods
public:
Single_Application ( int & argc,
char * argv[],
const QString & unique_key_n = QString () );
~Single_Application ();
// Unique key
const QString &
unique_key () const;
bool
set_unique_key ( const QString & unique_key_n );
bool
is_running () const;
// Message
bool
send_message ( const QString & msg_n );
const QString
latest_message () const;
// Session management
void
commitData ( QSessionManager & manager_n );
void
saveState ( QSessionManager & manager_n );
// Signals
signals:
void
sig_message_available ( QString mesg_n );
// Protected slots
protected slots:
void
new_client ();
void
read_clients_data ();
void
clear_dead_clients ();
// Protected methods
protected:
void
publish_message ( QByteArray & data_n );
// Private attributes
private:
bool _is_running;
QString _unique_key;
QString _com_key;
QString _com_file;
QString _latest_message;
QLocalServer * _local_server;
struct Client
{
QPointer< QLocalSocket > socket;
QByteArray data;
};
QList<Client> _clients;
const unsigned int _timeout;
};
inline bool
Single_Application::is_running () const
{
return _is_running;
}
inline const QString &
Single_Application::unique_key () const
{
return _unique_key;
}
inline const QString
Single_Application::latest_message () const
{
return _latest_message;
}
#endif
| 15.824561 | 67 | 0.695122 | amazingidiot |
c1f00d76bd6d589ade8d2cf83656cb920d8689ca | 3,229 | cpp | C++ | src/qt/btcu/mninfodialog.cpp | askiiRobotics/orion | b664d3bbcd0c8bde3798724e33cc56aae6d2b6d8 | [
"MIT"
] | 2 | 2021-02-05T18:37:43.000Z | 2021-04-27T04:29:22.000Z | src/qt/btcu/mninfodialog.cpp | askiiRobotics/orion | b664d3bbcd0c8bde3798724e33cc56aae6d2b6d8 | [
"MIT"
] | 2 | 2021-02-15T13:16:49.000Z | 2021-05-19T12:06:09.000Z | src/qt/btcu/mninfodialog.cpp | askiiRobotics/orion | b664d3bbcd0c8bde3798724e33cc56aae6d2b6d8 | [
"MIT"
] | 4 | 2021-02-22T22:03:39.000Z | 2022-03-31T10:18:34.000Z | // Copyright (c) 2019 The PIVX developers
// Copyright (c) 2020 The BTCU developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "qt/btcu/mninfodialog.h"
#include "qt/btcu/forms/ui_mninfodialog.h"
#include "walletmodel.h"
#include "wallet/wallet.h"
#include "guiutil.h"
#include "qt/btcu/qtutils.h"
#include <QDateTime>
MnInfoDialog::MnInfoDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::MnInfoDialog)
{
ui->setupUi(this);
this->setStyleSheet(parent->styleSheet());
setCssProperty(ui->frame, "container-border");
ui->frame->setContentsMargins(10,10,10,10);
//setCssProperty(ui->layoutScroll, "container-border");
//setCssProperty(ui->scrollArea, "container-border");
setCssProperty(ui->labelTitle, "text-title-dialog");
QList<QWidget*> lWidjets = {ui->labelName, ui->textName, ui->labelAddress, ui->textAddress, ui->labelPubKey, ui->textPubKey, ui->labelIP, ui->textIP,
ui->labelTxId, ui->textTxId, ui->labelOutIndex, ui->textOutIndex, ui->labelStatus, ui->textStatus, ui->textExport};
for(int i = 0; i < lWidjets.size(); ++i)
setCssSubtitleScreen(lWidjets.at(i));
setCssProperty({ui->labelDivider1, ui->labelDivider2, ui->labelDivider3, ui->labelDivider4, ui->labelDivider5, ui->labelDivider6, ui->labelDivider7, ui->labelDivider8}, "container-divider");
setCssProperty({ui->pushCopyKey, ui->pushCopyId, ui->pushExport}, "ic-copy-big");
setCssProperty(ui->btnEsc, "ic-close");
connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(closeDialog()));
connect(ui->pushCopyKey, &QPushButton::clicked, [this](){ copyInform(pubKey, "Masternode public key copied"); });
connect(ui->pushCopyId, &QPushButton::clicked, [this](){ copyInform(txId, "Collateral tx id copied"); });
connect(ui->pushExport, &QPushButton::clicked, [this](){ exportMN = true; accept(); });
}
void MnInfoDialog::setData(QString name, QString address, QString pubKey, QString ip, QString txId, QString outputIndex, QString status){
this->pubKey = pubKey;
this->txId = txId;
QString shortPubKey = pubKey;
QString shortTxId = txId;
if(shortPubKey.length() > 20) {
shortPubKey = shortPubKey.left(13) + "..." + shortPubKey.right(13);
}
if(shortTxId.length() > 20) {
shortTxId = shortTxId.left(12) + "..." + shortTxId.right(12);
}
ui->textName->setText(name);
ui->textAddress->setText(address);
ui->textPubKey->setText(shortPubKey);
ui->textIP->setText(ip);
ui->textTxId->setText(shortTxId);
ui->textOutIndex->setText(outputIndex);
ui->textStatus->setText(status);
}
void MnInfoDialog::copyInform(QString& copyStr, QString message){
GUIUtil::setClipboard(copyStr);
if(!snackBar) snackBar = new SnackBar(nullptr, this);
snackBar->setText(tr(message.toStdString().c_str()));
snackBar->resize(this->width(), snackBar->height());
openDialog(snackBar, this);
}
void MnInfoDialog::closeDialog(){
if(snackBar && snackBar->isVisible()) snackBar->hide();
close();
}
MnInfoDialog::~MnInfoDialog(){
if(snackBar) delete snackBar;
delete ui;
}
| 40.873418 | 194 | 0.6869 | askiiRobotics |
c1f216fd0d04799b4abcb0f5d4789a723dbfe7b6 | 4,452 | cpp | C++ | GUI.cpp | guc-cs/FPS-Trainer | 84c36af2abf9182fd76fead037ba7f6866a2749b | [
"MIT"
] | null | null | null | GUI.cpp | guc-cs/FPS-Trainer | 84c36af2abf9182fd76fead037ba7f6866a2749b | [
"MIT"
] | 1 | 2020-04-11T21:04:28.000Z | 2020-04-12T22:05:31.000Z | GUI.cpp | guc-cs/FPS-Trainer | 84c36af2abf9182fd76fead037ba7f6866a2749b | [
"MIT"
] | null | null | null | #include <GL/glut.h>
#include "GUI.h"
GUI gui;
Point::Point()
{
}
Point::Point(float posX, float posY)
{
x = posX;
y = posY;
}
MenuItem::MenuItem()
{
}
MenuItem::MenuItem(char* str)
{
s = str;
}
MenuItem::MenuItem(char* str, Point p1, Point p2, Point p3, Point p4)
{
s = str;
one = p1;
two = p2;
three = p3;
four = p4;
}
void MenuItem::drawItem()
{
glBegin(GL_LINE_LOOP);
glColor3f(1,0,0);
glVertex2f(one.x, one.y);
glVertex2f(two.x, two.y);
glVertex2f(three.x, three.y);
glVertex2f(four.x, four.y);
glEnd();
}
StartMenu::StartMenu()
{
Point p1 = Point(300,440), p2 = Point(300,500), p3 = Point(500,500), p4 = Point(500,440);
Point p5 = Point(300,240), p6 = Point(300,300), p7 = Point(500,300), p8 = Point(500,240);
startGame = MenuItem("Start Game", p1, p2, p3, p4);
exit = MenuItem("E X I T", p5, p6, p7, p8);
}
void StartMenu::drawMenu()
{
gui.draw2D();
startGame.drawItem();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(startGame.one.x + 8, (startGame.one.y + startGame.two.y)/2 - 10, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(startGame.s, GLUT_STROKE_ROMAN);
glPopMatrix();
exit.drawItem();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(exit.one.x + 30, (exit.one.y + exit.two.y)/2 - 10, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(exit.s, GLUT_STROKE_ROMAN);
glPopMatrix();
}
PauseMenu::PauseMenu()
{
Point p1 = Point(300,440), p2 = Point(300,500), p3 = Point(500,500), p4 = Point(500,440);
Point p5 = Point(300,320), p6 = Point(300,380), p7 = Point(500,380), p8 = Point(500,320);
Point p9 = Point(300,200), p10 = Point(300,260), p11 = Point(500,260), p12 = Point(500,200);
resumeGame = MenuItem("Resume", p1, p2, p3, p4);
back = MenuItem("Main Menu", p5, p6, p7, p8);
exit = MenuItem("E X I T", p9, p10, p11, p12);
}
void PauseMenu::drawMenu()
{
gui.draw2D();
resumeGame.drawItem();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(resumeGame.one.x + 40, (resumeGame.one.y + resumeGame.two.y)/2 - 10, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(resumeGame.s, GLUT_STROKE_ROMAN);
glPopMatrix();
back.drawItem();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(back.one.x + 15, (back.one.y + back.two.y)/2 - 10, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(back.s, GLUT_STROKE_ROMAN);
glPopMatrix();
exit.drawItem();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(exit.one.x + 30, (exit.one.y + exit.two.y)/2 - 10, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(exit.s, GLUT_STROKE_ROMAN);
glPopMatrix();
}
PlayMenu::PlayMenu()
{
name = MenuItem("Training");
bullets = MenuItem("Bullets:");
message = MenuItem("");
cursor = MenuItem(".");
}
void PlayMenu::drawMenu(int nBullets)
{
gui.draw2D();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(30, 550, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(name.s, GLUT_STROKE_ROMAN);
glPopMatrix();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(650, 550, 0);
glScaled(0.25, 0.25, 0.25);
char *buffer = new char[2];
//char *text = itoa(nBullets, buffer, 10);
gui.print(bullets.s, GLUT_STROKE_ROMAN);
//gui.print(text, GLUT_STROKE_ROMAN);
glPopMatrix();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(300, 550, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(message.s, GLUT_STROKE_ROMAN);
glPopMatrix();
glPushMatrix();
glLineWidth(5);
glColor3f(0.13, 0.54, 0.13);
glTranslated(400, 300, 0);
glScaled(0.25, 0.25, 0.25);
gui.print(cursor.s, GLUT_STROKE_ROMAN);
glPopMatrix();
draw3D();
}
void PlayMenu::draw3D()
{
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-2.0*70/54.0, 2.0*70/54.0, -2.0, 2.0, 0.1, 200);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
GUI::GUI()
{
}
void GUI::draw2D()
{
glDisable( GL_TEXTURE_2D );
glDisable(GL_DEPTH_TEST);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 800, 0, 600);
glMatrixMode(GL_MODELVIEW);
}
void GUI::print(char* string, void *font)
{
char* c;
for (c=string; *c != '\0'; c++)
glutStrokeCharacter(font, *c);
}
| 22.598985 | 94 | 0.623091 | guc-cs |
c1f79185179907836710189d5ff29b8af4818d3a | 9,227 | hpp | C++ | kty/containers/stringpool.hpp | mattheuslee/Kitty | 50bd18dc0b6c895f4b6b816c7340c03dd00a5f40 | [
"MIT"
] | null | null | null | kty/containers/stringpool.hpp | mattheuslee/Kitty | 50bd18dc0b6c895f4b6b816c7340c03dd00a5f40 | [
"MIT"
] | 6 | 2017-08-28T15:39:28.000Z | 2018-04-24T16:02:09.000Z | kty/containers/stringpool.hpp | mattheuslee/KittyInterpreter | 50bd18dc0b6c895f4b6b816c7340c03dd00a5f40 | [
"MIT"
] | null | null | null | #pragma once
#include <kty/sizes.hpp>
#include <kty/types.hpp>
namespace kty {
/*!
@brief Class that maintains all the strings in the program.
The memory pool is created on the stack to avoid heap fragmentation.
Holds enough memory to allocate N strings of at most length S.
*/
template <int N = Sizes::stringpool_size, int S = Sizes::string_length>
class StringPool {
public:
/*!
@brief Constructor for the string pool
*/
StringPool() {
Log.verbose(F("%s\n"), PRINT_FUNC);
memset((void*)pool_, '\0', N * (S + 1));
memset((void*)refCount_, 0, N * sizeof(int));
numTaken_ = 0;
maxNumTaken_ = 0;
}
/*!
@brief Prints stats about the string pool.
*/
void stat() const {
Log.notice(F("%s: num taken = %d, max num taken = %d\n"), PRINT_FUNC, numTaken_, maxNumTaken_);
}
/*!
@brief Resets the stats about the string pool.
*/
void reset_stat() {
Log.verbose(F("%s\n"), PRINT_FUNC);
maxNumTaken_ = numTaken_;
}
/*!
@brief Prints the addresses used by the string database
*/
void dump_addresses() const {
Log.notice(F("%s: Pool addresses = %d to %d\n"), PRINT_FUNC, (intptr_t)pool_, (intptr_t)(pool_ + N * (S + 1) - 1));
}
/*!
@brief Returns the maximum possible length for a string.
@return The maximum possible string length.
*/
int max_str_len() const {
Log.verbose(F("%s\n"), PRINT_FUNC);
return S;
}
/*!
@brief Checks if an index is owned by this pool.
@param idx
The index to check.
@return True if the index is owned by this pool, false otherwise.
*/
bool owns(int const & idx) {
Log.verbose(F("%s\n"), PRINT_FUNC);
return idx >= 0 && idx < N;
}
/*!
@brief Check the number of available blocks left in the pool.
@return The number of available blocks left in the pool.
*/
int available() const {
Log.verbose(F("%s\n"), PRINT_FUNC);
return N - numTaken_;
}
/*!
@brief Returns the reference count for an index.
@param idx
The index to get the reference count for.
@return The reference count for the index.
If the index is invalid, -1 is returned.
*/
int ref_count(int const & idx) {
Log.verbose(F("%s\n"), PRINT_FUNC);
if (idx >=0 && idx < N) {
return refCount_[idx];
}
Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx);
return -1;
}
/*!
@brief Increases the reference count for an index.
@param idx
The index to increase the reference count for.
@return The new reference count of the index.
If the address is invalid, -1 is returned.
*/
int inc_ref_count(int const & idx) {
Log.verbose(F("%s\n"), PRINT_FUNC);
if (idx >=0 && idx < N) {
++refCount_[idx];
return refCount_[idx];
}
Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx);
return -1;
}
/*!
@brief Decreases the reference count for an index.
If this operation decreases the reference count to 0,
it is not deallocated.
To ensure that a decrease to 0 deallocates the index,
call deallocate_idx().
@param idx
The index to decrease the reference count for.
@return The new reference count of the index.
If the address is invalid, -1 is returned.
*/
int dec_ref_count(int const & idx) {
Log.verbose(F("%s\n"), PRINT_FUNC);
if (idx >=0 && idx < N) {
--refCount_[idx];
return refCount_[idx];
}
Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx);
return -1;
}
/*!
@brief Gets the next free index for a string.
@return An index into the pool if there is space,
-1 otherwise.
*/
int allocate_idx() {
Log.verbose(F("%s\n"), PRINT_FUNC);
for (int i = 0; i < N; ++i) {
if (refCount_[i] == 0) {
++refCount_[i];
++numTaken_;
Log.trace(F("%s: Allocating index %d\n"), PRINT_FUNC, i);
memset((void*)(pool_ + (i * (S + 1))), '\0', S + 1);
if (numTaken_ > maxNumTaken_) {
maxNumTaken_ = numTaken_;
Log.trace(F("%s: new maxNumTaken %d\n"), PRINT_FUNC, maxNumTaken_);
}
return i;
}
}
Log.warning(F("%s: No more string indices to allocate\n"), PRINT_FUNC);
return -1;
}
/*!
@brief Returns a string index to the pool
@param idx
The index to return to the pool
@return True if the deallocation was successful, false otherwise.
*/
bool deallocate_idx(int const & idx) {
Log.verbose(F("%s\n"), PRINT_FUNC);
if (idx < 0 || idx >= N) {
Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx);
return false;
}
if (refCount_[idx] > 0) {
--refCount_[idx];
}
else {
Log.warning(F("%s: Index %d has already been previously deallocated\n"), PRINT_FUNC, idx);
return false;
}
if (refCount_[idx] == 0) {
--numTaken_;
Log.trace(F("%s: Index %d deallocated successfully\n"), PRINT_FUNC, idx);
return true;
}
else {
Log.trace(F("%s: Index %d is not the last reference\n"), PRINT_FUNC, idx);
return true;
}
}
/*!
@brief Returns the string at a given index.
@param idx
The database index for the string.
@return str
The stored string.
*/
char * c_str(int const & idx) const {
Log.verbose(F("%s\n"), PRINT_FUNC);
if (idx >= 0 && idx < N) {
return const_cast<char *>(pool_) + (idx * (S + 1));
}
Log.warning(F("%s: Index %d is invalid, index range is [0, %d]\n"), PRINT_FUNC, idx, N - 1);
return nullptr;
}
/*!
@brief Sets a string in the database, with an optional
index to start from.
@param idx
The database index for the string.
@param str
The incoming string.
@param i
The optional starting index within the string to
start copying from.
Default is index 0.
*/
void strcpy(int const & idx, char const * str, int const & i = 0) {
Log.verbose(F("%s\n"), PRINT_FUNC);
int copyStrLen = ::strlen(str);
int lenToCopy = (S < copyStrLen ? S : copyStrLen) - i;
::strncpy(c_str(idx) + i, str, lenToCopy);
*(c_str(idx) + i + lenToCopy) = '\0';
}
/*!
@brief Concatenates another string to the end of a string
in the pool.
@param idx
The database index for the string.
@param str
The incoming string which will be concatenated onto the end.
*/
void strcat(int const & idx, char const * str) {
Log.verbose(F("%s\n"), PRINT_FUNC);
int currLen = ::strlen(c_str(idx));
int catStrLen = ::strlen(str);
// Length to cat is minimum of remaining space and length of string to cat
int lenToCat = ((S - currLen) < catStrLen ? (S - currLen) : catStrLen);
Log.verbose(F("%s: length to cat %d\n"), PRINT_FUNC, lenToCat);
strncpy(c_str(idx) + currLen, str, lenToCat);
*(c_str(idx) + currLen + lenToCat) = '\0';
}
private:
char pool_[N * (S + 1)];
int refCount_[N];
int numTaken_;
int maxNumTaken_;
};
/*!
@brief Returns a pointer to a stringpool.
@param ptr
Used to set the address to return for the very first call.
Subsequent calls will return this address.
@return A pointer to a stringpool.
*/
StringPool<Sizes::stringpool_size, Sizes::string_length> * get_stringpool(StringPool<Sizes::stringpool_size, Sizes::string_length> * ptr) {
static StringPool<Sizes::stringpool_size, Sizes::string_length> * stringPool;
if (ptr != nullptr) {
stringPool = ptr;
}
return stringPool;
}
/*!
@brief Class to perform setup of the get_stringpool function at the global scope.
*/
template <typename StringPool = StringPool<Sizes::stringpool_size, Sizes::string_length>>
class GetStringPoolInit {
public:
/*!
@brief Executes the setup call to get_stringpool with the given string pool.
@param stringPool
The string pool to setup get_stringpool with.
*/
explicit GetStringPoolInit(StringPool & stringPool) {
get_stringpool(&stringPool);
}
private:
};
} // namespace kty
| 29.860841 | 139 | 0.539395 | mattheuslee |
c1f8739ea709fbc942e1eefa3df3db0e38622bf8 | 11,053 | cxx | C++ | retro/cores/atari2600/stella/src/debugger/RiotDebug.cxx | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 2,706 | 2018-04-05T18:28:50.000Z | 2022-03-29T16:56:59.000Z | retro/cores/atari2600/stella/src/debugger/RiotDebug.cxx | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 242 | 2018-04-05T22:30:42.000Z | 2022-03-19T01:55:11.000Z | retro/cores/atari2600/stella/src/debugger/RiotDebug.cxx | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 464 | 2018-04-05T19:10:34.000Z | 2022-03-28T13:33:32.000Z | //============================================================================
//
// SSSS tt lll lll
// SS SS tt ll ll
// SS tttttt eeee ll ll aaaa
// SSSS tt ee ee ll ll aa
// SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator"
// SS SS tt ee ll ll aa aa
// SSSS ttt eeeee llll llll aaaaa
//
// Copyright (c) 1995-2014 by Bradford W. Mott, Stephen Anthony
// and the Stella Team
//
// See the file "License.txt" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: RiotDebug.cxx 2838 2014-01-17 23:34:03Z stephena $
//============================================================================
#include <sstream>
#include "System.hxx"
#include "TIA.hxx"
#include "Debugger.hxx"
#include "Switches.hxx"
#include "RiotDebug.hxx"
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
RiotDebug::RiotDebug(Debugger& dbg, Console& console)
: DebuggerSystem(dbg, console)
{
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const DebuggerState& RiotDebug::getState()
{
// Port A & B registers
myState.SWCHA_R = swcha();
myState.SWCHA_W = mySystem.m6532().myOutA;
myState.SWACNT = swacnt();
myState.SWCHB_R = swchb();
myState.SWCHB_W = mySystem.m6532().myOutB;
myState.SWBCNT = swbcnt();
Debugger::set_bits(myState.SWCHA_R, myState.swchaReadBits);
Debugger::set_bits(myState.SWCHA_W, myState.swchaWriteBits);
Debugger::set_bits(myState.SWACNT, myState.swacntBits);
Debugger::set_bits(myState.SWCHB_R, myState.swchbReadBits);
Debugger::set_bits(myState.SWCHB_W, myState.swchbWriteBits);
Debugger::set_bits(myState.SWBCNT, myState.swbcntBits);
// TIA INPTx registers
myState.INPT0 = inpt(0);
myState.INPT1 = inpt(1);
myState.INPT2 = inpt(2);
myState.INPT3 = inpt(3);
myState.INPT4 = inpt(4);
myState.INPT5 = inpt(5);
// Timer registers
myState.TIM1T = tim1T();
myState.TIM8T = tim8T();
myState.TIM64T = tim64T();
myState.T1024T = tim1024T();
myState.INTIM = intim();
myState.TIMINT = timint();
myState.TIMCLKS = timClocks();
myState.INTIMCLKS = intimClocks();
return myState;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void RiotDebug::saveOldState()
{
// Port A & B registers
myOldState.SWCHA_R = swcha();
myOldState.SWCHA_W = mySystem.m6532().myOutA;
myOldState.SWACNT = swacnt();
myOldState.SWCHB_R = swchb();
myOldState.SWCHB_W = mySystem.m6532().myOutB;
myOldState.SWBCNT = swbcnt();
Debugger::set_bits(myOldState.SWCHA_R, myOldState.swchaReadBits);
Debugger::set_bits(myOldState.SWCHA_W, myOldState.swchaWriteBits);
Debugger::set_bits(myOldState.SWACNT, myOldState.swacntBits);
Debugger::set_bits(myOldState.SWCHB_R, myOldState.swchbReadBits);
Debugger::set_bits(myOldState.SWCHB_W, myOldState.swchbWriteBits);
Debugger::set_bits(myOldState.SWBCNT, myOldState.swbcntBits);
// TIA INPTx registers
myOldState.INPT0 = inpt(0);
myOldState.INPT1 = inpt(1);
myOldState.INPT2 = inpt(2);
myOldState.INPT3 = inpt(3);
myOldState.INPT4 = inpt(4);
myOldState.INPT5 = inpt(5);
// Timer registers
myOldState.TIM1T = tim1T();
myOldState.TIM8T = tim8T();
myOldState.TIM64T = tim64T();
myOldState.T1024T = tim1024T();
myOldState.INTIM = intim();
myOldState.TIMINT = timint();
myOldState.TIMCLKS = timClocks();
myOldState.INTIMCLKS = intimClocks();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::swcha(int newVal)
{
if(newVal > -1)
mySystem.poke(0x280, newVal);
return mySystem.peek(0x280);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::swchb(int newVal)
{
if(newVal > -1)
mySystem.poke(0x282, newVal);
return mySystem.peek(0x282);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::swacnt(int newVal)
{
if(newVal > -1)
mySystem.poke(0x281, newVal);
return mySystem.m6532().myDDRA;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::swbcnt(int newVal)
{
if(newVal > -1)
mySystem.poke(0x283, newVal);
return mySystem.m6532().myDDRB;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::inpt(int x)
{
static TIARegister _inpt[6] = { INPT0, INPT1, INPT2, INPT3, INPT4, INPT5 };
return mySystem.peek(_inpt[x]);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool RiotDebug::vblank(int bit)
{
if(bit == 6) // latches
return mySystem.tia().myVBLANK & 0x40;
else if(bit == 7) // dump to ground
return mySystem.tia().myDumpEnabled;
else
return true;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::tim1T(int newVal)
{
if(newVal > -1)
mySystem.poke(0x294, newVal);
return mySystem.m6532().myOutTimer[0];
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::tim8T(int newVal)
{
if(newVal > -1)
mySystem.poke(0x295, newVal);
return mySystem.m6532().myOutTimer[1];
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::tim64T(int newVal)
{
if(newVal > -1)
mySystem.poke(0x296, newVal);
return mySystem.m6532().myOutTimer[2];
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
uInt8 RiotDebug::tim1024T(int newVal)
{
if(newVal > -1)
mySystem.poke(0x297, newVal);
return mySystem.m6532().myOutTimer[3];
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Controller& RiotDebug::controller(Controller::Jack jack) const
{
return myConsole.controller(jack);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool RiotDebug::diffP0(int newVal)
{
uInt8& switches = myConsole.switches().mySwitches;
if(newVal > -1)
switches = Debugger::set_bit(switches, 6, newVal > 0);
return switches & 0x40;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool RiotDebug::diffP1(int newVal)
{
uInt8& switches = myConsole.switches().mySwitches;
if(newVal > -1)
switches = Debugger::set_bit(switches, 7, newVal > 0);
return switches & 0x80;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool RiotDebug::tvType(int newVal)
{
uInt8& switches = myConsole.switches().mySwitches;
if(newVal > -1)
switches = Debugger::set_bit(switches, 3, newVal > 0);
return switches & 0x08;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool RiotDebug::select(int newVal)
{
uInt8& switches = myConsole.switches().mySwitches;
if(newVal > -1)
switches = Debugger::set_bit(switches, 1, newVal > 0);
return switches & 0x02;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool RiotDebug::reset(int newVal)
{
uInt8& switches = myConsole.switches().mySwitches;
if(newVal > -1)
switches = Debugger::set_bit(switches, 0, newVal > 0);
return switches & 0x01;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string RiotDebug::dirP0String()
{
uInt8 reg = swcha();
ostringstream buf;
buf << (reg & 0x80 ? "" : "right ")
<< (reg & 0x40 ? "" : "left ")
<< (reg & 0x20 ? "" : "left ")
<< (reg & 0x10 ? "" : "left ")
<< ((reg & 0xf0) == 0xf0 ? "(no directions) " : "");
return buf.str();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string RiotDebug::dirP1String()
{
uInt8 reg = swcha();
ostringstream buf;
buf << (reg & 0x08 ? "" : "right ")
<< (reg & 0x04 ? "" : "left ")
<< (reg & 0x02 ? "" : "left ")
<< (reg & 0x01 ? "" : "left ")
<< ((reg & 0x0f) == 0x0f ? "(no directions) " : "");
return buf.str();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string RiotDebug::diffP0String()
{
return (swchb() & 0x40) ? "hard/A" : "easy/B";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string RiotDebug::diffP1String()
{
return (swchb() & 0x80) ? "hard/A" : "easy/B";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string RiotDebug::tvTypeString()
{
return (swchb() & 0x8) ? "Color" : "B&W";
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string RiotDebug::switchesString()
{
ostringstream buf;
buf << (swchb() & 0x2 ? "-" : "+") << "select "
<< (swchb() & 0x1 ? "-" : "+") << "reset";
return buf.str();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
string RiotDebug::toString()
{
const RiotState& state = (RiotState&) getState();
const RiotState& oldstate = (RiotState&) getOldState();
ostringstream buf;
buf << "280/SWCHA(R)=" << myDebugger.invIfChanged(state.SWCHA_R, oldstate.SWCHA_R)
<< " 280/SWCHA(W)=" << myDebugger.invIfChanged(state.SWCHA_W, oldstate.SWCHA_W)
<< " 281/SWACNT=" << myDebugger.invIfChanged(state.SWACNT, oldstate.SWACNT)
<< endl
<< "282/SWCHB(R)=" << myDebugger.invIfChanged(state.SWCHB_R, oldstate.SWCHB_R)
<< " 282/SWCHB(W)=" << myDebugger.invIfChanged(state.SWCHB_W, oldstate.SWCHB_W)
<< " 283/SWBCNT=" << myDebugger.invIfChanged(state.SWBCNT, oldstate.SWBCNT)
<< endl
// These are squirrely: some symbol files will define these as
// 0x284-0x287. Doesn't actually matter, these registers repeat
// every 16 bytes.
<< "294/TIM1T=" << myDebugger.invIfChanged(state.TIM1T, oldstate.TIM1T)
<< " 295/TIM8T=" << myDebugger.invIfChanged(state.TIM8T, oldstate.TIM8T)
<< " 296/TIM64T=" << myDebugger.invIfChanged(state.TIM64T, oldstate.TIM64T)
<< " 297/T1024T=" << myDebugger.invIfChanged(state.T1024T, oldstate.T1024T)
<< endl
<< "0x284/INTIM=" << myDebugger.invIfChanged(state.INTIM, oldstate.INTIM)
<< " 285/TIMINT=" << myDebugger.invIfChanged(state.TIMINT, oldstate.TIMINT)
<< " Timer_Clocks=" << myDebugger.invIfChanged(state.TIMCLKS, oldstate.TIMCLKS)
<< " INTIM_Clocks=" << myDebugger.invIfChanged(state.INTIMCLKS, oldstate.INTIMCLKS)
<< endl
<< "Left/P0diff: " << diffP0String() << " Right/P1diff: " << diffP0String()
<< endl
<< "TVType: " << tvTypeString() << " Switches: " << switchesString()
<< endl
// Yes, the fire buttons are in the TIA, but we might as well
// show them here for convenience.
<< "Left/P0 stick: " << dirP0String()
<< ((mySystem.peek(0x03c) & 0x80) ? "" : "(button) ")
<< endl
<< "Right/P1 stick: " << dirP1String()
<< ((mySystem.peek(0x03d) & 0x80) ? "" : "(button) ");
return buf.str();
}
| 31.135211 | 89 | 0.514702 | MatPoliquin |
c1f899816aa872e84a522afd43e47f3ba7778ce6 | 18,981 | cpp | C++ | tracker_tests/src/test_rendering.cpp | clickcao/fato | d2de665e83f82ea1094f488102aba37a8cdd53bb | [
"BSD-3-Clause"
] | 1 | 2018-07-31T04:11:32.000Z | 2018-07-31T04:11:32.000Z | tracker_tests/src/test_rendering.cpp | clickcao/fato | d2de665e83f82ea1094f488102aba37a8cdd53bb | [
"BSD-3-Clause"
] | null | null | null | tracker_tests/src/test_rendering.cpp | clickcao/fato | d2de665e83f82ea1094f488102aba37a8cdd53bb | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************/
/* Copyright (c) 2016, Alessandro Pieropan */
/* 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. */
/*****************************************************************************/
#include "../../fato_rendering/include/multiple_rigid_models_ogre.h"
#include "../../fato_rendering/include/windowless_gl_context.h"
#include "../../fato_rendering/include/device_2d.h"
#include "../../fato_rendering/include/device_1d.h"
#include "../../tracker/include/flow_graph.hpp"
#include "../../tracker/include/nvx_utilities.hpp"
#include "../../cuda/include/utility_kernels.h"
#include "../../tracker/include/tracker_model_vx.h"
#include "../../utilities/include/draw_functions.h"
#include "../../fato_rendering/include/renderer.h"
#include <NVX/nvxcu.h>
#include <NVX/nvx_opencv_interop.hpp>
#include <NVX/nvx_timer.hpp>
#include <string>
#include <memory>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/tracking.hpp>
#include <chrono>
#include <ros/ros.h>
using namespace std;
using namespace cv;
using namespace std::chrono;
struct ParamsBench {
float translation_x;
float translation_y;
float translation_z;
float rotation_x;
float rotation_y;
float min_scale;
float max_scale;
int framerate;
int camera_id;
float running_time;
string object_model_file;
string object_descriptors_file;
string result_file;
};
struct RenderData {
vector<Mat> images;
vector<Eigen::Transform<double, 3, Eigen::Affine>> poses;
void addFrame(Mat &img, Eigen::Transform<double, 3, Eigen::Affine> &pose) {
images.push_back(img);
poses.push_back(pose);
}
};
// default parameters
int width = 640;
int height = 480;
double fx = 500.0;
double fy = 500.0;
double cx = width / 2.0;
double cy = height / 2.0;
double near_plane = 0.01; // for init only
double far_plane = 1000.0; // for init only
float deg2rad = M_PI / 180.0;
float rad2deg = 180.0 / M_PI;
Eigen::Matrix<double, 3, 8> bounding_box;
enum IMG_BOUND { UP = 1, DOWN, LEFT, RIGHT };
Eigen::Matrix3d getRotationView(float rot_x, float rot_y) {
Eigen::Matrix3d rot_view;
rot_view = Eigen::AngleAxisd(rot_y, Eigen::Vector3d::UnitY()) *
Eigen::AngleAxisd(rot_x, Eigen::Vector3d::UnitX());
// rotate around x to 'render' just as Ogre
Eigen::Matrix3d Rx_180 = Eigen::Matrix<double, 3, 3>::Identity();
Rx_180(1, 1) = -1.0;
Rx_180(2, 2) = -1.0;
rot_view *= Rx_180;
return rot_view;
}
double getZshif(Eigen::Matrix3d &rot_view, float scale_apperance,
Eigen::Translation<double, 3> &tra_center) {
// apply tra_center -> rot_view to bounding box
Eigen::Transform<double, 3, Eigen::Affine> t = rot_view * tra_center;
Eigen::Matrix<double, 3, 8> bb;
bb = t * bounding_box;
double size_x = bb.row(0).array().abs().maxCoeff();
double size_y = bb.row(1).array().abs().maxCoeff();
size_x = size_x * (2 - scale_apperance);
size_y = size_y * (2 - scale_apperance);
double x_shift = (2.0 * fx / (double)width) * size_x;
double y_shift = (2.0 * fy / (double)height) * size_y;
if (x_shift > y_shift)
return x_shift;
else
return y_shift;
}
bool getTransformedObjectBox(Eigen::Transform<double, 3, Eigen::Affine> &pose,
pose::MultipleRigidModelsOgre &rendering_engine,
vector<vector<double>> &boxes) {
double tra_render[3];
double rot_render[9];
Eigen::Map<Eigen::Vector3d> tra_render_eig(tra_render);
Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> rot_render_eig(
rot_render);
tra_render_eig = pose.translation();
rot_render_eig = pose.rotation();
std::vector<pose::TranslationRotation3D> TR(1);
TR.at(0).setT(tra_render);
TR.at(0).setR_mat(rot_render);
boxes = rendering_engine.getBoundingBoxesInCameraImage(TR);
}
void getPose(float rot_x, float rot_y,
Eigen::Translation<double, 3> &tra_center,
Eigen::Transform<double, 3, Eigen::Affine> &t_render) {
Eigen::Matrix3d rot_view = getRotationView(rot_x, rot_y);
// apply tra_center -> rot_view to bounding box
Eigen::Transform<double, 3, Eigen::Affine> t = rot_view * tra_center;
Eigen::Matrix<double, 3, 8> bb;
bb = t * bounding_box;
// compute minimal z-shift required to ensure visibility
// assuming cx,cy in image center
Eigen::Matrix<double, 1, 8> shift_x =
(2.0 * fx / (double)width) * bb.row(0).array().abs();
shift_x -= bb.row(2);
Eigen::Matrix<double, 1, 8> shift_y =
(2.0 * fy / (double)height) * bb.row(1).array().abs();
shift_y -= bb.row(2);
Eigen::Matrix<double, 1, 16> shift;
shift << shift_x, shift_y;
double z_shift = shift.maxCoeff();
Eigen::Translation<double, 3> tra_z_shift(0, 0, z_shift);
// compute bounding box limits after z-shift
near_plane = (bb.row(2).array() + z_shift).minCoeff();
far_plane = (bb.row(2).array() + z_shift).maxCoeff();
// compose render transform (tra_center -> rot_view -> tra_z_shift)
t_render = tra_z_shift * rot_view * tra_center;
}
void renderObject(Eigen::Transform<double, 3, Eigen::Affine> &pose,
pose::MultipleRigidModelsOgre &model_ogre) {
double tra_render[3];
double rot_render[9];
Eigen::Map<Eigen::Vector3d> tra_render_eig(tra_render);
Eigen::Map<Eigen::Matrix<double, 3, 3, Eigen::RowMajor>> rot_render_eig(
rot_render);
tra_render_eig = pose.translation();
rot_render_eig = pose.rotation();
std::vector<pose::TranslationRotation3D> TR(1);
TR.at(0).setT(tra_render);
TR.at(0).setR_mat(rot_render);
model_ogre.updateProjectionMatrix(fx, fy, cx, cy, near_plane, far_plane);
model_ogre.render(TR);
}
void downloadRenderedImg(pose::MultipleRigidModelsOgre &model_ogre,
std::vector<uchar4> &h_texture) {
util::Device1D<uchar4> d_texture(height * width);
vision::convertFloatArrayToGrayRGBA(d_texture.data(), model_ogre.getTexture(),
width, height, 1.0, 2.0);
h_texture.resize(height * width);
d_texture.copyTo(h_texture);
}
void generateRenderedMovement(const ParamsBench ¶ms,
pose::MultipleRigidModelsOgre &rendering_engine,
RenderData &data) {
// object vertices
const render::RigidObject &obj_model = rendering_engine.getRigidObject(0);
Eigen::Map<const Eigen::MatrixXf> vertices_f(obj_model.getPositions().data(),
3, obj_model.getNPositions());
Eigen::MatrixXd vertices;
vertices = vertices_f.cast<double>();
// bounding box
Eigen::Map<const Eigen::MatrixXf> bounding_box_f(
obj_model.getBoundingBox().data(), 3, 8);
bounding_box = bounding_box_f.cast<double>();
// centralizing translation
auto mn = vertices.rowwise().minCoeff();
auto mx = vertices.rowwise().maxCoeff();
Eigen::Translation<double, 3> tra_center(-(mn + mx) / 2.0f);
Eigen::Transform<double, 3, Eigen::Affine> t_render;
Eigen::Matrix3d rot_view = getRotationView(0, 0);
double z_shift = getZshif(rot_view, 0.6, tra_center);
Eigen::Translation<double, 3> tra_z_shift(0, 0, z_shift);
// compose render transform (tra_center -> rot_view -> tra_z_shift)
t_render = tra_z_shift * rot_view * tra_center;
cout << "OGRE translation " << endl;
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 4; ++j)
{
cout << t_render(i,j) << " ";
}
cout << "\n";
}
Ogre::Quaternion q(Ogre::Degree(180), Ogre::Vector3::UNIT_X);
Ogre::Matrix3 rot;
q.ToRotationMatrix(rot);
cout << "ogre rotation matrix " << endl;
for(auto i = 0; i < 3; ++i)
{
for(auto j = 0; j < 3; ++j)
cout << (float)*rot[i,j] << " ";
cout << "\n";
}
cout << "\n";
renderObject(t_render, rendering_engine);
std::vector<uchar4> h_texture(height * width);
downloadRenderedImg(rendering_engine, h_texture);
cv::Mat img_rgba(height, width, CV_8UC4, h_texture.data());
cv::Mat img_gray;
cv::cvtColor(img_rgba, img_gray, CV_RGBA2BGR);
vector<vector<double>> boxes;
getTransformedObjectBox(t_render, rendering_engine, boxes);
//drawBox(boxes[0], img_gray);
float max_vel_h = params.translation_x;
float max_vel_v = params.translation_y;
float max_vel_d = params.translation_z;
float rot_x_vel = params.rotation_x; // degrees
float rot_y_vel = params.rotation_y;
float x_vel = max_vel_h; // velocity per second
float y_vel = max_vel_v;
float z_vel = max_vel_d;
float milliseconds = 0.010;
float x_pos = 0;
float y_pos = 0;
float z_pos = z_shift;
float x_rot = 0;
double min_scale = getZshif(rot_view, params.min_scale, tra_center);
double max_scale = getZshif(rot_view, params.max_scale, tra_center);
high_resolution_clock::time_point last_time = high_resolution_clock::now();
VideoCapture camera(params.camera_id);
if (!camera.isOpened()) {
cout << "cannot open camera!" << endl;
// return;
}
namedWindow("debug", 1);
Mat cam_img;
int num_frames = params.framerate * params.running_time;
int frame_count = 0;
while (1) {
auto now = high_resolution_clock::now();
float dt = 0.03;
// duration_cast<microseconds>(now - last_time).count() / 1000000.0f;
if (dt > milliseconds) {
x_pos += x_vel * float(dt);
y_pos += y_vel * float(dt);
z_pos += z_vel * float(dt);
x_rot += rot_x_vel * float(dt);
last_time = now;
}
float angle = x_rot * deg2rad;
if (x_rot >= 360) x_rot = 0;
rot_view = getRotationView(angle, 0);
Eigen::Translation<double, 3> tra_z_shift(0.1, 0.1, 0.7);
t_render = tra_z_shift * rot_view * tra_center;
renderObject(t_render, rendering_engine);
getTransformedObjectBox(t_render, rendering_engine, boxes);
// if (isOut(boxes[0]) == LEFT)
// x_vel = max_vel_h;
// else if (isOut(boxes[0]) == RIGHT)
// x_vel = -max_vel_h;
// if (isOut(boxes[0]) == UP)
// y_vel = max_vel_v;
// else if (isOut(boxes[0]) == DOWN)
// y_vel = -max_vel_v;
if (z_pos > min_scale) {
z_vel = -max_vel_d;
} else if (z_pos < max_scale) {
z_vel = max_vel_d;
}
downloadRenderedImg(rendering_engine, h_texture);
cv::Mat img_rgba(height, width, CV_8UC4, h_texture.data());
cv::Mat img_gray, out;
cv::cvtColor(img_rgba, img_gray, CV_RGBA2BGR);
if (camera.isOpened()) {
camera >> cam_img;
//blendImages(cam_img, img_gray, out);
} else
img_gray.copyTo(out);
data.addFrame(out, t_render);
imshow("debug", out);
auto c = waitKey(30);
if (c == 'q') break;
frame_count++;
}
}
void useNewRenderer(const ParamsBench ¶ms) {
rendering::Renderer renderer(width, height, fx, fy, cx, cy, near_plane,
far_plane);
renderer.initRenderContext(640, 480);
renderer.addModel(params.object_model_file,
"/home/alessandro/projects/fato_tracker/fato_rendering/"
"ogre_media/shaders/model.vs",
"/home/alessandro/projects/fato_tracker/fato_rendering/"
"ogre_media/shaders/model.frag");
rendering::RigidObject& obj = renderer.getObject(0);
cout << "object meshes " << obj.model.getMeshCount() << endl;
vector<float> bbox = obj.getBoundingBox();
Eigen::Map<const Eigen::MatrixXf> bounding_box_f(
bbox.data(), 3, 8);
bounding_box = bounding_box_f.cast<double>();
for(auto val : bbox)
cout << val << " ";
cout << "\n";
glm::vec3 translation_center = (-(obj.mins_ + obj.maxs_))/2.0f;
Eigen::Translation<double, 3> tra_center(translation_center.x,
translation_center.y,
translation_center.z);
Eigen::Transform<double, 3, Eigen::Affine> t_render;
Eigen::Matrix3d rot_view = getRotationView(0, 0);
double z_shift = getZshif(rot_view, 1, tra_center);
Eigen::Translation<double, 3> tra_z_shift(0, 0, z_shift);
// // compose render transform (tra_center -> rot_view -> tra_z_shift)
t_render = tra_z_shift * rot_view * tra_center;
cout << "OpenGL translation " << endl;
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 4; ++j)
{
cout << t_render(i,j) << " ";
}
cout << "\n";
}
obj.updatePose(t_render);
high_resolution_clock::time_point last_time = high_resolution_clock::now();
VideoCapture camera(params.camera_id);
if (!camera.isOpened()) {
cout << "cannot open camera!" << endl;
// return;
}
namedWindow("debug", 1);
int num_frames = params.framerate * params.running_time;
int frame_count = 0;
while (frame_count < num_frames) {
auto now = high_resolution_clock::now();
renderer.render();
Mat out(480, 640, CV_8UC3);
imshow("debug", out);
auto c = waitKey(30);
// if (c == 'q') break;
frame_count++;
}
}
void testObjectMovement(const ParamsBench ¶ms) {
render::WindowLessGLContext dummy(10, 10);
fato::TrackerVX::Params tracker_params;
tracker_params.descriptors_file = params.object_descriptors_file;
tracker_params.model_file = params.object_model_file;
tracker_params.image_width = width;
tracker_params.image_height = height;
tracker_params.fx = fx;
tracker_params.fy = fy;
tracker_params.cx = cx;
tracker_params.cy = cy;
tracker_params.parallel = false;
std::unique_ptr<fato::FeatureMatcher> matcher =
std::unique_ptr<fato::BriskMatcher>(new fato::BriskMatcher);
//useNewRenderer(params);
fato::TrackerVX vx_tracker(tracker_params, std::move(matcher));
// pose::MultipleRigidModelsOgre &rendering_engine =
// *vx_tracker.ogre_renderer_;
// RenderData data;
// generateRenderedMovement(params, rendering_engine, data);
// const render::RigidObject &obj_model = rendering_engine.getRigidObject(0);
//vector<float> bbox = obj_model.getBoundingBox();
// cout << "ogre bbox" << endl;
// for(auto val : bbox)
// cout << val << " ";
// trackGeneratedData(data, vx_tracker);
}
void readParameters(ParamsBench ¶ms) {
if (!ros::param::get("fato/model_file", params.object_model_file)) {
throw std::runtime_error("cannot read model_file file param");
}
if (!ros::param::get("fato/object_descriptors_file",
params.object_descriptors_file)) {
throw std::runtime_error("cannot read obj file param");
}
if (!ros::param::get("fato/translation_x", params.translation_x)) {
throw std::runtime_error("cannot read translation_x param");
}
if (!ros::param::get("fato/translation_y", params.translation_y)) {
throw std::runtime_error("cannot read translation_y param");
}
if (!ros::param::get("fato/translation_z", params.translation_z)) {
throw std::runtime_error("cannot read translation_z param");
}
if (!ros::param::get("fato/rotation_x", params.rotation_x)) {
throw std::runtime_error("cannot read rotation_x param");
}
if (!ros::param::get("fato/rotation_y", params.rotation_y)) {
throw std::runtime_error("cannot read rotation_y param");
}
if (!ros::param::get("fato/min_scale", params.min_scale)) {
throw std::runtime_error("cannot read min_scale param");
}
if (!ros::param::get("fato/max_scale", params.max_scale)) {
throw std::runtime_error("cannot read max_scale param");
}
if (!ros::param::get("fato/camera_id", params.camera_id)) {
throw std::runtime_error("cannot read camera_id param");
}
if (!ros::param::get("fato/framerate", params.framerate)) {
throw std::runtime_error("cannot read framerate param");
}
if (!ros::param::get("fato/result_file", params.result_file)) {
throw std::runtime_error("cannot read result_file param");
}
}
void loadParameters(ParamsBench ¶ms) {
params.camera_id = 1;
params.object_model_file =
"/home/alessandro/projects/drone_ws/src/fato_tracker/data/ros_hydro/"
"ros_hydro.obj";
params.object_descriptors_file =
"/home/alessandro/projects/drone_ws/src/fato_tracker/data/ros_hydro/"
"ros_hydro_features.h5";
params.translation_x = 0.00;
params.translation_y = 0.0;
params.translation_z = 0.0;
params.rotation_x = 0.0;
params.rotation_y = 0.0;
params.min_scale = 0.0;
params.max_scale = 0.0;
params.framerate = 30;
params.result_file = "/home/alessandro/debug/result.txt";
params.running_time = 20.0;
}
int main(int argc, char **argv) {
ros::init(argc, argv, "synthetic_benchmark");
// ros::NodeHandle nh;
ParamsBench params;
// readParameters(params);
loadParameters(params);
testObjectMovement(params);
return 0;
}
| 31.90084 | 80 | 0.640272 | clickcao |
c1fbe49daca95bdaaa9b831113042e4ac43b03a6 | 1,863 | cpp | C++ | Source/Particles/Gather/GetExternalFields.cpp | rlombardini76/artemis | 268f59491b263d6ea0197440abc837e1610279fc | [
"BSD-3-Clause-LBNL"
] | 2 | 2020-12-02T15:27:51.000Z | 2021-01-13T11:31:37.000Z | Source/Particles/Gather/GetExternalFields.cpp | rlombardini76/artemis | 268f59491b263d6ea0197440abc837e1610279fc | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/Particles/Gather/GetExternalFields.cpp | rlombardini76/artemis | 268f59491b263d6ea0197440abc837e1610279fc | [
"BSD-3-Clause-LBNL"
] | null | null | null | #include "WarpX.H"
#include "Particles/Gather/GetExternalFields.H"
GetExternalEField::GetExternalEField (const WarpXParIter& a_pti, int a_offset) noexcept
{
auto& warpx = WarpX::GetInstance();
auto& mypc = warpx.GetPartContainer();
if (mypc.m_E_ext_particle_s=="constant" || mypc.m_E_ext_particle_s=="default")
{
m_type = Constant;
m_field_value[0] = mypc.m_E_external_particle[0];
m_field_value[1] = mypc.m_E_external_particle[1];
m_field_value[2] = mypc.m_E_external_particle[2];
}
else if (mypc.m_E_ext_particle_s=="parse_e_ext_particle_function")
{
m_type = Parser;
m_time = warpx.gett_new(a_pti.GetLevel());
m_get_position = GetParticlePosition(a_pti, a_offset);
m_xfield_partparser = getParser(mypc.m_Ex_particle_parser);
m_yfield_partparser = getParser(mypc.m_Ey_particle_parser);
m_zfield_partparser = getParser(mypc.m_Ez_particle_parser);
}
}
GetExternalBField::GetExternalBField (const WarpXParIter& a_pti, int a_offset) noexcept
{
auto& warpx = WarpX::GetInstance();
auto& mypc = warpx.GetPartContainer();
if (mypc.m_B_ext_particle_s=="constant" || mypc.m_B_ext_particle_s=="default")
{
m_type = Constant;
m_field_value[0] = mypc.m_B_external_particle[0];
m_field_value[1] = mypc.m_B_external_particle[1];
m_field_value[2] = mypc.m_B_external_particle[2];
}
else if (mypc.m_B_ext_particle_s=="parse_b_ext_particle_function")
{
m_type = Parser;
m_time = warpx.gett_new(a_pti.GetLevel());
m_get_position = GetParticlePosition(a_pti, a_offset);
m_xfield_partparser = getParser(mypc.m_Bx_particle_parser);
m_yfield_partparser = getParser(mypc.m_By_particle_parser);
m_zfield_partparser = getParser(mypc.m_Bz_particle_parser);
}
}
| 39.638298 | 87 | 0.701557 | rlombardini76 |
c1fcafe794e6e4fbb6165e6a14667a3a0077b71c | 881 | hpp | C++ | examples/stm32f103c8t6_blue_pill/environment/thread_bmp180.hpp | roboterclubaachen/xpcc | 010924901947381d20e83b838502880eb2ffea72 | [
"BSD-3-Clause"
] | 161 | 2015-01-13T15:52:06.000Z | 2020-02-13T01:26:04.000Z | examples/stm32f103c8t6_blue_pill/environment/thread_bmp180.hpp | salkinium/xpcc | 010924901947381d20e83b838502880eb2ffea72 | [
"BSD-3-Clause"
] | 281 | 2015-01-06T12:46:40.000Z | 2019-01-06T13:06:57.000Z | examples/stm32f103c8t6_blue_pill/environment/thread_bmp180.hpp | salkinium/xpcc | 010924901947381d20e83b838502880eb2ffea72 | [
"BSD-3-Clause"
] | 51 | 2015-03-03T19:56:12.000Z | 2020-03-22T02:13:36.000Z | #ifndef THREAD_BMP180
#define THREAD_BMP180
#include <xpcc/processing/timer.hpp>
#include <xpcc/processing/protothread.hpp>
#include <xpcc/driver/pressure/bmp085.hpp>
#include "hardware.hpp"
class Bmp180Thread: public xpcc::pt::Protothread
{
public:
Bmp180Thread();
bool
update();
bool
startMeasurement();
bool
isNewDataAvailable() {
return new_data;
}
int16_t
getTemperatureA() {
return dataA.getTemperature();
}
int32_t
getPressureA() {
return dataA.getPressure();
}
int16_t
getTemperatureB() {
return dataB.getTemperature();
}
int32_t
getPressureB() {
return dataB.getPressure();
}
private:
xpcc::ShortTimeout timeout;
xpcc::bmp085::Data dataA;
xpcc::Bmp085<SensorsAI2cMaster> barometerA;
xpcc::bmp085::Data dataB;
xpcc::Bmp085<SensorsBI2cMaster> barometerB;
bool start_measurement;
bool new_data;
};
#endif // THREAD_BMP180
| 14.442623 | 48 | 0.734393 | roboterclubaachen |
c1fdb9a3258b8c5663524afa0f0df13fa1d2d4b5 | 4,140 | cpp | C++ | external/openglcts/modules/common/glcNoErrorTests.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 354 | 2017-01-24T17:12:38.000Z | 2022-03-30T07:40:19.000Z | external/openglcts/modules/common/glcNoErrorTests.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 275 | 2017-01-24T20:10:36.000Z | 2022-03-24T16:24:50.000Z | external/openglcts/modules/common/glcNoErrorTests.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 190 | 2017-01-24T18:02:04.000Z | 2022-03-27T13:11:23.000Z | /*-------------------------------------------------------------------------
* OpenGL Conformance Test Suite
* -----------------------------
*
* Copyright (c) 2017 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/ /*!
* \file
* \brief
*/ /*-------------------------------------------------------------------*/
/**
*/ /*!
* \file glcNoErrorTests.cpp
* \brief Conformance tests for the GL_KHR_no_error functionality.
*/ /*--------------------------------------------------------------------*/
#include "glcNoErrorTests.hpp"
#include "gluContextInfo.hpp"
#include "gluDefs.hpp"
#include "glwEnums.hpp"
#include "glwFunctions.hpp"
#include "tcuCommandLine.hpp"
#include "tcuTestLog.hpp"
using namespace glu;
namespace glcts
{
/** Constructor.
*
* @param context Rendering context
* @param name Test name
* @param description Test description
* @param apiType API version
*/
NoErrorContextTest::NoErrorContextTest(tcu::TestContext& testCtx, glu::ApiType apiType)
: tcu::TestCase(testCtx, "create_context", "Test verifies if it is possible to create context with "
"CONTEXT_FLAG_NO_ERROR_BIT_KHR flag set in CONTEXT_FLAGS")
, m_ApiType(apiType)
{
/* Left blank intentionally */
}
/** Tears down any GL objects set up to run the test. */
void NoErrorContextTest::deinit(void)
{
}
/** Stub init method */
void NoErrorContextTest::init(void)
{
}
/** Veriffy if no error context can be successfully created.
* @return True when no error context was successfully created.
*/
bool NoErrorContextTest::verifyNoErrorContext(void)
{
RenderConfig renderCfg(glu::ContextType(m_ApiType, glu::CONTEXT_NO_ERROR));
const tcu::CommandLine& commandLine = m_testCtx.getCommandLine();
glu::parseRenderConfig(&renderCfg, commandLine);
if (commandLine.getSurfaceType() != tcu::SURFACETYPE_WINDOW)
throw tcu::NotSupportedError("Test not supported in non-windowed context");
RenderContext* noErrorContext = createRenderContext(m_testCtx.getPlatform(), commandLine, renderCfg);
bool contextCreated = (noErrorContext != NULL);
delete noErrorContext;
return contextCreated;
}
/** Executes test iteration.
*
* @return Returns STOP when test has finished executing, CONTINUE if more iterations are needed.
*/
tcu::TestNode::IterateResult NoErrorContextTest::iterate(void)
{
{
glu::ContextType contextType(m_ApiType);
deqp::Context context(m_testCtx, contextType);
bool noErrorExtensionExists = glu::contextSupports(contextType, glu::ApiType::core(4, 6));
noErrorExtensionExists |= context.getContextInfo().isExtensionSupported("GL_KHR_no_error");
if (!noErrorExtensionExists)
{
m_testCtx.setTestResult(QP_TEST_RESULT_NOT_SUPPORTED, "GL_KHR_no_error extension not supported");
return STOP;
}
} // at this point intermediate context used to query the GL_KHR_no_error extension should be destroyed
if (verifyNoErrorContext())
{
m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass");
return STOP;
}
m_testCtx.getLog() << tcu::TestLog::Message << "Failed to create No Error context" << tcu::TestLog::EndMessage;
m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail");
return STOP;
}
/** Constructor.
*
* @param context Rendering context.
*/
NoErrorTests::NoErrorTests(tcu::TestContext& testCtx, glu::ApiType apiType)
: tcu::TestCaseGroup(testCtx, "no_error", "Verify conformance of GL_KHR_no_error implementation")
, m_ApiType(apiType)
{
}
/** Initializes the test group contents. */
void NoErrorTests::init(void)
{
addChild(new NoErrorContextTest(m_testCtx, m_ApiType));
}
} /* glcts namespace */
| 30.666667 | 112 | 0.694686 | iabernikhin |
c1fdd224e4088547b05dff16b70c6647758ba0c5 | 38,377 | cpp | C++ | external/vulkancts/modules/vulkan/image/vktImageMismatchedWriteOpTests.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 354 | 2017-01-24T17:12:38.000Z | 2022-03-30T07:40:19.000Z | external/vulkancts/modules/vulkan/image/vktImageMismatchedWriteOpTests.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 275 | 2017-01-24T20:10:36.000Z | 2022-03-24T16:24:50.000Z | external/vulkancts/modules/vulkan/image/vktImageMismatchedWriteOpTests.cpp | iabernikhin/VK-GL-CTS | a3338eb2ded98b5befda64f9325db0d219095a00 | [
"Apache-2.0"
] | 190 | 2017-01-24T18:02:04.000Z | 2022-03-27T13:11:23.000Z | /*------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2021 The Khronos Group Inc.
* Copyright (c) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief Image OpImageWrite tests.
*//*--------------------------------------------------------------------*/
#include "vktImageMismatchedWriteOpTests.hpp"
#include "vktImageTexture.hpp"
#include "vkImageUtil.hpp"
#include "vkBuilderUtil.hpp"
#include "vkObjUtil.hpp"
#include "vktImageTestsUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkCmdUtil.hpp"
#include "vkBarrierUtil.hpp"
#include "tcuStringTemplate.hpp"
#include "tcuTexture.hpp"
#include "tcuTextureUtil.hpp"
#include <set>
#define EPSILON_COMPARE(a,b,e) ((de::max((a),(b))-de::min((a),(b)))<=(e))
using namespace vk;
namespace vkt
{
namespace image
{
namespace
{
using tcu::TextureFormat;
using tcu::StringTemplate;
using tcu::TextureChannelClass;
using strings = std::map<std::string, std::string>;
class MismatchedWriteOpTest : public TestCase
{
public:
struct Params
{
VkFormat vkFormat;
int textureWidth;
int textureHeight;
VkFormat spirvFormat;
};
typedef de::SharedPtr<Params> ParamsSp;
MismatchedWriteOpTest (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const ParamsSp params)
: TestCase (testCtx, name, description)
, m_params (params)
{
}
virtual void checkSupport (Context& context) const override;
virtual TextureFormat getBufferFormat (void) const;
void getProgramCodeAndVariables (StringTemplate& code,
strings& variables) const;
template<class TestParams> void getParams(TestParams&);
protected:
const ParamsSp m_params;
};
class MismatchedVectorSizesTest : public MismatchedWriteOpTest
{
public:
MismatchedVectorSizesTest (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const ParamsSp params,
const int sourceWidth)
: MismatchedWriteOpTest (testCtx, name, description, params)
, m_sourceWidth (sourceWidth)
{
DE_ASSERT(getNumUsedChannels(params->vkFormat) <= sourceWidth);
}
virtual void initPrograms (SourceCollections& programCollection) const override;
virtual TestInstance* createInstance (Context& context) const override;
private:
const int m_sourceWidth;
};
class MismatchedSignednessAndTypeTest : public MismatchedWriteOpTest
{
public:
MismatchedSignednessAndTypeTest (tcu::TestContext& testCtx,
const std::string& name,
const std::string& description,
const ParamsSp params)
: MismatchedWriteOpTest (testCtx, name, description, params)
{
}
virtual void initPrograms (SourceCollections& programCollection) const override;
virtual TestInstance* createInstance (Context& context) const override;
};
class MismatchedWriteOpTestInstance : public TestInstance
{
public:
using TestClass = MismatchedWriteOpTest;
using ParamsSp = MismatchedWriteOpTest::ParamsSp;
MismatchedWriteOpTestInstance (Context& context,
const ParamsSp params,
const TestClass* test)
: TestInstance (context)
, m_params (params)
, m_test (test)
{
}
virtual tcu::TestStatus iterate (void) override;
virtual void clear (tcu::PixelBufferAccess& data) const;
virtual void populate (tcu::PixelBufferAccess& data) const;
virtual bool compare (tcu::PixelBufferAccess& result,
tcu::PixelBufferAccess& reference) const = 0;
protected:
const ParamsSp m_params;
const TestClass* m_test;
};
class MismatchedVectorSizesTestInstance : public MismatchedWriteOpTestInstance
{
public:
MismatchedVectorSizesTestInstance (Context& context,
const ParamsSp params,
const TestClass* test)
: MismatchedWriteOpTestInstance (context, params, test)
{
}
bool compare (tcu::PixelBufferAccess& result,
tcu::PixelBufferAccess& reference) const override;
};
class MismatchedSignednessAndTypeTestInstance : public MismatchedWriteOpTestInstance
{
public:
MismatchedSignednessAndTypeTestInstance (Context& context,
const ParamsSp params,
const TestClass* test)
: MismatchedWriteOpTestInstance (context, params, test)
{
}
bool compare (tcu::PixelBufferAccess& result,
tcu::PixelBufferAccess& reference) const override;
};
namespace ut
{
class StorageBuffer2D
{
public:
StorageBuffer2D (Context& context,
const tcu::TextureFormat& format,
deUint32 width,
deUint32 height);
VkBuffer getBuffer (void) const { return *m_buffer; }
VkDeviceSize getSize (void) const { return m_bufferSize; }
tcu::PixelBufferAccess& getPixelAccess (void) { return m_access[0]; }
void flush (void) { flushAlloc(m_context.getDeviceInterface(), m_context.getDevice(), *m_bufferMemory); }
void invalidate (void) { invalidateAlloc(m_context.getDeviceInterface(), m_context.getDevice(), *m_bufferMemory); }
protected:
friend class StorageImage2D;
Allocation& getMemory (void) const { return *m_bufferMemory; }
private:
Context& m_context;
const tcu::TextureFormat m_format;
const deUint32 m_width;
const deUint32 m_height;
const VkDeviceSize m_bufferSize;
Move<VkBuffer> m_buffer;
de::MovePtr<Allocation> m_bufferMemory;
std::vector<tcu::PixelBufferAccess> m_access;
};
class StorageImage2D
{
public:
StorageImage2D (Context& context,
VkFormat vkFormat,
const int width,
const int height,
bool sparse = false);
VkImageView getView (void) const { return *m_view; }
tcu::PixelBufferAccess& getPixelAccess (void) { return m_buffer.getPixelAccess(); }
void flush (void) { m_buffer.flush(); }
void invalidate (void) { m_buffer.invalidate(); }
void upload (const VkCommandBuffer cmdBuffer);
void download (const VkCommandBuffer cmdBuffer);
private:
Context& m_context;
const bool m_sparse;
const int m_width;
const int m_height;
const vk::VkFormat m_vkFormat;
const tcu::TextureFormat m_texFormat;
StorageBuffer2D m_buffer;
VkImageLayout m_layout;
Move<VkImage> m_image;
Move<VkImageView> m_view;
Move<VkSemaphore> m_semaphore;
std::vector<de::SharedPtr<Allocation>> m_allocations;
de::MovePtr<Allocation> m_imageMemory;
};
StorageImage2D::StorageImage2D (Context& context, VkFormat vkFormat, const int width, const int height, bool sparse)
: m_context (context)
, m_sparse (sparse)
, m_width (width)
, m_height (height)
, m_vkFormat (vkFormat)
, m_texFormat (mapVkFormat(m_vkFormat))
, m_buffer (m_context, m_texFormat, m_width, m_height)
{
const DeviceInterface& vki = m_context.getDeviceInterface();
const VkDevice dev = m_context.getDevice();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
Allocator& allocator = m_context.getDefaultAllocator();
// Create an image
{
VkImageCreateFlags imageCreateFlags = m_sparse? (VK_IMAGE_CREATE_SPARSE_BINDING_BIT | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) : 0u;
VkImageUsageFlags imageUsageFlags = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
const VkImageCreateInfo imageCreateInfo =
{
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
imageCreateFlags, // VkImageCreateFlags flags;
VK_IMAGE_TYPE_2D, // VkImageType imageType;
m_vkFormat, // VkFormat format;
{ deUint32(m_width), deUint32(m_height), 1u }, // VkExtent3D extent;
1u, // deUint32 mipLevels;
1u, // deUint32 arrayLayers;
VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples;
VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling;
imageUsageFlags, // VkImageUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyIndexCount;
&queueFamilyIndex, // const deUint32* pQueueFamilyIndices;
(m_layout = VK_IMAGE_LAYOUT_UNDEFINED) // VkImageLayout initialLayout;
};
m_image = createImage(vki, dev, &imageCreateInfo);
if (m_sparse)
{
m_semaphore = createSemaphore(vki, dev);
allocateAndBindSparseImage( vki, dev, m_context.getPhysicalDevice(), m_context.getInstanceInterface(),
imageCreateInfo, *m_semaphore, m_context.getSparseQueue(),
allocator, m_allocations, mapVkFormat(m_vkFormat), *m_image );
}
else
{
m_imageMemory = allocator.allocate(getImageMemoryRequirements(vki, dev, *m_image), MemoryRequirement::Any);
VK_CHECK(vki.bindImageMemory(dev, *m_image, m_imageMemory->getMemory(), m_imageMemory->getOffset()));
}
VkImageSubresourceRange subresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
m_view = makeImageView(vki, dev, *m_image, VK_IMAGE_VIEW_TYPE_2D, m_vkFormat, subresourceRange);
}
}
void StorageImage2D::upload (const VkCommandBuffer cmdBuffer)
{
const DeviceInterface& vki = m_context.getDeviceInterface();
const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
const VkBufferImageCopy copyRegion = makeBufferImageCopy(makeExtent3D(tcu::IVec3(m_width, m_height, 1)), 1u);
{
const VkBufferMemoryBarrier bufferBarrier = makeBufferMemoryBarrier(
VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
m_buffer.getBuffer(), 0ull, m_buffer.getSize());
const VkImageMemoryBarrier beforeCopyBarrier = makeImageMemoryBarrier(
(VkAccessFlagBits)0, VK_ACCESS_TRANSFER_WRITE_BIT,
m_layout, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
*m_image, fullImageSubresourceRange);
vki.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0,
0, (const VkMemoryBarrier*)DE_NULL, 1, &bufferBarrier, 1, &beforeCopyBarrier);
}
vki.cmdCopyBufferToImage(cmdBuffer, m_buffer.getBuffer(), *m_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, ©Region);
{
const VkBufferMemoryBarrier bufferBarrier = makeBufferMemoryBarrier(
VK_ACCESS_TRANSFER_READ_BIT, (VkAccessFlags)0,
m_buffer.getBuffer(), 0ull, m_buffer.getSize());
m_layout = VK_IMAGE_LAYOUT_GENERAL;
const VkImageMemoryBarrier afterCopyBarrier = makeImageMemoryBarrier(
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_WRITE_BIT,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, m_layout,
*m_image, fullImageSubresourceRange);
vki.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, (VkDependencyFlags)0,
0, (const VkMemoryBarrier*)DE_NULL, 1, &bufferBarrier, 1, &afterCopyBarrier);
}
}
void StorageImage2D::download (const VkCommandBuffer cmdBuffer)
{
const DeviceInterface& vki = m_context.getDeviceInterface();
const VkImageSubresourceRange fullImageSubresourceRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u);
const VkBufferImageCopy copyRegion = makeBufferImageCopy(makeExtent3D(tcu::IVec3(m_width, m_height, 1)), 1u);
{
const VkBufferMemoryBarrier bufferBarrier = makeBufferMemoryBarrier(
(VkAccessFlags)0, VK_ACCESS_TRANSFER_WRITE_BIT,
m_buffer.getBuffer(), 0ull, m_buffer.getSize());
const VkImageMemoryBarrier beforeCopyBarrier = makeImageMemoryBarrier(
VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT,
m_layout, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
*m_image, fullImageSubresourceRange);
vki.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, (VkDependencyFlags)0,
0, (const VkMemoryBarrier*)DE_NULL, 1, &bufferBarrier, 1, &beforeCopyBarrier);
}
vki.cmdCopyImageToBuffer(cmdBuffer, *m_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, m_buffer.getBuffer(), 1, ©Region);
{
const VkBufferMemoryBarrier bufferBarrier = makeBufferMemoryBarrier(
VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT,
m_buffer.getBuffer(), 0ull, m_buffer.getSize());
const VkImageMemoryBarrier afterCopyBarrier = makeImageMemoryBarrier(
VK_ACCESS_TRANSFER_READ_BIT, (VkAccessFlags)0,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, m_layout,
*m_image, fullImageSubresourceRange);
vki.cmdPipelineBarrier(cmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, (VkDependencyFlags)0,
0, (const VkMemoryBarrier*)DE_NULL, 1, &bufferBarrier, 1, &afterCopyBarrier);
}
}
StorageBuffer2D::StorageBuffer2D (Context& context, const tcu::TextureFormat& format, deUint32 width, deUint32 height)
: m_context (context)
, m_format (format)
, m_width (width)
, m_height (height)
, m_bufferSize (m_width * m_height * m_format.getPixelSize())
{
const DeviceInterface& vki = m_context.getDeviceInterface();
const VkDevice dev = m_context.getDevice();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
Allocator& allocator = m_context.getDefaultAllocator();
const VkBufferUsageFlags bufferUsageFlags = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
const VkBufferCreateInfo bufferCreateInfo =
{
VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType;
DE_NULL, // const void* pNext;
0u, // VkBufferCreateFlags flags;
m_bufferSize, // VkDeviceSize size;
bufferUsageFlags, // VkBufferUsageFlags usage;
VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode;
1u, // deUint32 queueFamilyIndexCount;
&queueFamilyIndex // const deUint32* pQueueFamilyIndices;
};
m_buffer = createBuffer(vki, dev, &bufferCreateInfo);
m_bufferMemory = allocator.allocate(getBufferMemoryRequirements(vki, dev, *m_buffer), MemoryRequirement::HostVisible);
VK_CHECK(vki.bindBufferMemory(dev, *m_buffer, m_bufferMemory->getMemory(), m_bufferMemory->getOffset()));
m_access.emplace_back(m_format, tcu::IVec3(m_width, m_height, 1), m_bufferMemory->getHostPtr());
}
tcu::Vec4 gluePixels (const tcu::Vec4& a, const tcu::Vec4& b, const int pivot)
{
tcu::Vec4 result;
for (int i = 0; i < pivot; ++i) result[i] = a[i];
for (int i = pivot; i < 4; ++i) result[i] = b[i];
return result;
}
template<class T, int N>
bool comparePixels (const tcu::Vector<T,N>& res, const tcu::Vector<T,N>& ref, const int targetWidth, const T eps = {})
{
bool ok = true;
for (int i = 0; ok && i < targetWidth; ++i)
{
ok &= EPSILON_COMPARE(res[i], ref[i], eps);
}
return ok;
}
} // ut
TestInstance* MismatchedVectorSizesTest::createInstance (Context& context) const
{
return (new MismatchedVectorSizesTestInstance(context, m_params, this));
}
TestInstance* MismatchedSignednessAndTypeTest::createInstance (Context& context) const
{
return (new MismatchedSignednessAndTypeTestInstance(context, m_params, this));
}
const VkFormat allFormats[] =
{
VK_FORMAT_R32G32B32A32_SFLOAT,
VK_FORMAT_R32G32_SFLOAT,
VK_FORMAT_R32_SFLOAT,
VK_FORMAT_R16G16B16A16_SFLOAT,
VK_FORMAT_R16G16_SFLOAT,
VK_FORMAT_R16_SFLOAT,
VK_FORMAT_R16G16B16A16_UNORM,
VK_FORMAT_R16G16_UNORM,
VK_FORMAT_R16_UNORM,
VK_FORMAT_R16G16B16A16_SNORM,
VK_FORMAT_R16G16_SNORM,
VK_FORMAT_R16_SNORM,
VK_FORMAT_A2B10G10R10_UNORM_PACK32,
VK_FORMAT_B10G11R11_UFLOAT_PACK32,
VK_FORMAT_R8G8B8A8_UNORM,
VK_FORMAT_R8G8_UNORM,
VK_FORMAT_R8_UNORM,
VK_FORMAT_R8G8B8A8_SNORM,
VK_FORMAT_R8G8_SNORM,
VK_FORMAT_R8_SNORM,
VK_FORMAT_R32G32B32A32_SINT,
VK_FORMAT_R32G32_SINT,
VK_FORMAT_R32_SINT,
VK_FORMAT_R16G16B16A16_SINT,
VK_FORMAT_R16G16_SINT,
VK_FORMAT_R16_SINT,
VK_FORMAT_R8G8B8A8_SINT,
VK_FORMAT_R8G8_SINT,
VK_FORMAT_R8_SINT,
VK_FORMAT_R32G32B32A32_UINT,
VK_FORMAT_R32G32_UINT,
VK_FORMAT_R32_UINT,
VK_FORMAT_R16G16B16A16_UINT,
VK_FORMAT_R16G16_UINT,
VK_FORMAT_R16_UINT,
VK_FORMAT_A2B10G10R10_UINT_PACK32,
VK_FORMAT_R8G8B8A8_UINT,
VK_FORMAT_R8G8_UINT,
VK_FORMAT_R8_UINT,
VK_FORMAT_R64_SINT,
VK_FORMAT_R64_UINT,
};
std::vector<VkFormat> findFormatsByChannelClass(TextureChannelClass channelClass)
{
std::vector<VkFormat> result;
for (const VkFormat& f : allFormats)
{
if (getTextureChannelClass(mapVkFormat(f).type) == channelClass)
result.emplace_back(f);
}
DE_ASSERT(!result.empty());
return result;
}
const char* getChannelStr (const TextureFormat::ChannelType& type)
{
switch (type)
{
case TextureFormat::FLOAT: return "float";
case TextureFormat::SIGNED_INT32: return "sint";
case TextureFormat::UNSIGNED_INT32: return "uint";
case TextureFormat::FLOAT64: return "double";
case TextureFormat::SIGNED_INT64: return "slong";
case TextureFormat::UNSIGNED_INT64: return "ulong";
default: DE_ASSERT(DE_FALSE);
}
return nullptr;
}
TextureFormat::ChannelType makeChannelType (tcu::TextureChannelClass channelClass, bool doubled)
{
auto channelType = TextureFormat::ChannelType::CHANNELTYPE_LAST;
switch (channelClass)
{
case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
channelType = doubled ? TextureFormat::ChannelType::SIGNED_INT64 : TextureFormat::ChannelType::SIGNED_INT32;
break;
case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
channelType = doubled ? TextureFormat::ChannelType::UNSIGNED_INT64 : TextureFormat::ChannelType::UNSIGNED_INT32;
break;
default:
channelType = doubled ? TextureFormat::ChannelType::FLOAT64 : TextureFormat::ChannelType::FLOAT;
}
return channelType;
}
TextureFormat makeBufferFormat (tcu::TextureChannelClass channelClass, bool doubled)
{
return TextureFormat(TextureFormat::ChannelOrder::RGBA, makeChannelType(channelClass, doubled));
}
void MismatchedWriteOpTest::checkSupport (Context& context) const
{
// capabilities that may be used in the shader
if (is64BitIntegerFormat(m_params->vkFormat))
{
const VkPhysicalDeviceFeatures deviceFeatures = getPhysicalDeviceFeatures(context.getInstanceInterface(), context.getPhysicalDevice());
if(!deviceFeatures.shaderInt64)
{
TCU_THROW(NotSupportedError, "Device feature shaderInt64 is not supported");
}
context.requireDeviceFunctionality("VK_EXT_shader_image_atomic_int64");
}
// extensions used statically in the shader
context.requireDeviceFunctionality("VK_KHR_variable_pointers");
context.requireDeviceFunctionality("VK_KHR_storage_buffer_storage_class");
VkFormatProperties formatProperties = getPhysicalDeviceFormatProperties(context.getInstanceInterface(), context.getPhysicalDevice(), m_params->vkFormat);
if ((formatProperties.optimalTilingFeatures & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT) == 0)
{
TCU_THROW(NotSupportedError, "Creating storage image with this format is not supported");
}
}
TextureFormat MismatchedWriteOpTest::getBufferFormat (void) const
{
const TextureFormat texFormat = mapVkFormat(m_params->vkFormat);
return makeBufferFormat(getTextureChannelClass(texFormat.type), is64BitIntegerFormat(m_params->vkFormat));
}
void MismatchedWriteOpTest::getProgramCodeAndVariables (StringTemplate& code, strings& variables) const
{
std::string shaderTemplate(R"(
OpCapability Shader
OpCapability StorageImageExtendedFormats
${CAPABILITY_INT64}
OpExtension "SPV_KHR_variable_pointers"
OpExtension "SPV_KHR_storage_buffer_storage_class"
${EXTENSIONS}
%std450 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %main "main" %gid %image %buffer
OpExecutionMode %main LocalSize 1 1 1
OpDecorate %gid BuiltIn GlobalInvocationId
OpDecorate %image DescriptorSet 0
OpDecorate %image Binding 0
OpDecorate %rta ArrayStride ${ARRAY_STRIDE}
OpMemberDecorate %struct 0 Offset 0
OpDecorate %struct Block
OpDecorate %buffer DescriptorSet 0
OpDecorate %buffer Binding 1
%void = OpTypeVoid
%fn_void = OpTypeFunction %void
${TYPES_INT64}
%float = OpTypeFloat 32
%sint = OpTypeInt 32 1
%uint = OpTypeInt 32 0
%v4float = OpTypeVector %float 4
%v3float = OpTypeVector %float 3
%v2float = OpTypeVector %float 2
%v4sint = OpTypeVector %sint 4
%v3sint = OpTypeVector %sint 3
%v2sint = OpTypeVector %sint 2
%v4uint = OpTypeVector %uint 4
%v3uint = OpTypeVector %uint 3
%v2uint = OpTypeVector %uint 2
%v3uint_in_ptr = OpTypePointer Input %v3uint
%gid = OpVariable %v3uint_in_ptr Input
%image_type = OpTypeImage %${SAMPLED_TYPE} 2D 0 0 0 2 ${SPIRV_IMAGE_FORMAT}
%image_ptr = OpTypePointer UniformConstant %image_type
%image = OpVariable %image_ptr UniformConstant
%image_width = OpConstant %sint ${IMAGE_WIDTH}
%image_height = OpConstant %sint ${IMAGE_HEIGHT}
%rta_offset = OpConstant %uint 0
%rta = OpTypeRuntimeArray %v4${SAMPLED_TYPE}
%struct = OpTypeStruct %rta
%ssbo_ptr = OpTypePointer StorageBuffer %struct
%buffer = OpVariable %ssbo_ptr StorageBuffer
%red_offset = OpConstant %uint 0
%green_offset = OpConstant %uint 1
%blue_offset = OpConstant %uint 2
%alpha_offset = OpConstant %uint 3
%${SAMPLED_TYPE}_PTR = OpTypePointer StorageBuffer %${SAMPLED_TYPE}
%var_sint_ptr = OpTypePointer Function %sint
; Entry main procedure
%main = OpFunction %void None %fn_void
%entry = OpLabel
%index = OpVariable %var_sint_ptr Function
; Transform gl_GlobalInvocationID.xyz to ivec2(gl_GlobalInvocationID.xy)
%id = OpLoad %v3uint %gid
%u_id_x = OpCompositeExtract %uint %id 0
%s_id_x = OpBitcast %sint %u_id_x
%u_id_y = OpCompositeExtract %uint %id 1
%s_id_y = OpBitcast %sint %u_id_y
%id_xy = OpCompositeConstruct %v2sint %s_id_x %s_id_y
; Calculate index in buffer
%mul = OpIMul %sint %s_id_y %image_width
%add = OpIAdd %sint %mul %s_id_x
OpStore %index %add
; Final image variable used to read from or write to
%img = OpLoad %image_type %image
; Accessors to buffer components
%idx = OpLoad %sint %index
%alpha_access = OpAccessChain %${SAMPLED_TYPE}_PTR %buffer %rta_offset %idx %alpha_offset
%blue_access = OpAccessChain %${SAMPLED_TYPE}_PTR %buffer %rta_offset %idx %blue_offset
%green_access = OpAccessChain %${SAMPLED_TYPE}_PTR %buffer %rta_offset %idx %green_offset
%red_access = OpAccessChain %${SAMPLED_TYPE}_PTR %buffer %rta_offset %idx %red_offset
%red = OpLoad %${SAMPLED_TYPE} %red_access
%green = OpLoad %${SAMPLED_TYPE} %green_access
%blue = OpLoad %${SAMPLED_TYPE} %blue_access
%alpha = OpLoad %${SAMPLED_TYPE} %alpha_access
${WRITE_TO_IMAGE}
OpReturn
OpFunctionEnd
)");
const std::string typesInt64(R"(
%slong = OpTypeInt 64 1
%ulong = OpTypeInt 64 0
%v4slong = OpTypeVector %slong 4
%v3slong = OpTypeVector %slong 3
%v2slong = OpTypeVector %slong 2
%v4ulong = OpTypeVector %ulong 4
%v3ulong = OpTypeVector %ulong 3
%v2ulong = OpTypeVector %ulong 2
)");
const tcu::TextureFormat buffFormat = getBufferFormat();
variables["SPIRV_IMAGE_FORMAT"] = getSpirvFormat(m_params->vkFormat);
variables["CAPABILITY_INT64"] = "";
variables["EXTENSIONS"] = "";
variables["TYPES_INT64"] = "";
if (is64BitIntegerFormat(m_params->vkFormat))
{
variables["EXTENSIONS"] = "OpExtension \"SPV_EXT_shader_image_int64\"";
variables["CAPABILITY_INT64"] = "OpCapability Int64ImageEXT\n"
"OpCapability Int64";
variables["TYPES_INT64"] = typesInt64;
}
variables["SAMPLED_TYPE"] = getChannelStr(buffFormat.type);
variables["IMAGE_WIDTH"] = std::to_string(m_params->textureWidth);
variables["IMAGE_HEIGHT"] = std::to_string(m_params->textureHeight);
variables["ARRAY_STRIDE"] = std::to_string(tcu::getChannelSize(buffFormat.type) * tcu::getNumUsedChannels(buffFormat.order));
code.setString(shaderTemplate);
}
void MismatchedVectorSizesTest::initPrograms (SourceCollections& programCollection) const
{
strings variables {};
StringTemplate shaderTemplate {};
const StringTemplate writeFromSingleComponent (R"(
OpImageWrite %img %id_xy %red
)");
const StringTemplate writeFromTwoComponents (R"(
%rg = OpCompositeConstruct %v2${SAMPLED_TYPE} %red %green
OpImageWrite %img %id_xy %rg
)");
const StringTemplate writeFromThreeComponents (R"(
%rgb = OpCompositeConstruct %v3${SAMPLED_TYPE} %red %green %blue
OpImageWrite %img %id_xy %rgb
)");
const StringTemplate writeFromFourComponents (R"(
%rgba = OpCompositeConstruct %v4${SAMPLED_TYPE} %red %green %blue %alpha
OpImageWrite %img %id_xy %rgba
)");
getProgramCodeAndVariables(shaderTemplate, variables);
variables["WRITE_TO_IMAGE"] = (m_sourceWidth == 1
? writeFromSingleComponent
: m_sourceWidth == 2
? writeFromTwoComponents
: m_sourceWidth == 3
? writeFromThreeComponents
: writeFromFourComponents).specialize(variables);
programCollection.spirvAsmSources.add("comp")
<< shaderTemplate.specialize(variables)
<< vk::SpirVAsmBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_4, true);
}
void MismatchedSignednessAndTypeTest::initPrograms (SourceCollections& programCollection) const
{
strings variables {};
StringTemplate shaderTemplate {};
const StringTemplate writeToImage (R"(
%color = OpCompositeConstruct %v4${SAMPLED_TYPE} %red %green %blue %alpha
OpImageWrite %img %id_xy %color
)");
getProgramCodeAndVariables(shaderTemplate, variables);
variables["WRITE_TO_IMAGE"] = writeToImage.specialize(variables);
programCollection.spirvAsmSources.add("comp")
<< shaderTemplate.specialize(variables)
<< vk::SpirVAsmBuildOptions(programCollection.usedVulkanVersion, vk::SPIRV_VERSION_1_4, true);
}
void MismatchedWriteOpTestInstance::clear (tcu::PixelBufferAccess& pixels) const
{
const auto channelClass = tcu::getTextureChannelClass(mapVkFormat(m_params->vkFormat).type);
switch (channelClass)
{
case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
tcu::clear(pixels, tcu::IVec4(-1, -2, -3, -4));
break;
case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
tcu::clear(pixels, tcu::UVec4(1, 2, 3, 4));
break;
default:
tcu::clear(pixels, tcu::Vec4(0.2f, 0.3f, 0.4f, 0.5f));
}
}
void MismatchedWriteOpTestInstance::populate (tcu::PixelBufferAccess& pixels) const
{
const auto texFormat = mapVkFormat(m_params->vkFormat);
const auto bitDepth = tcu::getTextureFormatBitDepth(texFormat);
const auto channelClass = tcu::getTextureChannelClass(texFormat.type);
const tcu::IVec4 signedMinValues (bitDepth[0] ? deIntMinValue32(deMin32(bitDepth[0], 32)) : (-1),
bitDepth[1] ? deIntMinValue32(deMin32(bitDepth[1], 32)) : (-1),
bitDepth[2] ? deIntMinValue32(deMin32(bitDepth[2], 32)) : (-1),
bitDepth[3] ? deIntMinValue32(deMin32(bitDepth[3], 32)) : (-1));
const tcu::IVec4 signedMaxValues (bitDepth[0] ? deIntMaxValue32(deMin32(bitDepth[0], 32)) : 1,
bitDepth[1] ? deIntMaxValue32(deMin32(bitDepth[1], 32)) : 1,
bitDepth[2] ? deIntMaxValue32(deMin32(bitDepth[2], 32)) : 1,
bitDepth[3] ? deIntMaxValue32(deMin32(bitDepth[3], 32)) : 1);
const tcu::UVec4 unsignedMinValues (0u);
const tcu::UVec4 unsignedMaxValues (bitDepth[0] ? deUintMaxValue32(deMin32(bitDepth[0], 32)) : 1u,
bitDepth[1] ? deUintMaxValue32(deMin32(bitDepth[1], 32)) : 1u,
bitDepth[2] ? deUintMaxValue32(deMin32(bitDepth[2], 32)) : 1u,
bitDepth[3] ? deUintMaxValue32(deMin32(bitDepth[3], 32)) : 1u);
auto nextSigned = [&](tcu::IVec4& color)
{
color[0] = (static_cast<deInt64>(color[0] + 2) < signedMaxValues[0]) ? (color[0] + 2) : signedMinValues[0];
color[1] = (static_cast<deInt64>(color[1] + 3) < signedMaxValues[1]) ? (color[1] + 3) : signedMinValues[1];
color[2] = (static_cast<deInt64>(color[2] + 5) < signedMaxValues[2]) ? (color[2] + 5) : signedMinValues[2];
color[3] = (static_cast<deInt64>(color[3] + 7) < signedMaxValues[3]) ? (color[3] + 7) : signedMinValues[3];
};
auto nextUnsigned = [&](tcu::UVec4& color)
{
color[0] = (static_cast<deUint64>(color[0] + 2) < unsignedMaxValues[0]) ? (color[0] + 2) : unsignedMinValues[0];
color[1] = (static_cast<deUint64>(color[1] + 3) < unsignedMaxValues[1]) ? (color[1] + 3) : unsignedMinValues[1];
color[2] = (static_cast<deUint64>(color[2] + 5) < unsignedMaxValues[2]) ? (color[2] + 5) : unsignedMinValues[2];
color[3] = (static_cast<deUint64>(color[3] + 7) < unsignedMaxValues[3]) ? (color[3] + 7) : unsignedMinValues[3];
};
deUint64 floatsData [4];
tcu::PixelBufferAccess floatsAccess (texFormat, 1, 1, 1, floatsData);
tcu::Vec4 tmpFloats (0.0f);
const float divider (static_cast<float>(m_params->textureHeight));
const tcu::Vec4 ufloatStep (1.0f/(divider*1.0f), 1.0f/(divider*2.0f), 1.0f/(divider*3.0f), 1.0f/(divider*5.0f));
const tcu::Vec4 sfloatStep (2.0f/(divider*1.0f), 2.0f/(divider*2.0f), 2.0f/(divider*3.0f), 2.0f/(divider*5.0f));
tcu::IVec4 signedColor (0);
tcu::UVec4 unsignedColor (0u);
tcu::Vec4 ufloatColor (0.0f);
tcu::Vec4 sfloatColor (-1.0f);
for (int y = 0; y < m_params->textureHeight; ++y)
{
for (int x = 0; x < m_params->textureWidth; ++x)
{
switch (channelClass)
{
case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
pixels.setPixel(signedColor, x, y);
break;
case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
pixels.setPixel(unsignedColor, x, y);
break;
case tcu::TEXTURECHANNELCLASS_SIGNED_FIXED_POINT:
floatsAccess.setPixel(sfloatColor, 0, 0);
tmpFloats = ut::gluePixels(floatsAccess.getPixel(0, 0), sfloatColor, tcu::getNumUsedChannels(texFormat.order));
pixels.setPixel(tmpFloats, x, y);
break;
// TEXTURECHANNELCLASS_FLOATING_POINT or
// TEXTURECHANNELCLASS_UNSIGNED_FIXED_POINT
default:
floatsAccess.setPixel(ufloatColor, 0, 0);
tmpFloats = ut::gluePixels(floatsAccess.getPixel(0, 0), ufloatColor, tcu::getNumUsedChannels(texFormat.order));
pixels.setPixel(tmpFloats, x, y);
break;
}
}
nextSigned (signedColor);
nextUnsigned (unsignedColor);
sfloatColor += sfloatStep;
ufloatColor += ufloatStep;
}
}
tcu::TestStatus MismatchedWriteOpTestInstance::iterate (void)
{
const DeviceInterface& vki = m_context.getDeviceInterface();
const VkDevice dev = m_context.getDevice();
const VkQueue queue = m_context.getUniversalQueue();
const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex();
Move<VkCommandPool> cmdPool = createCommandPool(vki, dev, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, queueFamilyIndex);
Move<VkCommandBuffer> cmdBuffer = allocateCommandBuffer(vki, dev, *cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY);
Move<VkShaderModule> shaderModule = createShaderModule(vki, dev, m_context.getBinaryCollection().get("comp"), 0);
Move<VkDescriptorSetLayout> descriptorSetLayout = DescriptorSetLayoutBuilder()
.addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT)
.addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT)
.build(vki, dev);
Move<VkDescriptorPool> descriptorPool = DescriptorPoolBuilder()
.addType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE)
.addType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)
.build(vki, dev, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u);
Move<VkDescriptorSet> descriptorSet = makeDescriptorSet(vki, dev, *descriptorPool, *descriptorSetLayout);
Move<VkPipelineLayout> pipelineLayout = makePipelineLayout(vki, dev, *descriptorSetLayout);
Move<VkPipeline> pipeline = makeComputePipeline(vki, dev, *pipelineLayout, *shaderModule);
ut::StorageImage2D image (m_context, m_params->vkFormat, m_params->textureWidth, m_params->textureHeight);
ut::StorageBuffer2D buffer (m_context, m_test->getBufferFormat(), m_params->textureWidth, m_params->textureHeight);
VkDescriptorImageInfo inputImageInfo = makeDescriptorImageInfo(DE_NULL, image.getView(), VK_IMAGE_LAYOUT_GENERAL);
VkDescriptorBufferInfo outputBufferInfo = makeDescriptorBufferInfo(buffer.getBuffer(), 0u, buffer.getSize());
DescriptorSetUpdateBuilder builder;
builder
.writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &inputImageInfo)
.writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &outputBufferInfo)
.update(vki, dev);
populate (buffer.getPixelAccess());
clear (image.getPixelAccess());
beginCommandBuffer(vki, *cmdBuffer);
image.upload(*cmdBuffer);
vki.cmdBindPipeline(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipeline);
vki.cmdBindDescriptorSets(*cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *pipelineLayout, 0u, 1u, &descriptorSet.get(), 0u, DE_NULL);
vki.cmdDispatch(*cmdBuffer, m_params->textureWidth, m_params->textureHeight, 1);
image.download(*cmdBuffer);
endCommandBuffer(vki, *cmdBuffer);
image.flush();
buffer.flush();
submitCommandsAndWait(vki, dev, queue, *cmdBuffer);
image.invalidate();
buffer.invalidate();
return compare(image.getPixelAccess(), buffer.getPixelAccess())
? tcu::TestStatus::pass("")
: tcu::TestStatus::fail("Pixel comparison failed");
}
bool MismatchedVectorSizesTestInstance::compare (tcu::PixelBufferAccess& result, tcu::PixelBufferAccess& reference) const
{
const tcu::TextureFormat texFormat = mapVkFormat(m_params->vkFormat);
const tcu::TextureChannelClass channelClass = tcu::getTextureChannelClass(texFormat.type);
const int targetWidth = getNumUsedChannels(texFormat.order);
bool doContinue = true;
for (int y = 0; doContinue && y < m_params->textureHeight; ++y)
{
for (int x = 0; doContinue && x < m_params->textureWidth; ++x)
{
switch (channelClass)
{
case tcu::TEXTURECHANNELCLASS_SIGNED_INTEGER:
doContinue = ut::comparePixels(result.getPixelInt(x,y), reference.getPixelInt(x,y), targetWidth );
break;
case tcu::TEXTURECHANNELCLASS_UNSIGNED_INTEGER:
doContinue = ut::comparePixels(result.getPixelUint(x,y), reference.getPixelUint(x,y), targetWidth );
break;
default:
doContinue = ut::comparePixels(result.getPixel(x,y), reference.getPixel(x,y), targetWidth, 0.0005f);
break;
}
}
}
return doContinue;
}
bool MismatchedSignednessAndTypeTestInstance::compare (tcu::PixelBufferAccess& result, tcu::PixelBufferAccess& reference) const
{
DE_UNREF(result);
DE_UNREF(reference);
return true;
}
} // anonymous
tcu::TestCaseGroup* createImageWriteOpTests (tcu::TestContext& testCtx)
{
std::stringstream ss;
auto genVectorSizesTestName = [&](const VkFormat& f, const int sourceWidth) -> std::string
{
ss.str(std::string());
ss << de::toLower(getSpirvFormat(f)) << "_from";
if (sourceWidth > 1)
ss << "_vec" << sourceWidth;
else ss << "_scalar";
return ss.str();
};
auto testGroup = new tcu::TestCaseGroup(testCtx, "mismatched_write_op", "Test image OpImageWrite operation in various aspects.");
auto testGroupMismatchedVectorSizes = new tcu::TestCaseGroup(testCtx, "mismatched_vector_sizes", "Case OpImageWrite operation on mismatched vector sizes.");
auto testGroupMismatchedSignedness = new tcu::TestCaseGroup(testCtx, "mismatched_signedness_and_type", "Case OpImageWrite operation on mismatched signedness and values.");
for (const VkFormat& f : allFormats)
{
const auto switchClass = getTextureChannelClass(mapVkFormat(f).type);
auto compatibleFormats = findFormatsByChannelClass(switchClass);
auto end = compatibleFormats.cend();
auto begin = compatibleFormats.cbegin();
for (auto i = begin; i != end; ++i)
{
if (is64BitIntegerFormat(i[0]) || is64BitIntegerFormat(f)) continue;
const std::string testName = de::toLower(getSpirvFormat(i[0])) + "_from_" + de::toLower(getSpirvFormat(f));
auto params = new MismatchedWriteOpTest::Params { f, 12, 8*static_cast<int>(std::distance(begin,i)+1), i[0] };
testGroupMismatchedSignedness->addChild(new MismatchedSignednessAndTypeTest(testCtx, testName, {}, MismatchedVectorSizesTest::ParamsSp(params)));
}
for (int sourceWidth = 4; sourceWidth > 0; --sourceWidth)
{
if (sourceWidth >= getNumUsedChannels(f))
{
auto params = new MismatchedWriteOpTest::Params { f, 12*sourceWidth, 8*(4-sourceWidth+1), f };
testGroupMismatchedVectorSizes->addChild(
new MismatchedVectorSizesTest(testCtx, genVectorSizesTestName(f, sourceWidth), {}, MismatchedVectorSizesTest::ParamsSp(params), sourceWidth));
}
}
}
testGroup->addChild(testGroupMismatchedVectorSizes);
testGroup->addChild(testGroupMismatchedSignedness);
return testGroup;
}
} // image
} // vkt
| 36.65425 | 172 | 0.715402 | iabernikhin |
de00be4d0f1b03344bc2724dfe63180bcba2c6c0 | 22,435 | cpp | C++ | src/jitcat/ASTHelper.cpp | mvhooren/JitCat | 8e05b51c5feda8fa9258ba443854b23c4ad8bf7c | [
"MIT"
] | 14 | 2019-03-16T07:00:44.000Z | 2021-10-20T23:36:51.000Z | src/jitcat/ASTHelper.cpp | mvhooren/JitCat | 8e05b51c5feda8fa9258ba443854b23c4ad8bf7c | [
"MIT"
] | 13 | 2019-11-22T12:43:55.000Z | 2020-05-25T13:09:08.000Z | src/jitcat/ASTHelper.cpp | mvhooren/JitCat | 8e05b51c5feda8fa9258ba443854b23c4ad8bf7c | [
"MIT"
] | 1 | 2019-11-23T17:59:58.000Z | 2019-11-23T17:59:58.000Z | /*
This file is part of the JitCat library.
Copyright (C) Machiel van Hooren 2018
Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/
#include "jitcat/ASTHelper.h"
#include "jitcat/CatArgumentList.h"
#include "jitcat/CatAssignableExpression.h"
#include "jitcat/CatBuiltInFunctionCall.h"
#include "jitcat/CatIdentifier.h"
#include "jitcat/CatIndirectionConversion.h"
#include "jitcat/CatRuntimeContext.h"
#include "jitcat/CatScopeBlock.h"
#include "jitcat/CatTypedExpression.h"
#include "jitcat/ExpressionErrorManager.h"
#include "jitcat/FunctionSignature.h"
#include "jitcat/ReflectableHandle.h"
#include "jitcat/Tools.h"
#include "jitcat/TypeInfo.h"
#include <cassert>
#include <sstream>
using namespace jitcat;
using namespace jitcat::AST;
using namespace jitcat::Reflection;
void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatScopeBlock>& uPtr, CatStatement* statement)
{
if (uPtr.get() != static_cast<CatScopeBlock*>(statement))
{
uPtr.reset(static_cast<CatScopeBlock*>(statement));
}
}
void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatStatement>& uPtr, CatStatement* statement)
{
if (uPtr.get() != statement)
{
uPtr.reset(statement);
}
}
void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatTypedExpression>& uPtr, CatStatement* expression)
{
if (uPtr.get() != static_cast<CatTypedExpression*>(expression))
{
uPtr.reset(static_cast<CatTypedExpression*>(expression));
}
}
void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatAssignableExpression>& uPtr, CatStatement* expression)
{
if (uPtr.get() != static_cast<CatAssignableExpression*>(expression))
{
uPtr.reset(static_cast<CatAssignableExpression*>(expression));
}
}
void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatIdentifier>& uPtr, CatStatement* expression)
{
if (uPtr.get() != static_cast<CatIdentifier*>(expression))
{
uPtr.reset(static_cast<CatIdentifier*>(expression));
}
}
bool ASTHelper::doTypeConversion(std::unique_ptr<CatTypedExpression>& uPtr, const CatGenericType& targetType)
{
CatGenericType sourceType = uPtr->getType();
//Currently, only basic type conversions are supported.
if ((sourceType.isBasicType() || sourceType.isStringType())
&& (targetType.isBasicType() || targetType.isStringType())
&& sourceType != targetType)
{
CatTypedExpression* sourceExpression = uPtr.release();
CatArgumentList* arguments = new CatArgumentList(sourceExpression->getLexeme(), std::vector<CatTypedExpression*>({sourceExpression}));
const char* functionName = nullptr;
if (targetType.isIntType()) functionName = "toInt";
else if (targetType.isDoubleType()) functionName = "toDouble";
else if (targetType.isFloatType()) functionName = "toFloat";
else if (targetType.isBoolType()) functionName = "toBool";
else if (targetType.isStringType()) functionName = "toString";
assert(functionName != nullptr);
CatBuiltInFunctionCall* functionCall = new CatBuiltInFunctionCall(functionName, sourceExpression->getLexeme(), arguments, sourceExpression->getLexeme());
uPtr.reset(functionCall);
return true;
}
return false;
}
bool ASTHelper::doIndirectionConversion(std::unique_ptr<CatTypedExpression>& uPtr, const CatGenericType& expectedType, bool allowAddressOf, IndirectionConversionMode& conversionMode)
{
conversionMode = expectedType.getIndirectionConversion(uPtr->getType());
if (conversionMode != IndirectionConversionMode::None && isValidConversionMode(conversionMode))
{
if (!isDereferenceConversionMode(conversionMode) && !allowAddressOf)
{
return false;
}
std::unique_ptr<CatTypedExpression> expression(uPtr.release());
uPtr = std::make_unique<CatIndirectionConversion>(expression->getLexeme(), expectedType, conversionMode, std::move(expression));
}
return isValidConversionMode(conversionMode);
}
bool ASTHelper::makeSameLeastIndirection(std::unique_ptr<CatTypedExpression>& expression1, std::unique_ptr<CatTypedExpression>& expression2)
{
int expr1Indirection = 0;
expression1->getType().removeIndirection(expr1Indirection);
int expr2Indirection = 0;
expression2->getType().removeIndirection(expr2Indirection);
//we should conert the argument with the highest level of indirection to the same level of indirection as the other argument.
if (expr1Indirection != expr2Indirection)
{
if (expr1Indirection > expr2Indirection)
{
const CatGenericType* expr1Type = &expression1->getType();
while (expr1Indirection > expr2Indirection)
{
expr1Type = expr1Type->getPointeeType();
expr1Indirection--;
}
IndirectionConversionMode mode;
if (ASTHelper::doIndirectionConversion(expression1, *expr1Type, false, mode))
{
return true;
}
}
else
{
const CatGenericType* expr2Type = &expression2->getType();
while (expr2Indirection > expr1Indirection)
{
expr2Type = expr2Type->getPointeeType();
expr2Indirection--;
}
IndirectionConversionMode mode;
if (ASTHelper::doIndirectionConversion(expression2, *expr2Type, false, mode))
{
return true;
}
}
}
return false;
}
std::any ASTHelper::doAssignment(CatAssignableExpression* target, CatTypedExpression* source, CatRuntimeContext* context)
{
const CatGenericType& targetType = target->getAssignableType();
const CatGenericType* sourceType = &source->getType();
std::any targetValue = target->executeAssignable(context);
std::any sourceValue;
if ((targetType.isPointerToHandleType() || targetType.isPointerToPointerType())
&& ( targetType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Owned
|| targetType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Shared)
&& (sourceType->getOwnershipSemantics() == TypeOwnershipSemantics::Owned))
{
sourceValue = static_cast<CatAssignableExpression*>(source)->executeAssignable(context);
sourceType = &static_cast<CatAssignableExpression*>(source)->getAssignableType();
}
else
{
sourceValue = source->execute(context);
}
return doAssignment(targetValue, sourceValue, targetType, *sourceType);
}
std::any jitcat::AST::ASTHelper::doGetArgument(CatTypedExpression* argument, const CatGenericType& parameterType, CatRuntimeContext* context)
{
if (!parameterType.isPointerToReflectableObjectType()
|| (parameterType.getOwnershipSemantics() != TypeOwnershipSemantics::Owned
&& !(parameterType.getOwnershipSemantics() == TypeOwnershipSemantics::Shared && argument->getType().getOwnershipSemantics() == TypeOwnershipSemantics::Owned))
|| argument->getType().getOwnershipSemantics() == TypeOwnershipSemantics::Value)
{
return argument->execute(context);
}
else
{
assert(argument->isAssignable());
assert(argument->getType().getOwnershipSemantics() == TypeOwnershipSemantics::Owned);
std::any sourceValue = static_cast<CatAssignableExpression*>(argument)->executeAssignable(context);
const CatGenericType& sourceType = static_cast<CatAssignableExpression*>(argument)->getAssignableType();
if (sourceType.isPointerToPointerType() && sourceType.getPointeeType()->getPointeeType()->isReflectableObjectType())
{
unsigned char** reflectableSource = reinterpret_cast<unsigned char**>(sourceType.getRawPointer(sourceValue));
if (reflectableSource != nullptr)
{
unsigned char* value = *reflectableSource;
*reflectableSource = nullptr;
return sourceType.getPointeeType()->createFromRawPointer(reinterpret_cast<uintptr_t>(value));
}
return sourceType.getPointeeType()->createNullPtr();
}
else if (sourceType.isPointerToHandleType())
{
ReflectableHandle* handleSource = std::any_cast<ReflectableHandle*>(sourceValue);
if (handleSource != nullptr)
{
unsigned char* value = reinterpret_cast<unsigned char*>(handleSource->get());
*handleSource = nullptr;
return sourceType.getPointeeType()->createFromRawPointer(reinterpret_cast<uintptr_t>(value));
}
return sourceType.getPointeeType()->createNullPtr();
}
else
{
assert(false);
return sourceType.getPointeeType()->createNullPtr();
}
}
}
std::any ASTHelper::doAssignment(std::any& target, std::any& source, const CatGenericType& targetType, const CatGenericType& sourceType)
{
if (targetType.isPointerType() && targetType.getPointeeType()->isBasicType())
{
std::any convertedSource = targetType.removeIndirection().convertToType(source, sourceType);
if (targetType.getPointeeType()->isIntType())
{
int* intTarget = std::any_cast<int*>(target);
if (intTarget != nullptr)
{
*intTarget = std::any_cast<int>(convertedSource);
}
}
else if (targetType.getPointeeType()->isFloatType())
{
float* floatTarget = std::any_cast<float*>(target);
if (floatTarget != nullptr)
{
*floatTarget = std::any_cast<float>(convertedSource);
}
}
else if (targetType.getPointeeType()->isDoubleType())
{
double* doubleTarget = std::any_cast<double*>(target);
if (doubleTarget != nullptr)
{
*doubleTarget = std::any_cast<double>(convertedSource);
}
}
else if (targetType.getPointeeType()->isBoolType())
{
bool* boolTarget = std::any_cast<bool*>(target);
if (boolTarget != nullptr)
{
*boolTarget = std::any_cast<bool>(convertedSource);
}
}
else if (targetType.isPointerToReflectableObjectType())
{
//Not supported for now. This would need to call operator= on the target object, not all objects will have implemented this.
assert(false);
}
return target;
}
else if (targetType.isStringPtrType() && sourceType.isStringPtrType())
{
*std::any_cast<Configuration::CatString*>(target) = *std::any_cast<Configuration::CatString*>(source);
return target;
}
else if (targetType.isStringPtrType() && sourceType.isStringType())
{
*std::any_cast<Configuration::CatString*>(target) = std::any_cast<Configuration::CatString>(source);
return target;
}
else if (targetType.isPointerToPointerType() && targetType.getPointeeType()->isPointerToReflectableObjectType())
{
unsigned char** reflectableTarget = reinterpret_cast<unsigned char**>(targetType.getRawPointer(target));
if (reflectableTarget != nullptr)
{
TypeOwnershipSemantics targetOwnership = targetType.getPointeeType()->getOwnershipSemantics();
if (targetOwnership == TypeOwnershipSemantics::Owned && *reflectableTarget != nullptr)
{
targetType.getPointeeType()->getPointeeType()->getObjectType()->destruct(*reflectableTarget);
}
if (sourceType.isPointerToReflectableObjectType() || sourceType.isReflectableHandleType())
{
*reflectableTarget = reinterpret_cast<unsigned char*>(sourceType.getRawPointer(source));
}
else if (sourceType.isPointerToHandleType())
{
TypeOwnershipSemantics sourceOwnership = sourceType.getPointeeType()->getOwnershipSemantics();
ReflectableHandle* sourceHandle = std::any_cast<ReflectableHandle*>(source);
if (sourceHandle != nullptr)
{
*reflectableTarget = reinterpret_cast<unsigned char*>(sourceHandle->get());
if ((targetOwnership == TypeOwnershipSemantics::Owned
|| targetOwnership == TypeOwnershipSemantics::Shared)
&& sourceOwnership == TypeOwnershipSemantics::Owned)
{
*sourceHandle = nullptr;
}
}
else
{
*reflectableTarget = nullptr;
}
}
else if (sourceType.isPointerToPointerType() && sourceType.getPointeeType()->isPointerToReflectableObjectType())
{
TypeOwnershipSemantics sourceOwnership = sourceType.getPointeeType()->getOwnershipSemantics();
unsigned char** sourcePointer = reinterpret_cast<unsigned char**>(sourceType.getRawPointer(source));
if (sourcePointer != nullptr)
{
*reflectableTarget = *sourcePointer;
if ((targetOwnership == TypeOwnershipSemantics::Owned
|| targetOwnership == TypeOwnershipSemantics::Shared)
&& sourceOwnership == TypeOwnershipSemantics::Owned)
{
*sourcePointer = nullptr;
}
}
else
{
*reflectableTarget = nullptr;
}
}
}
return target;
}
else if (targetType.isPointerToHandleType())
{
ReflectableHandle* handleTarget = std::any_cast<ReflectableHandle*>(target);
if (handleTarget != nullptr)
{
TypeOwnershipSemantics targetOwnership = targetType.getPointeeType()->getOwnershipSemantics();
if (targetOwnership == TypeOwnershipSemantics::Owned && handleTarget->getIsValid())
{
targetType.getPointeeType()->getPointeeType()->getObjectType()->destruct(handleTarget->get());
}
if (sourceType.isPointerToReflectableObjectType()
|| sourceType.isReflectableHandleType())
{
handleTarget->setReflectable(reinterpret_cast<unsigned char*>(sourceType.getRawPointer(source)), sourceType.removeIndirection().getObjectType());
}
else if (sourceType.isPointerToHandleType())
{
ReflectableHandle* sourceHandle = std::any_cast<ReflectableHandle*>(source);
if (sourceHandle != nullptr)
{
*handleTarget = *sourceHandle;
if ((targetOwnership == TypeOwnershipSemantics::Owned
|| targetOwnership == TypeOwnershipSemantics::Shared)
&& sourceType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Owned)
{
*sourceHandle = nullptr;
}
}
else
{
*handleTarget = nullptr;
}
}
else if (sourceType.isPointerToPointerType() && sourceType.getPointeeType()->isPointerToReflectableObjectType())
{
unsigned char** sourcePointer = reinterpret_cast<unsigned char**>(sourceType.getRawPointer(source));
if (sourcePointer != nullptr)
{
handleTarget->setReflectable(*sourcePointer, sourceType.removeIndirection().getObjectType());
if ((targetOwnership == TypeOwnershipSemantics::Owned
|| targetOwnership == TypeOwnershipSemantics::Shared)
&& sourceType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Owned)
{
*sourcePointer = nullptr;
}
}
else
{
*handleTarget = nullptr;
}
}
}
return target;
}
assert(false);
return std::any();
}
MemberFunctionInfo* ASTHelper::memberFunctionSearch(const std::string& functionName, const std::vector<CatGenericType>& argumentTypes, TypeInfo* type,
ExpressionErrorManager* errorManager, CatRuntimeContext* context, void* errorSource, const Tokenizer::Lexeme& lexeme)
{
SearchFunctionSignature signature(functionName, argumentTypes);
MemberFunctionInfo* functionInfo = type->getMemberFunctionInfo(signature);
if (functionInfo != nullptr)
{
return functionInfo;
}
else if (functionName == "init")
{
//If it is the constructor function, also search for the auto-generated constructor if the user-defined constructor was not found.
signature.setFunctionName("__init");
functionInfo = type->getMemberFunctionInfo(signature);
if (functionInfo != nullptr)
{
return functionInfo;
}
}
else if (functionName == "destroy")
{
//If it is the constructor function, also search for the auto-generated constructor if the user-defined constructor was not found.
signature.setFunctionName("__destroy");
functionInfo = type->getMemberFunctionInfo(signature);
if (functionInfo != nullptr)
{
return functionInfo;
}
}
//The function was not found. Generate a list of all the functions with that name (that do not match the argument types).
std::vector<MemberFunctionInfo*> foundFunctions = type->getMemberFunctionsByName(functionName);
if (foundFunctions.size() == 0 && functionName == "init")
{
foundFunctions = type->getMemberFunctionsByName("__init");
}
else if (foundFunctions.size() == 0 && functionName == "detroy")
{
foundFunctions = type->getMemberFunctionsByName("__destroy");
}
if (foundFunctions.size() == 0)
{
//There exist no functions of that name.
errorManager->compiledWithError(Tools::append("Member function not found: ", functionName, "."), errorSource, context->getContextName(), lexeme);
return nullptr;
}
else
{
MemberFunctionInfo* onlyFunction = nullptr;
if (foundFunctions.size() == 1)
{
onlyFunction = foundFunctions[0];
}
else
{
MemberFunctionInfo* potentialOnlyFunction;
int functionsWithSameNumberOfArguments = 0;
for (auto& iter : foundFunctions)
{
if (iter->getNumParameters() == (int)argumentTypes.size())
{
functionsWithSameNumberOfArguments++;
potentialOnlyFunction = iter;
}
}
if (functionsWithSameNumberOfArguments == 1)
{
onlyFunction = potentialOnlyFunction;
}
else if (functionsWithSameNumberOfArguments > 1)
{
//Print an error with each potential match.
std::ostringstream errorStream;
errorStream << "Invalid argument(s) for function " << functionName << ". There are " << functionsWithSameNumberOfArguments << " potential candidates: \n";
for (auto& iter : foundFunctions)
{
if (iter->getNumParameters() == (int)argumentTypes.size())
{
errorStream << "\t" << iter->getReturnType().toString() << " " << functionName << "(" << ASTHelper::getTypeListString(iter->getArgumentTypes()) << ")\n";
}
}
errorManager->compiledWithError(errorStream.str(), errorSource, context->getContextName(), lexeme);
return nullptr;
}
}
//There is only one function of that name, or only one function with that number of arguments.
//Print errors based on number of arguments and argument types.
if (onlyFunction != nullptr)
{
if (onlyFunction->getNumberOfArguments() != argumentTypes.size())
{
errorManager->compiledWithError(Tools::append("Invalid number of arguments for function: ", functionName, " expected ",
onlyFunction->getNumberOfArguments(), " arguments."),
errorSource, context->getContextName(), lexeme);
return nullptr;
}
else
{
for (unsigned int i = 0; i < argumentTypes.size(); i++)
{
if (!onlyFunction->getArgumentType(i).compare(argumentTypes[i], false, false))
{
errorManager->compiledWithError(Tools::append("Invalid argument for function: ", functionName, " argument nr: ", i,
" expected: ", onlyFunction->getArgumentType(i).toString()),
errorSource, context->getContextName(), lexeme);
return nullptr;
}
else if (!ASTHelper::checkOwnershipSemantics(onlyFunction->getArgumentType(i), argumentTypes[i], errorManager, context, errorSource, lexeme, "pass"))
{
return nullptr;
}
}
}
}
else
{
//There are multiple functions with that name, all with a different number of arguments that the number of arguments supplied.
//Print an error with each potential match.
std::ostringstream errorStream;
errorStream << "Invalid number of arguments for function " << functionName << ". There are " << foundFunctions.size() << " potential candidates: \n";
for (auto& iter : foundFunctions)
{
errorStream << "\t" << iter->getReturnType().toString() << " " << functionName << "(" << ASTHelper::getTypeListString(iter->getArgumentTypes()) << ")\n";
}
errorManager->compiledWithError(errorStream.str(), errorSource, context->getContextName(), lexeme);
return nullptr;
}
}
return nullptr;
}
std::string jitcat::AST::ASTHelper::getTypeListString(const std::vector<CatGenericType>& types)
{
std::ostringstream typeListStream;
for (std::size_t i = 0; i < types.size(); ++i)
{
if (i != 0) typeListStream << ", ";
typeListStream << types[i].toString();
}
return typeListStream.str();
}
bool jitcat::AST::ASTHelper::checkAssignment(const CatTypedExpression* lhs, const CatTypedExpression* rhs, ExpressionErrorManager* errorManager, CatRuntimeContext* context, void* errorSource, const Tokenizer::Lexeme& lexeme)
{
CatGenericType leftType = lhs->getType();
CatGenericType rightType = rhs->getType();
if ((!leftType.isWritable())
|| leftType.isConst()
|| !lhs->isAssignable())
{
errorManager->compiledWithError("Assignment failed because target cannot be assigned.", errorSource, context->getContextName(), lexeme);
return false;
}
else
{
if (leftType.compare(rightType, false, false))
{
if (!checkOwnershipSemantics(leftType, rightType, errorManager, context, errorSource, lexeme, "assign"))
{
return false;
}
return true;
}
else
{
errorManager->compiledWithError(Tools::append("Cannot assign ", rightType.toString(), " to ", leftType.toString(), "."), errorSource, context->getContextName(), lexeme);
return false;
}
}
}
bool jitcat::AST::ASTHelper::checkOwnershipSemantics(const CatGenericType& targetType, const CatGenericType& sourceType, ExpressionErrorManager* errorManager, CatRuntimeContext* context, void* errorSource, const Tokenizer::Lexeme& lexeme, const std::string& operation)
{
TypeOwnershipSemantics leftOwnership = targetType.getOwnershipSemantics();
TypeOwnershipSemantics rightOwnership = sourceType.getOwnershipSemantics();
if (leftOwnership == TypeOwnershipSemantics::Owned)
{
if (rightOwnership == TypeOwnershipSemantics::Shared)
{
errorManager->compiledWithError(Tools::append("Cannot ", operation, " shared ownership value to unique ownership value."), errorSource, context->getContextName(), lexeme);
return false;
}
else if (rightOwnership == TypeOwnershipSemantics::Weak)
{
errorManager->compiledWithError(Tools::append("Cannot ", operation, " weakly-owned value to unique ownership value."), errorSource, context->getContextName(), lexeme);
return false;
}
}
else if (leftOwnership == TypeOwnershipSemantics::Shared)
{
if (rightOwnership == TypeOwnershipSemantics::Weak)
{
errorManager->compiledWithError(Tools::append("Cannot ", operation, " weakly-owned value to shared ownership value."), errorSource, context->getContextName(), lexeme);
return false;
}
}
/*else if (leftOwnership == TypeOwnershipSemantics::Weak)
{
if (rightOwnership == TypeOwnershipSemantics::Value && !sourceType.isNullptrType())
{
errorManager->compiledWithError(Tools::append("Cannot ", operation, " owned temporary value to weak ownership value."), errorSource, context->getContextName(), lexeme);
return false;
}
}*/
if (rightOwnership == TypeOwnershipSemantics::Owned
&& (leftOwnership == TypeOwnershipSemantics::Owned
|| leftOwnership == TypeOwnershipSemantics::Shared))
{
if (!sourceType.isWritable() || sourceType.isConst())
{
errorManager->compiledWithError("Cannot write from owned value because rhs cannot be assigned.", errorSource, context->getContextName(), lexeme);
return false;
}
}
return true;
}
| 36.302589 | 268 | 0.727925 | mvhooren |
de03ff19c26b6bfe1f4b0974b048e5b9412c4953 | 9,211 | cpp | C++ | src/syntax/lambda_man.cpp | tomoki/Shiranui | 0c02933d718ecf5c446ca00c0ede17fd1897f58d | [
"BSD-3-Clause"
] | 12 | 2015-01-10T15:21:09.000Z | 2021-04-09T02:53:23.000Z | src/syntax/lambda_man.cpp | tomoki/Shiranui | 0c02933d718ecf5c446ca00c0ede17fd1897f58d | [
"BSD-3-Clause"
] | 3 | 2015-01-01T04:26:07.000Z | 2015-08-20T12:51:39.000Z | src/syntax/lambda_man.cpp | tomoki/Shiranui | 0c02933d718ecf5c446ca00c0ede17fd1897f58d | [
"BSD-3-Clause"
] | 1 | 2020-05-20T08:25:43.000Z | 2020-05-20T08:25:43.000Z | #include "lambda_man.hpp"
namespace shiranui{
namespace syntax{
void LambdaMarkerScanner::visit(ast::Identifier&){}
void LambdaMarkerScanner::visit(ast::Variable&){}
void LambdaMarkerScanner::visit(ast::Number&){}
void LambdaMarkerScanner::visit(ast::String&){}
void LambdaMarkerScanner::visit(ast::Boolean&){}
void LambdaMarkerScanner::visit(ast::Enum& node){
for(auto e : node.expressions){
e->accept(*this);
}
}
void LambdaMarkerScanner::visit(ast::Interval& node){
if(node.start != nullptr){
node.start->accept(*this);
}
if(node.end != nullptr){
node.end->accept(*this);
}
if(node.next != nullptr){
node.next->accept(*this);
}
}
void LambdaMarkerScanner::visit(ast::Block& node){
for(auto s : node.statements){
s->accept(*this);
}
for(auto s : node.flymarks){
s->accept(*this);
}
}
void LambdaMarkerScanner::visit(ast::Function& node){
// FIXME: copy is safe,BUT should not.(runtime_infomation is not shared)
auto copy = std::make_shared<ast::Function>(node);
where_are_you_from[node.body] = copy;
if(node.lambda_id.name != ""){
marker_to_lambda[node.lambda_id] = copy;
}
node.body->accept(*this);
}
void LambdaMarkerScanner::visit(ast::FunctionCall& node){
node.function->accept(*this);
for(auto a : node.arguments){
a->accept(*this);
}
}
void LambdaMarkerScanner::visit(ast::BinaryOperator& node){
node.left->accept(*this);
node.right->accept(*this);
}
void LambdaMarkerScanner::visit(ast::UnaryOperator& node){
node.exp->accept(*this);
}
void LambdaMarkerScanner::visit(ast::IfElseExpression& node){
node.pred->accept(*this);
node.ife->accept(*this);
node.elsee->accept(*this);
}
void LambdaMarkerScanner::visit(ast::Definement& node){
node.value->accept(*this);
}
void LambdaMarkerScanner::visit(ast::ExpressionStatement& node){
node.exp->accept(*this);
}
void LambdaMarkerScanner::visit(ast::ReturnStatement& node){
node.value->accept(*this);
}
void LambdaMarkerScanner::visit(ast::ProbeStatement& node){
node.value->accept(*this);
}
void LambdaMarkerScanner::visit(ast::AssertStatement& node){
node.value->accept(*this);
}
void LambdaMarkerScanner::visit(ast::IfElseStatement& node){
node.pred->accept(*this);
node.ifblock->accept(*this);
node.elseblock->accept(*this);
}
// should return forstatement?
void LambdaMarkerScanner::visit(ast::ForStatement& node){
node.loop_exp->accept(*this);
node.block->accept(*this);
}
void LambdaMarkerScanner::visit(ast::Assignment& node){
node.value->accept(*this);
}
void LambdaMarkerScanner::visit(ast::TestFlyLine& node){
// node.left->accept(*this);
}
void LambdaMarkerScanner::visit(ast::IdleFlyLine& node){
// node.left->accept(*this);
}
void LambdaMarkerScanner::visit(ast::FlyMark&){}
void LambdaMarkerScanner::visit(ast::SourceCode& node){
for(auto s : node.statements){
s->accept(*this);
}
// for(auto p : node.flylines){
// p->accept(*this);
// }
}
void LambdaMarkerScanner::visit(ast::DSL::DataDSL&){}
std::pair<
std::map<sp<ast::Block>,sp<ast::Function> >,
std::map<ast::Identifier,sp<ast::Function> >
>
scan_lambda_marker(ast::SourceCode& source){
LambdaMarkerScanner h;
h.visit(source);
return std::make_pair(h.where_are_you_from,
h.marker_to_lambda);
}
// ---------------------------------------------------------------------
LambdaFreeVariableScanner::LambdaFreeVariableScanner(){}
void LambdaFreeVariableScanner::visit(ast::Identifier&){}
void LambdaFreeVariableScanner::visit(ast::Variable& v){
if(is_free(v.value)){
free.insert(v.value);
}else{
}
}
void LambdaFreeVariableScanner::visit(ast::Number&){}
void LambdaFreeVariableScanner::visit(ast::String&){}
void LambdaFreeVariableScanner::visit(ast::Boolean&){}
void LambdaFreeVariableScanner::visit(ast::Enum& node){
for(auto e : node.expressions){
e->accept(*this);
}
}
void LambdaFreeVariableScanner::visit(ast::Interval& node){
if(node.start != nullptr){
node.start->accept(*this);
}
if(node.end != nullptr){
node.end->accept(*this);
}
if(node.next != nullptr){
node.next->accept(*this);
}
}
void LambdaFreeVariableScanner::visit(ast::Block& node){
bound.emplace();
for(auto s : node.statements){
s->accept(*this);
}
for(auto s : node.flymarks){
s->accept(*this);
}
bound.pop();
}
void LambdaFreeVariableScanner::visit(ast::Function& node){
bound.emplace();
for(auto i : node.parameters){
bound.top().insert(i);
}
node.body->accept(*this);
bound.pop();
}
void LambdaFreeVariableScanner::visit(ast::FunctionCall& node){
node.function->accept(*this);
for(auto a : node.arguments){
a->accept(*this);
}
}
void LambdaFreeVariableScanner::visit(ast::BinaryOperator& node){
node.left->accept(*this);
node.right->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::UnaryOperator& node){
node.exp->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::IfElseExpression& node){
node.pred->accept(*this);
node.ife->accept(*this);
node.elsee->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::Definement& node){
// for recursive function, add here.
bound.top().insert(node.id);
node.value->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::ExpressionStatement& node){
node.exp->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::ReturnStatement& node){
node.value->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::ProbeStatement& node){
node.value->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::AssertStatement& node){
node.value->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::IfElseStatement& node){
node.pred->accept(*this);
node.ifblock->accept(*this);
node.elseblock->accept(*this);
}
// should return forstatement?
void LambdaFreeVariableScanner::visit(ast::ForStatement& node){
node.loop_exp->accept(*this);
node.block->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::Assignment& node){
if(is_free(node.id)){
free.insert(node.id);
}else{
}
node.value->accept(*this);
}
void LambdaFreeVariableScanner::visit(ast::TestFlyLine&){}
void LambdaFreeVariableScanner::visit(ast::IdleFlyLine&){}
void LambdaFreeVariableScanner::visit(ast::FlyMark&){}
void LambdaFreeVariableScanner::visit(ast::SourceCode& node){
for(auto s : node.statements){
s->accept(*this);
}
for(auto p : node.flylines){
p->accept(*this);
}
}
void LambdaFreeVariableScanner::visit(ast::DSL::DataDSL&){}
bool LambdaFreeVariableScanner::is_free(ast::Identifier i){
auto copy = bound;
while(not copy.empty()){
auto t = copy.top();
if(t.find(i) != t.end()){
return false;
}
copy.pop();
}
return true;
}
std::set<ast::Identifier> scan_free_variable(ast::Function& f){
LambdaFreeVariableScanner sc;
f.accept(sc);
return sc.free;
}
std::set<ast::Identifier> scan_free_variable(sp<ast::Function> fp){
return scan_free_variable(*fp);
}
}
}
| 36.551587 | 84 | 0.525676 | tomoki |
90024ead7d13719eb9fa2cbabebb488ad8227d5c | 7,057 | hpp | C++ | include/multigraph/functors.hpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | null | null | null | include/multigraph/functors.hpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | null | null | null | include/multigraph/functors.hpp | YuanL12/BATS | 35a32facc87e17649b7fc32225c8ffaf0301bbfa | [
"MIT"
] | null | null | null | #pragma once
/*
Functors from one type of diagram to another
*/
#include "diagram.hpp"
#include <topology/data.hpp>
#include <topology/cover.hpp>
#include <topology/rips.hpp>
#include <topology/nerve.hpp>
#include <complex/simplicial_complex.hpp>
#include <complex/simplicial_map.hpp>
#include <chain/chain_complex.hpp>
#include <chain/chain_map.hpp>
#include <homology/basis.hpp>
#include <homology/induced_map.hpp>
#include <dgvs/dgvs.hpp>
#include <dgvs/dgmap.hpp>
#include <homology/dgbasis.hpp>
#include <stdexcept>
namespace bats {
Diagram<SimplicialComplex, CellularMap> Nerve(
const Diagram<bats::Cover, std::vector<size_t>> &D,
const size_t dmax // maximum simplex dimension
) {
size_t n = D.nnode();
size_t m = D.nedge();
// Diagram of simplicial complexes and maps
Diagram<SimplicialComplex, CellularMap> TD(n, m);
// apply functor to nodes
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
TD.set_node(i, Nerve(D.node[i], dmax));
}
// apply functor to edges
#pragma omp parallel for
for (size_t i = 0; i < m; i++) {
auto s = D.elist[i].src;
auto t = D.elist[i].targ;
TD.set_edge(i, s, t,
SimplicialMap(TD.node[s] , TD.node[t], D.edata[i])
);
}
return TD;
}
// Create diagram of Rips complexes from subsets
template <typename T, typename M>
Diagram<SimplicialComplex, CellularMap> Rips(
const Diagram<std::set<size_t>, std::vector<size_t>> &D,
const DataSet<T> &X,
const M &dist, // distance
const T rmax, // maximum radius
const size_t dmax // maximum simplex dimension
) {
size_t n = D.nnode();
size_t m = D.nedge();
// Diagram of simplicial complexes and maps
Diagram<SimplicialComplex, CellularMap> TD(n, m);
// apply functor to nodes
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
auto XI = get_subset(X, D.node[i]);
TD.set_node(i, RipsComplex<SimplicialComplex>(XI, dist, rmax, dmax));
}
// apply functor to edges
#pragma omp parallel for
for (size_t i = 0; i < m; i++) {
auto s = D.elist[i].src;
auto t = D.elist[i].targ;
TD.set_edge(i, s, t,
SimplicialMap(TD.node[s] , TD.node[t], D.edata[i])
);
}
return TD;
}
// Create diagram of Rips complexes from subsets
// uses a different rips parameter for each node
template <typename T, typename M>
Diagram<SimplicialComplex, CellularMap> Rips(
const Diagram<std::set<size_t>, std::vector<size_t>> &D,
const DataSet<T> &X,
const M &dist, // distance
const std::vector<T> &rmax, // maximum radius for each node
const size_t dmax // maximum simplex dimension
) {
size_t n = D.nnode();
size_t m = D.nedge();
// Diagram of simplicial complexes and maps
Diagram<SimplicialComplex, CellularMap> TD(n, m);
// apply functor to nodes
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
auto XI = get_subset(X, D.node[i]);
TD.set_node(i, RipsComplex<SimplicialComplex>(XI, dist, rmax[i], dmax));
}
// apply functor to edges
#pragma omp parallel for
for (size_t i = 0; i < m; i++) {
auto s = D.elist[i].src;
auto t = D.elist[i].targ;
if (rmax[t] < rmax[s]) {
throw std::range_error("Rips parameter must be non-decreasing from source to target.");
}
TD.set_edge(i, s, t,
SimplicialMap(TD.node[s] , TD.node[t], D.edata[i])
);
}
return TD;
}
// ChainComplex functor
// template over matrix type, diagram type
template <typename TM, typename DT>
Diagram<ChainComplex<TM>, ChainMap<TM>> ChainFunctor(const DT &D) {
size_t n = D.nnode();
size_t m = D.nedge();
// Diagram of chain complexes and chain maps
Diagram<ChainComplex<TM>, ChainMap<TM>> CD(n, m);
// apply chain functor to nodes
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
CD.set_node(i, ChainComplex<TM>(D.node[i]));
}
// apply chain functor to edges
#pragma omp parallel for
for (size_t j = 0; j < m; j++) {
auto s = D.elist[j].src;
auto t = D.elist[j].targ;
CD.set_edge(j, s, t, ChainMap<TM>(D.edata[j]));
}
return CD;
}
template <typename TF, typename DT>
inline auto ChainFunctor(const DT &D, TF) {
using TM = ColumnMatrix<SparseVector<TF>>;
return ChainFunctor<TM>(D);
}
// easy chain functor
template <typename DT, typename T>
inline auto __ChainFunctor(const DT &D, T) {
using VT = SparseVector<T, size_t>;
using MT = ColumnMatrix<VT>;
return ChainFunctor<MT, DT>(D);
}
template <typename CpxT, typename T>
inline auto Chain(const Diagram<CpxT, CellularMap>& D, T) {
using VT = SparseVector<T, size_t>;
using MT = ColumnMatrix<VT>;
return ChainFunctor<MT, Diagram<CpxT, CellularMap>>(D);
}
// Homology functor for dimension k
// template over matrix type
template <typename TM>
Diagram<ReducedChainComplex<TM>, TM> Hom(
const Diagram<ChainComplex<TM>, ChainMap<TM>> &D,
size_t k
) {
size_t n = D.nnode();
size_t m = D.nedge();
// Diagram of chain complexes and chain maps
Diagram<ReducedChainComplex<TM>, TM> HD(n, m);
// apply hom functor to nodes
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
HD.set_node(i, ReducedChainComplex<TM>(D.node[i]));
}
// apply hom functor to edges
#pragma omp parallel for
for (size_t j = 0; j < m; j++) {
auto s = D.elist[j].src;
auto t = D.elist[j].targ;
HD.set_edge(j, s, t,
induced_map(D.edata[j], HD.node[s], HD.node[t], k)
);
}
return HD;
}
/**
Functor from topological category to category of
differential graded vector spaces
Chain functor is degree = -1 (default)
Cochain functor is degree = +1. This is contravariant (reverses arrows)
*/
template <typename TM, typename DT>
Diagram<DGVectorSpace<TM>, DGLinearMap<TM>> DGLinearFunctor(
const DT &D,
int degree=-1
) {
size_t n = D.nnode();
size_t m = D.nedge();
// Diagram of chain complexes and chain maps
Diagram<DGVectorSpace<TM>, DGLinearMap<TM>> DGD(n, m);
// apply chain functor to nodes
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
DGD.set_node(i, DGVectorSpace<TM>(D.node[i], degree));
}
// apply chain functor to edges
#pragma omp parallel for
for (size_t j = 0; j < m; j++) {
auto s = (degree == -1) ? D.elist[j].src : D.elist[j].targ;
auto t = (degree == -1) ? D.elist[j].targ : D.elist[j].src;
DGD.set_edge(j, s, t, DGLinearMap<TM>(D.edata[j], degree));
}
return DGD;
}
/**
Homology functor for dimension k
template over matrix type
*/
template <typename TM>
Diagram<ReducedDGVectorSpace<TM>, TM> Hom(
const Diagram<DGVectorSpace<TM>, DGLinearMap<TM>> &D,
size_t k
) {
size_t n = D.nnode();
size_t m = D.nedge();
// Diagram of chain complexes and chain maps
Diagram<ReducedDGVectorSpace<TM>, TM> HD(n, m);
// apply hom functor to nodes
#pragma omp parallel for
for (size_t i = 0; i < n; i++) {
HD.set_node(i, ReducedDGVectorSpace<TM>(D.node[i]));
}
// apply hom functor to edges
#pragma omp parallel for
for (size_t j = 0; j < m; j++) {
auto s = D.elist[j].src;
auto t = D.elist[j].targ;
HD.set_edge(j, s, t,
induced_map(D.edata[j], HD.node[s], HD.node[t], k)
);
}
return HD;
}
} // namespace bats
| 24.848592 | 90 | 0.659912 | YuanL12 |
9005b1e0cf6005acbdc988b40daf51ac99f3edd1 | 806 | cpp | C++ | Problema_88/Problema_88.cpp | EneRgYCZ/Problems | e8bf9aa4bba2b5ead25fc5ce482a36c861501f46 | [
"MIT"
] | null | null | null | Problema_88/Problema_88.cpp | EneRgYCZ/Problems | e8bf9aa4bba2b5ead25fc5ce482a36c861501f46 | [
"MIT"
] | null | null | null | Problema_88/Problema_88.cpp | EneRgYCZ/Problems | e8bf9aa4bba2b5ead25fc5ce482a36c861501f46 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
ifstream fin("palindrom.in");
ofstream fout("palindrom.out");
int main()
{
int index = 0, ok = 0;
char s[256];
fin>>index;
for (int i = index; i > 0; i--)
{
fin.getline(s, 256);
int inceput = 0, sfarsit = strlen(s) - 1;
for (int j = 0; j <= strlen(s) / 2; j++)
{
if (s[inceput] == s[sfarsit])
{
ok = 1;
inceput++;
sfarsit--;
}
else
{
ok = 0;
break;
}
}
if (ok == 1)
{
fout << 1 << endl;
}
else
{
fout << 0 << endl;
}
ok = 0;
}
}
| 19.190476 | 49 | 0.361042 | EneRgYCZ |
900a8fe26480116bd977fd5facd23c1bdc3b2dbc | 28,661 | cpp | C++ | third_party/externals/angle2/src/libANGLE/renderer/vulkan/renderervk_utils.cpp | pepstack/skia-build-msvc | 73e50bc303f66f494f0b53f4747c2cfabe227917 | [
"BSD-3-Clause"
] | 4 | 2019-10-18T05:53:30.000Z | 2021-08-21T07:36:37.000Z | third_party/externals/angle2/src/libANGLE/renderer/vulkan/renderervk_utils.cpp | kniefliu/skia | f7d3ea6d9ec7a3d8ef17456cc23da7291737c680 | [
"BSD-3-Clause"
] | null | null | null | third_party/externals/angle2/src/libANGLE/renderer/vulkan/renderervk_utils.cpp | kniefliu/skia | f7d3ea6d9ec7a3d8ef17456cc23da7291737c680 | [
"BSD-3-Clause"
] | 4 | 2018-10-14T00:17:11.000Z | 2020-07-01T04:01:25.000Z | //
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// renderervk_utils:
// Helper functions for the Vulkan Renderer.
//
#include "renderervk_utils.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
namespace rx
{
namespace
{
GLenum DefaultGLErrorCode(VkResult result)
{
switch (result)
{
case VK_ERROR_OUT_OF_HOST_MEMORY:
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
case VK_ERROR_TOO_MANY_OBJECTS:
return GL_OUT_OF_MEMORY;
default:
return GL_INVALID_OPERATION;
}
}
EGLint DefaultEGLErrorCode(VkResult result)
{
switch (result)
{
case VK_ERROR_OUT_OF_HOST_MEMORY:
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
case VK_ERROR_TOO_MANY_OBJECTS:
return EGL_BAD_ALLOC;
case VK_ERROR_INITIALIZATION_FAILED:
return EGL_NOT_INITIALIZED;
case VK_ERROR_SURFACE_LOST_KHR:
case VK_ERROR_DEVICE_LOST:
return EGL_CONTEXT_LOST;
default:
return EGL_BAD_ACCESS;
}
}
// Gets access flags that are common between source and dest layouts.
VkAccessFlags GetBasicLayoutAccessFlags(VkImageLayout layout)
{
switch (layout)
{
case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL:
return VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL:
return VK_ACCESS_TRANSFER_WRITE_BIT;
case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR:
return VK_ACCESS_MEMORY_READ_BIT;
case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL:
return VK_ACCESS_TRANSFER_READ_BIT;
case VK_IMAGE_LAYOUT_UNDEFINED:
case VK_IMAGE_LAYOUT_GENERAL:
return 0;
default:
// TODO(jmadill): Investigate other flags.
UNREACHABLE();
return 0;
}
}
} // anonymous namespace
// Mirrors std_validation_str in loader.h
// TODO(jmadill): Possibly wrap the loader into a safe source file. Can't be included trivially.
const char *g_VkStdValidationLayerName = "VK_LAYER_LUNARG_standard_validation";
const char *VulkanResultString(VkResult result)
{
switch (result)
{
case VK_SUCCESS:
return "Command successfully completed.";
case VK_NOT_READY:
return "A fence or query has not yet completed.";
case VK_TIMEOUT:
return "A wait operation has not completed in the specified time.";
case VK_EVENT_SET:
return "An event is signaled.";
case VK_EVENT_RESET:
return "An event is unsignaled.";
case VK_INCOMPLETE:
return "A return array was too small for the result.";
case VK_SUBOPTIMAL_KHR:
return "A swapchain no longer matches the surface properties exactly, but can still be "
"used to present to the surface successfully.";
case VK_ERROR_OUT_OF_HOST_MEMORY:
return "A host memory allocation has failed.";
case VK_ERROR_OUT_OF_DEVICE_MEMORY:
return "A device memory allocation has failed.";
case VK_ERROR_INITIALIZATION_FAILED:
return "Initialization of an object could not be completed for implementation-specific "
"reasons.";
case VK_ERROR_DEVICE_LOST:
return "The logical or physical device has been lost.";
case VK_ERROR_MEMORY_MAP_FAILED:
return "Mapping of a memory object has failed.";
case VK_ERROR_LAYER_NOT_PRESENT:
return "A requested layer is not present or could not be loaded.";
case VK_ERROR_EXTENSION_NOT_PRESENT:
return "A requested extension is not supported.";
case VK_ERROR_FEATURE_NOT_PRESENT:
return "A requested feature is not supported.";
case VK_ERROR_INCOMPATIBLE_DRIVER:
return "The requested version of Vulkan is not supported by the driver or is otherwise "
"incompatible for implementation-specific reasons.";
case VK_ERROR_TOO_MANY_OBJECTS:
return "Too many objects of the type have already been created.";
case VK_ERROR_FORMAT_NOT_SUPPORTED:
return "A requested format is not supported on this device.";
case VK_ERROR_SURFACE_LOST_KHR:
return "A surface is no longer available.";
case VK_ERROR_NATIVE_WINDOW_IN_USE_KHR:
return "The requested window is already connected to a VkSurfaceKHR, or to some other "
"non-Vulkan API.";
case VK_ERROR_OUT_OF_DATE_KHR:
return "A surface has changed in such a way that it is no longer compatible with the "
"swapchain.";
case VK_ERROR_INCOMPATIBLE_DISPLAY_KHR:
return "The display used by a swapchain does not use the same presentable image "
"layout, or is incompatible in a way that prevents sharing an image.";
case VK_ERROR_VALIDATION_FAILED_EXT:
return "The validation layers detected invalid API usage.";
default:
return "Unknown vulkan error code.";
}
}
bool HasStandardValidationLayer(const std::vector<VkLayerProperties> &layerProps)
{
for (const auto &layerProp : layerProps)
{
if (std::string(layerProp.layerName) == g_VkStdValidationLayerName)
{
return true;
}
}
return false;
}
namespace vk
{
Error::Error(VkResult result) : mResult(result), mFile(nullptr), mLine(0)
{
ASSERT(result == VK_SUCCESS);
}
Error::Error(VkResult result, const char *file, unsigned int line)
: mResult(result), mFile(file), mLine(line)
{
}
Error::~Error()
{
}
Error::Error(const Error &other) = default;
Error &Error::operator=(const Error &other) = default;
gl::Error Error::toGL(GLenum glErrorCode) const
{
if (!isError())
{
return gl::NoError();
}
// TODO(jmadill): Set extended error code to 'vulkan internal error'.
return gl::Error(glErrorCode, glErrorCode, toString());
}
egl::Error Error::toEGL(EGLint eglErrorCode) const
{
if (!isError())
{
return egl::NoError();
}
// TODO(jmadill): Set extended error code to 'vulkan internal error'.
return egl::Error(eglErrorCode, eglErrorCode, toString());
}
std::string Error::toString() const
{
std::stringstream errorStream;
errorStream << "Internal Vulkan error: " << VulkanResultString(mResult) << ", in " << mFile
<< ", line " << mLine << ".";
return errorStream.str();
}
Error::operator gl::Error() const
{
return toGL(DefaultGLErrorCode(mResult));
}
Error::operator egl::Error() const
{
return toEGL(DefaultEGLErrorCode(mResult));
}
bool Error::isError() const
{
return (mResult != VK_SUCCESS);
}
// CommandPool implementation.
CommandPool::CommandPool()
{
}
void CommandPool::destroy(VkDevice device)
{
if (valid())
{
vkDestroyCommandPool(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error CommandPool::init(VkDevice device, const VkCommandPoolCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreateCommandPool(device, &createInfo, nullptr, &mHandle));
return NoError();
}
// CommandBuffer implementation.
CommandBuffer::CommandBuffer() : mStarted(false), mCommandPool(nullptr)
{
}
void CommandBuffer::setCommandPool(CommandPool *commandPool)
{
ASSERT(!mCommandPool && commandPool->valid());
mCommandPool = commandPool;
}
Error CommandBuffer::begin(VkDevice device)
{
if (mStarted)
{
return NoError();
}
if (mHandle == VK_NULL_HANDLE)
{
VkCommandBufferAllocateInfo commandBufferInfo;
commandBufferInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
commandBufferInfo.pNext = nullptr;
commandBufferInfo.commandPool = mCommandPool->getHandle();
commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
commandBufferInfo.commandBufferCount = 1;
ANGLE_VK_TRY(vkAllocateCommandBuffers(device, &commandBufferInfo, &mHandle));
}
else
{
reset();
}
mStarted = true;
VkCommandBufferBeginInfo beginInfo;
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.pNext = nullptr;
// TODO(jmadill): Use other flags?
beginInfo.flags = 0;
beginInfo.pInheritanceInfo = nullptr;
ANGLE_VK_TRY(vkBeginCommandBuffer(mHandle, &beginInfo));
return NoError();
}
Error CommandBuffer::end()
{
mStarted = false;
ASSERT(valid());
ANGLE_VK_TRY(vkEndCommandBuffer(mHandle));
return NoError();
}
Error CommandBuffer::reset()
{
mStarted = false;
ASSERT(valid());
ANGLE_VK_TRY(vkResetCommandBuffer(mHandle, 0));
return NoError();
}
void CommandBuffer::singleImageBarrier(VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
VkDependencyFlags dependencyFlags,
const VkImageMemoryBarrier &imageMemoryBarrier)
{
ASSERT(valid());
vkCmdPipelineBarrier(mHandle, srcStageMask, dstStageMask, dependencyFlags, 0, nullptr, 0,
nullptr, 1, &imageMemoryBarrier);
}
void CommandBuffer::destroy(VkDevice device)
{
if (valid())
{
ASSERT(mCommandPool && mCommandPool->valid());
vkFreeCommandBuffers(device, mCommandPool->getHandle(), 1, &mHandle);
mHandle = VK_NULL_HANDLE;
}
}
void CommandBuffer::clearSingleColorImage(const vk::Image &image, const VkClearColorValue &color)
{
ASSERT(valid());
ASSERT(image.getCurrentLayout() == VK_IMAGE_LAYOUT_GENERAL ||
image.getCurrentLayout() == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
VkImageSubresourceRange range;
range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
range.baseMipLevel = 0;
range.levelCount = 1;
range.baseArrayLayer = 0;
range.layerCount = 1;
vkCmdClearColorImage(mHandle, image.getHandle(), image.getCurrentLayout(), &color, 1, &range);
}
void CommandBuffer::copySingleImage(const vk::Image &srcImage,
const vk::Image &destImage,
const gl::Box ©Region,
VkImageAspectFlags aspectMask)
{
ASSERT(valid());
ASSERT(srcImage.getCurrentLayout() == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL ||
srcImage.getCurrentLayout() == VK_IMAGE_LAYOUT_GENERAL);
ASSERT(destImage.getCurrentLayout() == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL ||
destImage.getCurrentLayout() == VK_IMAGE_LAYOUT_GENERAL);
VkImageCopy region;
region.srcSubresource.aspectMask = aspectMask;
region.srcSubresource.mipLevel = 0;
region.srcSubresource.baseArrayLayer = 0;
region.srcSubresource.layerCount = 1;
region.srcOffset.x = copyRegion.x;
region.srcOffset.y = copyRegion.y;
region.srcOffset.z = copyRegion.z;
region.dstSubresource.aspectMask = aspectMask;
region.dstSubresource.mipLevel = 0;
region.dstSubresource.baseArrayLayer = 0;
region.dstSubresource.layerCount = 1;
region.dstOffset.x = copyRegion.x;
region.dstOffset.y = copyRegion.y;
region.dstOffset.z = copyRegion.z;
region.extent.width = copyRegion.width;
region.extent.height = copyRegion.height;
region.extent.depth = copyRegion.depth;
vkCmdCopyImage(mHandle, srcImage.getHandle(), srcImage.getCurrentLayout(),
destImage.getHandle(), destImage.getCurrentLayout(), 1, ®ion);
}
void CommandBuffer::beginRenderPass(const RenderPass &renderPass,
const Framebuffer &framebuffer,
const gl::Rectangle &renderArea,
const std::vector<VkClearValue> &clearValues)
{
ASSERT(!clearValues.empty());
ASSERT(mHandle != VK_NULL_HANDLE);
VkRenderPassBeginInfo beginInfo;
beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
beginInfo.pNext = nullptr;
beginInfo.renderPass = renderPass.getHandle();
beginInfo.framebuffer = framebuffer.getHandle();
beginInfo.renderArea.offset.x = static_cast<uint32_t>(renderArea.x);
beginInfo.renderArea.offset.y = static_cast<uint32_t>(renderArea.y);
beginInfo.renderArea.extent.width = static_cast<uint32_t>(renderArea.width);
beginInfo.renderArea.extent.height = static_cast<uint32_t>(renderArea.height);
beginInfo.clearValueCount = static_cast<uint32_t>(clearValues.size());
beginInfo.pClearValues = clearValues.data();
vkCmdBeginRenderPass(mHandle, &beginInfo, VK_SUBPASS_CONTENTS_INLINE);
}
void CommandBuffer::endRenderPass()
{
ASSERT(mHandle != VK_NULL_HANDLE);
vkCmdEndRenderPass(mHandle);
}
void CommandBuffer::draw(uint32_t vertexCount,
uint32_t instanceCount,
uint32_t firstVertex,
uint32_t firstInstance)
{
ASSERT(valid());
vkCmdDraw(mHandle, vertexCount, instanceCount, firstVertex, firstInstance);
}
void CommandBuffer::bindPipeline(VkPipelineBindPoint pipelineBindPoint,
const vk::Pipeline &pipeline)
{
ASSERT(valid() && pipeline.valid());
vkCmdBindPipeline(mHandle, pipelineBindPoint, pipeline.getHandle());
}
void CommandBuffer::bindVertexBuffers(uint32_t firstBinding,
const std::vector<VkBuffer> &buffers,
const std::vector<VkDeviceSize> &offsets)
{
ASSERT(valid() && buffers.size() == offsets.size());
vkCmdBindVertexBuffers(mHandle, firstBinding, static_cast<uint32_t>(buffers.size()),
buffers.data(), offsets.data());
}
// Image implementation.
Image::Image() : mCurrentLayout(VK_IMAGE_LAYOUT_UNDEFINED)
{
}
Image::Image(VkImage image) : WrappedObject(image), mCurrentLayout(VK_IMAGE_LAYOUT_UNDEFINED)
{
}
void Image::retain(VkDevice device, Image &&other)
{
WrappedObject::retain(device, std::move(other));
std::swap(mCurrentLayout, other.mCurrentLayout);
}
void Image::reset()
{
mHandle = VK_NULL_HANDLE;
}
void Image::destroy(VkDevice device)
{
if (valid())
{
vkDestroyImage(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error Image::init(VkDevice device, const VkImageCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreateImage(device, &createInfo, nullptr, &mHandle));
return NoError();
}
void Image::changeLayoutTop(VkImageAspectFlags aspectMask,
VkImageLayout newLayout,
CommandBuffer *commandBuffer)
{
if (newLayout == mCurrentLayout)
{
// No-op.
return;
}
changeLayoutWithStages(aspectMask, newLayout, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, commandBuffer);
}
void Image::changeLayoutWithStages(VkImageAspectFlags aspectMask,
VkImageLayout newLayout,
VkPipelineStageFlags srcStageMask,
VkPipelineStageFlags dstStageMask,
CommandBuffer *commandBuffer)
{
VkImageMemoryBarrier imageMemoryBarrier;
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.pNext = nullptr;
imageMemoryBarrier.srcAccessMask = 0;
imageMemoryBarrier.dstAccessMask = 0;
imageMemoryBarrier.oldLayout = mCurrentLayout;
imageMemoryBarrier.newLayout = newLayout;
imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.image = mHandle;
// TODO(jmadill): Is this needed for mipped/layer images?
imageMemoryBarrier.subresourceRange.aspectMask = aspectMask;
imageMemoryBarrier.subresourceRange.baseMipLevel = 0;
imageMemoryBarrier.subresourceRange.levelCount = 1;
imageMemoryBarrier.subresourceRange.baseArrayLayer = 0;
imageMemoryBarrier.subresourceRange.layerCount = 1;
// TODO(jmadill): Test all the permutations of the access flags.
imageMemoryBarrier.srcAccessMask = GetBasicLayoutAccessFlags(mCurrentLayout);
if (mCurrentLayout == VK_IMAGE_LAYOUT_PREINITIALIZED)
{
imageMemoryBarrier.srcAccessMask |= VK_ACCESS_HOST_WRITE_BIT;
}
imageMemoryBarrier.dstAccessMask = GetBasicLayoutAccessFlags(newLayout);
if (newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)
{
imageMemoryBarrier.srcAccessMask |=
(VK_ACCESS_HOST_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT);
imageMemoryBarrier.dstAccessMask |= VK_ACCESS_SHADER_READ_BIT;
}
if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
{
imageMemoryBarrier.dstAccessMask |= VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
}
commandBuffer->singleImageBarrier(srcStageMask, dstStageMask, 0, imageMemoryBarrier);
mCurrentLayout = newLayout;
}
void Image::getMemoryRequirements(VkDevice device, VkMemoryRequirements *requirementsOut) const
{
ASSERT(valid());
vkGetImageMemoryRequirements(device, mHandle, requirementsOut);
}
Error Image::bindMemory(VkDevice device, const vk::DeviceMemory &deviceMemory)
{
ASSERT(valid() && deviceMemory.valid());
ANGLE_VK_TRY(vkBindImageMemory(device, mHandle, deviceMemory.getHandle(), 0));
return NoError();
}
// ImageView implementation.
ImageView::ImageView()
{
}
void ImageView::destroy(VkDevice device)
{
if (valid())
{
vkDestroyImageView(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error ImageView::init(VkDevice device, const VkImageViewCreateInfo &createInfo)
{
ANGLE_VK_TRY(vkCreateImageView(device, &createInfo, nullptr, &mHandle));
return NoError();
}
// Semaphore implementation.
Semaphore::Semaphore()
{
}
void Semaphore::destroy(VkDevice device)
{
if (valid())
{
vkDestroySemaphore(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error Semaphore::init(VkDevice device)
{
ASSERT(!valid());
VkSemaphoreCreateInfo semaphoreInfo;
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
semaphoreInfo.pNext = nullptr;
semaphoreInfo.flags = 0;
ANGLE_VK_TRY(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &mHandle));
return NoError();
}
// Framebuffer implementation.
Framebuffer::Framebuffer()
{
}
void Framebuffer::destroy(VkDevice device)
{
if (valid())
{
vkDestroyFramebuffer(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error Framebuffer::init(VkDevice device, const VkFramebufferCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreateFramebuffer(device, &createInfo, nullptr, &mHandle));
return NoError();
}
// DeviceMemory implementation.
DeviceMemory::DeviceMemory()
{
}
void DeviceMemory::destroy(VkDevice device)
{
if (valid())
{
vkFreeMemory(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error DeviceMemory::allocate(VkDevice device, const VkMemoryAllocateInfo &allocInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkAllocateMemory(device, &allocInfo, nullptr, &mHandle));
return NoError();
}
Error DeviceMemory::map(VkDevice device,
VkDeviceSize offset,
VkDeviceSize size,
VkMemoryMapFlags flags,
uint8_t **mapPointer)
{
ASSERT(valid());
ANGLE_VK_TRY(
vkMapMemory(device, mHandle, offset, size, flags, reinterpret_cast<void **>(mapPointer)));
return NoError();
}
void DeviceMemory::unmap(VkDevice device)
{
ASSERT(valid());
vkUnmapMemory(device, mHandle);
}
// RenderPass implementation.
RenderPass::RenderPass()
{
}
void RenderPass::destroy(VkDevice device)
{
if (valid())
{
vkDestroyRenderPass(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error RenderPass::init(VkDevice device, const VkRenderPassCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreateRenderPass(device, &createInfo, nullptr, &mHandle));
return NoError();
}
// StagingImage implementation.
StagingImage::StagingImage() : mSize(0)
{
}
StagingImage::StagingImage(StagingImage &&other)
: mImage(std::move(other.mImage)),
mDeviceMemory(std::move(other.mDeviceMemory)),
mSize(other.mSize)
{
other.mSize = 0;
}
void StagingImage::destroy(VkDevice device)
{
mImage.destroy(device);
mDeviceMemory.destroy(device);
}
void StagingImage::retain(VkDevice device, StagingImage &&other)
{
mImage.retain(device, std::move(other.mImage));
mDeviceMemory.retain(device, std::move(other.mDeviceMemory));
std::swap(mSize, other.mSize);
}
Error StagingImage::init(VkDevice device,
uint32_t queueFamilyIndex,
uint32_t hostVisibleMemoryIndex,
TextureDimension dimension,
VkFormat format,
const gl::Extents &extent)
{
VkImageCreateInfo createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.imageType = VK_IMAGE_TYPE_2D;
createInfo.format = format;
createInfo.extent.width = static_cast<uint32_t>(extent.width);
createInfo.extent.height = static_cast<uint32_t>(extent.height);
createInfo.extent.depth = static_cast<uint32_t>(extent.depth);
createInfo.mipLevels = 1;
createInfo.arrayLayers = 1;
createInfo.samples = VK_SAMPLE_COUNT_1_BIT;
createInfo.tiling = VK_IMAGE_TILING_LINEAR;
createInfo.usage = (VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
createInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
createInfo.queueFamilyIndexCount = 1;
createInfo.pQueueFamilyIndices = &queueFamilyIndex;
createInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
ANGLE_TRY(mImage.init(device, createInfo));
VkMemoryRequirements memoryRequirements;
mImage.getMemoryRequirements(device, &memoryRequirements);
// Ensure we can read this memory.
ANGLE_VK_CHECK((memoryRequirements.memoryTypeBits & (1 << hostVisibleMemoryIndex)) != 0,
VK_ERROR_VALIDATION_FAILED_EXT);
VkMemoryAllocateInfo allocateInfo;
allocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocateInfo.pNext = nullptr;
allocateInfo.allocationSize = memoryRequirements.size;
allocateInfo.memoryTypeIndex = hostVisibleMemoryIndex;
ANGLE_TRY(mDeviceMemory.allocate(device, allocateInfo));
ANGLE_TRY(mImage.bindMemory(device, mDeviceMemory));
mSize = memoryRequirements.size;
return NoError();
}
// Buffer implementation.
Buffer::Buffer()
{
}
void Buffer::destroy(VkDevice device)
{
if (valid())
{
mMemory.destroy(device);
vkDestroyBuffer(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
void Buffer::retain(VkDevice device, Buffer &&other)
{
WrappedObject::retain(device, std::move(other));
mMemory.retain(device, std::move(other.mMemory));
}
Error Buffer::init(VkDevice device, const VkBufferCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreateBuffer(device, &createInfo, nullptr, &mHandle));
return NoError();
}
Error Buffer::bindMemory(VkDevice device)
{
ASSERT(valid() && mMemory.valid());
ANGLE_VK_TRY(vkBindBufferMemory(device, mHandle, mMemory.getHandle(), 0));
return NoError();
}
// ShaderModule implementation.
ShaderModule::ShaderModule()
{
}
void ShaderModule::destroy(VkDevice device)
{
if (mHandle != VK_NULL_HANDLE)
{
vkDestroyShaderModule(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error ShaderModule::init(VkDevice device, const VkShaderModuleCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreateShaderModule(device, &createInfo, nullptr, &mHandle));
return NoError();
}
// Pipeline implementation.
Pipeline::Pipeline()
{
}
void Pipeline::destroy(VkDevice device)
{
if (valid())
{
vkDestroyPipeline(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error Pipeline::initGraphics(VkDevice device, const VkGraphicsPipelineCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(
vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &createInfo, nullptr, &mHandle));
return NoError();
}
// PipelineLayout implementation.
PipelineLayout::PipelineLayout()
{
}
void PipelineLayout::destroy(VkDevice device)
{
if (valid())
{
vkDestroyPipelineLayout(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error PipelineLayout::init(VkDevice device, const VkPipelineLayoutCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreatePipelineLayout(device, &createInfo, nullptr, &mHandle));
return NoError();
}
// Fence implementation.
Fence::Fence()
{
}
void Fence::destroy(VkDevice device)
{
if (valid())
{
vkDestroyFence(device, mHandle, nullptr);
mHandle = VK_NULL_HANDLE;
}
}
Error Fence::init(VkDevice device, const VkFenceCreateInfo &createInfo)
{
ASSERT(!valid());
ANGLE_VK_TRY(vkCreateFence(device, &createInfo, nullptr, &mHandle));
return NoError();
}
VkResult Fence::getStatus(VkDevice device) const
{
return vkGetFenceStatus(device, mHandle);
}
} // namespace vk
Optional<uint32_t> FindMemoryType(const VkPhysicalDeviceMemoryProperties &memoryProps,
const VkMemoryRequirements &requirements,
uint32_t propertyFlagMask)
{
for (uint32_t typeIndex = 0; typeIndex < memoryProps.memoryTypeCount; ++typeIndex)
{
if ((requirements.memoryTypeBits & (1u << typeIndex)) != 0 &&
((memoryProps.memoryTypes[typeIndex].propertyFlags & propertyFlagMask) ==
propertyFlagMask))
{
return typeIndex;
}
}
return Optional<uint32_t>::Invalid();
}
namespace gl_vk
{
VkPrimitiveTopology GetPrimitiveTopology(GLenum mode)
{
switch (mode)
{
case GL_TRIANGLES:
return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
case GL_POINTS:
return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
case GL_LINES:
return VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
case GL_LINE_STRIP:
return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
case GL_TRIANGLE_FAN:
return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN;
case GL_TRIANGLE_STRIP:
return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
case GL_LINE_LOOP:
// TODO(jmadill): Implement line loop support.
UNIMPLEMENTED();
return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
default:
UNREACHABLE();
return VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
}
}
VkCullModeFlags GetCullMode(const gl::RasterizerState &rasterState)
{
if (!rasterState.cullFace)
{
return VK_CULL_MODE_NONE;
}
switch (rasterState.cullMode)
{
case GL_FRONT:
return VK_CULL_MODE_FRONT_BIT;
case GL_BACK:
return VK_CULL_MODE_BACK_BIT;
case GL_FRONT_AND_BACK:
return VK_CULL_MODE_FRONT_AND_BACK;
default:
UNREACHABLE();
return VK_CULL_MODE_NONE;
}
}
VkFrontFace GetFrontFace(GLenum frontFace)
{
switch (frontFace)
{
case GL_CW:
return VK_FRONT_FACE_CLOCKWISE;
case GL_CCW:
return VK_FRONT_FACE_COUNTER_CLOCKWISE;
default:
UNREACHABLE();
return VK_FRONT_FACE_COUNTER_CLOCKWISE;
}
}
} // namespace gl_vk
} // namespace rx
std::ostream &operator<<(std::ostream &stream, const rx::vk::Error &error)
{
stream << error.toString();
return stream;
}
| 29.731328 | 100 | 0.665539 | pepstack |
900adff34cf687e962e5192990010f4b25724061 | 393 | cpp | C++ | indigo_drivers/ccd_apogee/bin_externals/libapogee/IUsb.cpp | RusDavies/indigo | f46003ffd0d9f5fd5d3cf1daf8292ca216ad982f | [
"RSA-MD"
] | 83 | 2016-11-02T19:37:05.000Z | 2022-03-25T00:46:48.000Z | indigo_drivers/ccd_apogee/bin_externals/libapogee/IUsb.cpp | RusDavies/indigo | f46003ffd0d9f5fd5d3cf1daf8292ca216ad982f | [
"RSA-MD"
] | 202 | 2016-11-05T10:58:09.000Z | 2022-03-30T23:51:45.000Z | indigo_drivers/ccd_apogee/bin_externals/libapogee/IUsb.cpp | RusDavies/indigo | f46003ffd0d9f5fd5d3cf1daf8292ca216ad982f | [
"RSA-MD"
] | 57 | 2016-12-15T06:43:29.000Z | 2022-03-10T17:53:16.000Z | /*!
* 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/.
*
* Copyright(c) 2009 Apogee Instruments, Inc.
* \class IUsb
* \brief Interface class for usb io
*
*/
#include "IUsb.h"
////////////////////////////
// DTOR
IUsb::~IUsb()
{
}
| 18.714286 | 75 | 0.608142 | RusDavies |
900b0b3092775c01a2603502b2c1b26d2d6b96fc | 970 | cpp | C++ | Util/llvm/tools/clang/test/CXX/temp/temp.spec/temp.explicit/p10.cpp | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | 5 | 2020-06-30T05:06:40.000Z | 2021-05-24T08:38:33.000Z | Util/llvm/tools/clang/test/CXX/temp/temp.spec/temp.explicit/p10.cpp | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | null | null | null | Util/llvm/tools/clang/test/CXX/temp/temp.spec/temp.explicit/p10.cpp | ianloic/unladen-swallow | 28148f4ddbb3d519042de1f9fc9f1356fdd31e31 | [
"PSF-2.0"
] | 2 | 2015-10-01T18:28:20.000Z | 2020-09-09T16:25:27.000Z | // RUN: clang-cc -fsyntax-only -verify %s
template<typename T>
struct X0 {
void f(T&);
struct Inner;
static T static_var;
};
template<typename T>
void X0<T>::f(T& t) {
t = 1; // expected-error{{incompatible type}}
}
template<typename T>
struct X0<T>::Inner {
T member;
};
template<typename T>
T X0<T>::static_var = 1; // expected-error{{incompatible type}}
extern template struct X0<void*>;
template struct X0<void*>; // expected-note 2{{instantiation}}
template struct X0<int>; // expected-note 4{{explicit instantiation definition is here}}
extern template void X0<int>::f(int&); // expected-error{{follows explicit instantiation definition}}
extern template struct X0<int>::Inner; // expected-error{{follows explicit instantiation definition}}
extern template int X0<int>::static_var; // expected-error{{follows explicit instantiation definition}}
extern template struct X0<int>; // expected-error{{follows explicit instantiation definition}}
| 28.529412 | 103 | 0.724742 | ianloic |
900bec79bda00185ffaccaf6ed5f5ac0b79c3355 | 618 | hpp | C++ | include/Analyzer.hpp | pinxau1000/Simple-Buffer-Analyzer | 7df52a5a6f557ba7ec95f7a8d0e32b2338b012c2 | [
"MIT"
] | null | null | null | include/Analyzer.hpp | pinxau1000/Simple-Buffer-Analyzer | 7df52a5a6f557ba7ec95f7a8d0e32b2338b012c2 | [
"MIT"
] | null | null | null | include/Analyzer.hpp | pinxau1000/Simple-Buffer-Analyzer | 7df52a5a6f557ba7ec95f7a8d0e32b2338b012c2 | [
"MIT"
] | null | null | null | //
// Created by pinxau1000 on 12/07/21.
//
#ifndef MAIN_ANALYZER_HPP
#define MAIN_ANALYZER_HPP
#include <iostream>
#include <exception>
#include <vector>
#include <string>
#include <cmath>
#include <ctime>
#include "Buffer.hpp"
#include "Bitstream.hpp"
#include "Definitions.hpp"
Buffer analyze(std::string arg_csv_file, double arg_bit_rate, double arg_buffer_length, double arg_init_buffer_length = 0,
int arg_fps = 0, std::string arg_unit = "b", std::string arg_generate_csv = "",
std::string arg_generate_plot = "", int arg_verbose = VERBOSE_STANDARD);
#endif //MAIN_ANALYZER_HPP
| 26.869565 | 122 | 0.721683 | pinxau1000 |
900befff6025f7b5c413a811831768e78c2d4a0c | 168 | hpp | C++ | src/EventHandler.hpp | tblyons/goon | fd5fbdda14fe1b4869e365c7cebec2bcb7de06e3 | [
"Unlicense"
] | 1 | 2021-03-14T01:27:42.000Z | 2021-03-14T01:27:42.000Z | apps/Goon/src/EventHandler.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | 15 | 2021-08-21T13:41:29.000Z | 2022-03-08T14:13:43.000Z | apps/Goon/src/EventHandler.hpp | tybl/tybl | cc74416d3d982177d46b89c0ca44f3a8e1cf00d6 | [
"Unlicense"
] | null | null | null | // License: The Unlicense (https://unlicense.org)
#ifndef GOON_EVENTHANDLER_HPP
#define GOON_EVENTHANDLER_HPP
void SetUpEvents(void);
#endif // GOON_EVENTHANDLER_HPP
| 21 | 49 | 0.803571 | tblyons |
900d1e777a5b1061a4d377cbe5c88eddd4fb18d4 | 9,731 | cpp | C++ | blast/src/objtools/alnmgr/pairwise_aln.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objtools/alnmgr/pairwise_aln.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/objtools/alnmgr/pairwise_aln.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* $Id: pairwise_aln.cpp 489594 2016-01-14 14:58:22Z grichenk $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Kamen Todorov, NCBI
*
* File Description:
* Pairwise and query-anchored alignments
*
* ===========================================================================
*/
#include <ncbi_pch.hpp>
#include <objtools/alnmgr/pairwise_aln.hpp>
BEGIN_NCBI_SCOPE
USING_SCOPE(objects);
CPairwise_CI& CPairwise_CI::operator++(void)
{
if ( m_Direct ) {
if (m_It == m_GapIt) {
// Advance to the next gap.
++m_It;
}
// Advance to the next non-gap segment if there's no unaligned range
// to show.
else if ( !m_Unaligned ) {
// Advance to the next segment.
++m_GapIt;
_ASSERT(m_It == m_GapIt);
}
}
else {
if (m_It == m_GapIt) {
if (m_It == m_Aln->begin()) {
m_It = m_Aln->end();
m_GapIt = m_Aln->end();
}
else {
--m_It;
}
}
else if ( !m_Unaligned ) {
_ASSERT(m_GapIt != m_Aln->begin());
--m_GapIt;
_ASSERT(m_It == m_GapIt);
}
}
x_InitSegment();
return *this;
}
void CPairwise_CI::x_Init(bool force_direct)
{
// Mixed direction and empty alignments are iterated in direct order.
m_Direct = force_direct ||
((m_Aln->GetFlags() & CPairwiseAln::fMixedDir) == CPairwiseAln::fMixedDir) ||
m_Aln->empty() ||
m_Aln->begin()->IsFirstDirect();
if ( m_Direct ) {
TCheckedIterator it = m_Aln->find_2(m_Range.GetFrom());
m_It = it.first;
m_GapIt = it.first;
if ( !it.second ) {
if (m_GapIt != m_Aln->begin()) {
--m_GapIt;
}
}
}
else {
CPairwiseAln::const_iterator last = m_Aln->end();
if ( !m_Aln->empty() ) {
--last;
}
TCheckedIterator it = m_Range.IsWhole() ?
TCheckedIterator(last, true)
: m_Aln->find_2(m_Range.GetTo());
if (it.first == m_Aln->end()) {
it.first = last;
}
m_It = it.first;
m_GapIt = it.first;
if ( !it.second ) {
if (m_GapIt != m_Aln->end() && m_GapIt != last) {
++m_GapIt;
}
}
}
x_InitSegment();
}
void CPairwise_CI::x_InitSegment(void)
{
if ( !*this ) {
m_FirstRg = TSignedRange::GetEmpty();
m_SecondRg = TSignedRange::GetEmpty();
return;
}
_ASSERT(m_It != m_Aln->end() && m_GapIt != m_Aln->end());
if (m_It == m_GapIt) {
// Normal segment
m_FirstRg = m_It->GetFirstRange();
m_SecondRg = m_It->GetSecondRange();
}
else {
// Gap
TSignedSeqPos it_second_from = m_It->GetSecondFrom();
TSignedSeqPos it_second_to = m_It->GetSecondToOpen();
TSignedSeqPos gap_second_from = m_GapIt->GetSecondFrom();
TSignedSeqPos gap_second_to = m_GapIt->GetSecondToOpen();
if ( m_Direct ) {
m_FirstRg.SetOpen(m_GapIt->GetFirstToOpen(), m_It->GetFirstFrom());
if ( m_It->IsDirect() ) {
if ( m_GapIt->IsDirect() ) {
m_SecondRg.SetOpen(gap_second_to, it_second_from);
}
else {
m_SecondRg.SetOpen(min(gap_second_from, it_second_from),
max(gap_second_from, it_second_from));
}
}
else {
if ( !m_GapIt->IsDirect() ) {
m_SecondRg.SetOpen(it_second_to, gap_second_from);
}
else {
m_SecondRg.SetOpen(min(gap_second_to, it_second_to),
max(gap_second_to, it_second_to));
}
}
if ( !m_Unaligned ) {
if (!m_FirstRg.Empty() && !m_SecondRg.Empty()) {
// Show gap first, then unaligned segment.
m_SecondRg.SetToOpen(m_SecondRg.GetFrom());
m_Unaligned = true;
}
}
else {
// Show unaligned segment after gap.
m_FirstRg.SetFrom(m_FirstRg.GetToOpen());
m_Unaligned = false;
// Don't clip unaligned segments.
return;
}
}
else {
m_FirstRg.SetOpen(m_It->GetFirstToOpen(), m_GapIt->GetFirstFrom());
if ( m_It->IsDirect() ) {
if ( m_GapIt->IsDirect() ) {
m_SecondRg.SetOpen(it_second_to, gap_second_from);
}
else {
m_SecondRg.SetOpen(min(it_second_to, gap_second_to),
max(it_second_to, gap_second_to));
}
}
else {
if ( !m_GapIt->IsDirect() ) {
m_SecondRg.SetOpen(gap_second_to, it_second_from);
}
else {
m_SecondRg.SetOpen(min(it_second_from, gap_second_from),
max(it_second_from, gap_second_from));
}
}
if ( !m_Unaligned ) {
if ( !m_FirstRg.Empty() && !m_SecondRg.Empty()) {
m_SecondRg.SetFrom(m_SecondRg.GetToOpen());
m_Unaligned = true;
}
}
else {
m_FirstRg.SetToOpen(m_FirstRg.GetFrom());
m_Unaligned = false;
return;
}
}
}
if ( m_Range.IsWhole() ) {
return;
}
// Take both direction into account, adjust ranges if clipped.
TSignedSeqPos left_shift = 0;
TSignedSeqPos right_shift = 0;
if (m_FirstRg.GetFrom() < m_Range.GetFrom()) {
left_shift = m_Range.GetFrom() - m_FirstRg.GetFrom();
}
if (m_FirstRg.GetToOpen() > m_Range.GetToOpen()) {
right_shift = m_FirstRg.GetToOpen() - m_Range.GetToOpen();
}
m_FirstRg.IntersectWith(m_Range);
if (left_shift != 0 || right_shift != 0) {
if ( m_It->IsReversed() ) {
swap(left_shift, right_shift);
}
m_SecondRg.SetOpen(m_SecondRg.GetFrom() + left_shift,
m_SecondRg.GetToOpen() - right_shift);
if (m_SecondRg.GetToOpen() < m_SecondRg.GetFrom()) {
m_SecondRg.SetToOpen(m_SecondRg.GetFrom());
}
}
}
/// Split rows with mixed dir into separate rows
/// returns true if the operation was performed
bool CAnchoredAln::SplitStrands()
{
TDim dim = GetDim();
TDim new_dim = dim;
TDim row;
TDim new_row;
for (row = 0; row < dim; ++row) {
if (m_PairwiseAlns[row]->IsSet(CPairwiseAln::fMixedDir)) {
++new_dim;
}
}
_ASSERT(dim <= new_dim);
if (new_dim > dim) {
m_PairwiseAlns.resize(new_dim);
row = dim - 1;
new_row = new_dim - 1;
while (row < new_row) {
_ASSERT(row >= 0);
_ASSERT(new_row > 0);
if (row == m_AnchorRow) {
m_AnchorRow = new_row;
}
const CPairwiseAln& aln = *m_PairwiseAlns[row];
if (aln.IsSet(CPairwiseAln::fMixedDir)) {
m_PairwiseAlns[new_row].Reset
(new CPairwiseAln(aln.GetFirstId(),
aln.GetSecondId(),
aln.GetPolicyFlags()));
CPairwiseAln& reverse_aln = *m_PairwiseAlns[new_row--];
m_PairwiseAlns[new_row].Reset
(new CPairwiseAln(aln.GetFirstId(),
aln.GetSecondId(),
aln.GetPolicyFlags()));
CPairwiseAln& direct_aln = *m_PairwiseAlns[new_row--];
ITERATE (CPairwiseAln, aln_rng_it, aln) {
if (aln_rng_it->IsDirect()) {
direct_aln.push_back(*aln_rng_it);
} else {
reverse_aln.push_back(*aln_rng_it);
}
}
} else {
m_PairwiseAlns[new_row--].Reset
(new CPairwiseAln(aln));
}
--row;
_ASSERT(row <= new_row);
}
return true;
} else {
_ASSERT(dim == new_dim);
return false;
}
}
END_NCBI_SCOPE
| 33.211604 | 86 | 0.504573 | mycolab |
90144adc4e684ba0b37255dcb76a4200d471c0ad | 3,114 | cpp | C++ | src/set_fen.cpp | dave7895/libchess | f32d66249830c0cb2c378121dcca473c49b17e3e | [
"MIT"
] | null | null | null | src/set_fen.cpp | dave7895/libchess | f32d66249830c0cb2c378121dcca473c49b17e3e | [
"MIT"
] | null | null | null | src/set_fen.cpp | dave7895/libchess | f32d66249830c0cb2c378121dcca473c49b17e3e | [
"MIT"
] | 2 | 2022-02-15T15:19:55.000Z | 2022-02-21T22:54:13.000Z | #include <cassert>
#include <sstream>
#include "libchess/position.hpp"
namespace libchess {
void Position::set_fen(const std::string &fen) noexcept {
if (fen == "startpos") {
set_fen("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1");
return;
}
clear();
std::stringstream ss{fen};
std::string word;
ss >> word;
int i = 56;
for (const auto &c : word) {
switch (c) {
case 'P':
set(Square(i), Side::White, Piece::Pawn);
i++;
break;
case 'p':
set(Square(i), Side::Black, Piece::Pawn);
i++;
break;
case 'N':
set(Square(i), Side::White, Piece::Knight);
i++;
break;
case 'n':
set(Square(i), Side::Black, Piece::Knight);
i++;
break;
case 'B':
set(Square(i), Side::White, Piece::Bishop);
i++;
break;
case 'b':
set(Square(i), Side::Black, Piece::Bishop);
i++;
break;
case 'R':
set(Square(i), Side::White, Piece::Rook);
i++;
break;
case 'r':
set(Square(i), Side::Black, Piece::Rook);
i++;
break;
case 'Q':
set(Square(i), Side::White, Piece::Queen);
i++;
break;
case 'q':
set(Square(i), Side::Black, Piece::Queen);
i++;
break;
case 'K':
set(Square(i), Side::White, Piece::King);
i++;
break;
case 'k':
set(Square(i), Side::Black, Piece::King);
i++;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
i += c - '1' + 1;
break;
case '/':
i -= 16;
break;
default:
break;
}
}
// Side to move
ss >> word;
if (word == "w") {
to_move_ = Side::White;
} else {
to_move_ = Side::Black;
}
// Castling perms
ss >> word;
for (const auto &c : word) {
if (c == 'K') {
castling_[0] = true;
} else if (c == 'Q') {
castling_[1] = true;
} else if (c == 'k') {
castling_[2] = true;
} else if (c == 'q') {
castling_[3] = true;
}
}
// En passant
ss >> word;
if (word != "-") {
ep_ = Square(word);
}
// Halfmove clock
ss >> halfmove_clock_;
// Fullmove clock
ss >> fullmove_clock_;
// Calculate hash
#ifdef NO_HASH
hash_ = 0;
#else
hash_ = calculate_hash();
#endif
assert(valid());
}
} // namespace libchess
| 23.413534 | 76 | 0.376044 | dave7895 |
9014dc1e880880177f5f61850b3305955fe47861 | 25,407 | cpp | C++ | src/win32/net.cpp | shuryanc/sdk | b7ece50cfc546fa6c3620c28ee4d9aa05059678b | [
"BSD-2-Clause"
] | 3 | 2015-07-25T02:22:33.000Z | 2021-04-09T14:22:12.000Z | src/win32/net.cpp | shuryanc/sdk | b7ece50cfc546fa6c3620c28ee4d9aa05059678b | [
"BSD-2-Clause"
] | 1 | 2021-01-21T12:13:43.000Z | 2021-01-21T12:13:43.000Z | src/win32/net.cpp | shuryanc/sdk | b7ece50cfc546fa6c3620c28ee4d9aa05059678b | [
"BSD-2-Clause"
] | 1 | 2021-02-02T08:10:49.000Z | 2021-02-02T08:10:49.000Z | /**
* @file win32/net.cpp
* @brief Win32 network access layer (using WinHTTP)
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
// FIXME: Work around WinHTTP's inability to POST additional data
// after having read from the HTTP connection
#include "meganet.h"
#include <winhttp.h>
namespace mega {
extern PGTC pGTC;
WinHttpIO::WinHttpIO()
{
InitializeCriticalSection(&csHTTP);
EnterCriticalSection(&csHTTP);
hWakeupEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
waiter = NULL;
}
WinHttpIO::~WinHttpIO()
{
WinHttpCloseHandle(hSession);
LeaveCriticalSection(&csHTTP);
}
void WinHttpIO::setuseragent(string* useragent)
{
string wuseragent;
wuseragent.resize((useragent->size() + 1) * sizeof(wchar_t));
wuseragent.resize(sizeof(wchar_t)
* (MultiByteToWideChar(CP_UTF8, 0, useragent->c_str(),
-1, (wchar_t*)wuseragent.data(),
int(wuseragent.size() / sizeof(wchar_t) + 1))
- 1));
// create the session handle using the default settings.
hSession = WinHttpOpen((LPCWSTR)wuseragent.data(),
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
WINHTTP_FLAG_ASYNC);
DWORD protocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 |
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 |
WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, &protocols, sizeof (protocols));
}
void WinHttpIO::setproxy(Proxy* proxy)
{
Proxy* autoProxy = NULL;
proxyUsername.clear();
proxyPassword.clear();
if (proxy->getProxyType() == Proxy::AUTO)
{
autoProxy = getautoproxy();
proxy = autoProxy;
}
if (proxy->getProxyType() == Proxy::NONE)
{
WINHTTP_PROXY_INFO proxyInfo;
proxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NO_PROXY;
proxyInfo.lpszProxy = WINHTTP_NO_PROXY_NAME;
proxyInfo.lpszProxyBypass = WINHTTP_NO_PROXY_BYPASS;
WinHttpSetOption(hSession, WINHTTP_OPTION_PROXY, &proxyInfo, sizeof(proxyInfo));
LOG_info << "Proxy disabled";
}
else if (proxy->getProxyType() == Proxy::CUSTOM)
{
string proxyURL = proxy->getProxyURL();
proxyURL.append("", 1);
WINHTTP_PROXY_INFO proxyInfo;
proxyInfo.dwAccessType = WINHTTP_ACCESS_TYPE_NAMED_PROXY;
proxyInfo.lpszProxy = (LPWSTR)proxyURL.data();
proxyInfo.lpszProxyBypass = WINHTTP_NO_PROXY_BYPASS;
WinHttpSetOption(hSession, WINHTTP_OPTION_PROXY, &proxyInfo, sizeof(proxyInfo));
LOG_info << "Proxy enabled";
if (proxy->credentialsNeeded())
{
proxyUsername = proxy->getUsername();
if (proxyUsername.size())
{
proxyUsername.append("", 1);
}
proxyPassword = proxy->getPassword();
if(proxyPassword.size())
{
proxyPassword.append("", 1);
}
LOG_info << "Proxy requires authentication";
}
}
delete autoProxy;
}
// trigger wakeup
void WinHttpIO::httpevent()
{
SetEvent(hWakeupEvent);
}
// (WinHTTP unfortunately uses threads, hence the need for a mutex)
void WinHttpIO::lock()
{
EnterCriticalSection(&csHTTP);
}
void WinHttpIO::unlock()
{
LeaveCriticalSection(&csHTTP);
}
// ensure wakeup from WinHttpIO events
void WinHttpIO::addevents(Waiter* cwaiter, int flags)
{
waiter = (WinWaiter*)cwaiter;
waiter->addhandle(hWakeupEvent, flags);
waiter->pcsHTTP = &csHTTP;
}
// handle WinHTTP callbacks (which can be in a worker thread context)
VOID CALLBACK WinHttpIO::asynccallback(HINTERNET hInternet, DWORD_PTR dwContext,
DWORD dwInternetStatus,
LPVOID lpvStatusInformation,
DWORD dwStatusInformationLength)
{
WinHttpContext* httpctx = (WinHttpContext*)dwContext;
WinHttpIO* httpio = (WinHttpIO*)httpctx->httpio;
if (dwInternetStatus == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING)
{
LOG_verbose << "Closing request";
assert(!httpctx->req);
if (httpctx->gzip)
{
inflateEnd(&httpctx->z);
}
delete httpctx;
return;
}
httpio->lock();
HttpReq* req = httpctx->req;
// request cancellations that occured after asynccallback() was entered are caught here
if (!req)
{
LOG_verbose << "Request cancelled";
httpio->unlock();
return;
}
switch (dwInternetStatus)
{
case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE:
{
DWORD size = *(DWORD*)lpvStatusInformation;
if (!size)
{
if (req->binary)
{
LOG_debug << req->logname << "[received " << (req->buf ? req->buflen : req->in.size()) << " bytes of raw data]";
}
else
{
if(req->in.size() < 2048)
{
LOG_debug << req->logname << "Received: " << req->in.c_str();
}
else
{
LOG_debug << req->logname << "Received: " << req->in.substr(0,2048).c_str();
}
}
LOG_debug << "Request finished with HTTP status: " << req->httpstatus;
req->status = (req->httpstatus == 200
&& (req->contentlength < 0
|| req->contentlength == (req->buf ? req->bufpos : (int)req->in.size())))
? REQ_SUCCESS : REQ_FAILURE;
if (req->status == REQ_SUCCESS)
{
httpio->lastdata = Waiter::ds;
req->lastdata = Waiter::ds;
}
httpio->success = true;
}
else
{
LOG_verbose << "Data available. Remaining: " << size << " bytes";
char* ptr;
if (httpctx->gzip)
{
m_off_t zprevsize = httpctx->zin.size();
httpctx->zin.resize(size_t(zprevsize + size));
ptr = (char*)httpctx->zin.data() + zprevsize;
}
else
{
ptr = (char*)req->reserveput((unsigned*)&size);
req->bufpos += size;
}
if (!WinHttpReadData(hInternet, ptr, size, NULL))
{
LOG_err << "Unable to get more data. Code: " << GetLastError();
httpio->cancel(req);
}
}
httpio->httpevent();
break;
}
case WINHTTP_CALLBACK_STATUS_READ_COMPLETE:
LOG_verbose << "Read complete";
if (dwStatusInformationLength)
{
LOG_verbose << dwStatusInformationLength << " bytes received";
if (req->httpio)
{
req->httpio->lastdata = Waiter::ds;
req->lastdata = Waiter::ds;
}
if (httpctx->gzip)
{
httpctx->z.next_in = (Bytef*)lpvStatusInformation;
httpctx->z.avail_in = dwStatusInformationLength;
req->bufpos += httpctx->z.avail_out;
int t = inflate(&httpctx->z, Z_SYNC_FLUSH);
req->bufpos -= httpctx->z.avail_out;
if ((char*)lpvStatusInformation + dwStatusInformationLength ==
httpctx->zin.data() + httpctx->zin.size())
{
httpctx->zin.clear();
}
if (t != Z_OK && (t != Z_STREAM_END || httpctx->z.avail_out))
{
LOG_err << "GZIP error";
httpio->cancel(req);
}
}
else
{
// data was copied direct to buf or to req->in.
assert(req->buf && (byte*)lpvStatusInformation >= req->buf && (byte*)lpvStatusInformation + dwStatusInformationLength <= req->buf + req->buflen ||
!req->buf && (char*)lpvStatusInformation >= req->in.data() && (char*)lpvStatusInformation + dwStatusInformationLength <= req->in.data() + req->in.size());
}
if (!WinHttpQueryDataAvailable(httpctx->hRequest, NULL))
{
LOG_err << "Error on WinHttpQueryDataAvailable. Code: " << GetLastError();
httpio->cancel(req);
httpio->httpevent();
}
}
break;
case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE:
{
DWORD statusCode;
DWORD statusCodeSize = sizeof(statusCode);
if (!WinHttpQueryHeaders(httpctx->hRequest,
WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
WINHTTP_HEADER_NAME_BY_INDEX,
&statusCode,
&statusCodeSize,
WINHTTP_NO_HEADER_INDEX))
{
LOG_err << "Error getting headers. Code: " << GetLastError();
httpio->cancel(req);
httpio->httpevent();
}
else
{
LOG_verbose << "Headers available";
req->httpstatus = statusCode;
if (req->httpio)
{
req->httpio->lastdata = Waiter::ds;
req->lastdata = Waiter::ds;
}
if (!req->buf)
{
DWORD timeLeft;
DWORD timeLeftSize = sizeof(timeLeft);
if (WinHttpQueryHeaders(httpctx->hRequest,
WINHTTP_QUERY_CUSTOM | WINHTTP_QUERY_FLAG_NUMBER,
L"X-MEGA-Time-Left",
&timeLeft,
&timeLeftSize,
WINHTTP_NO_HEADER_INDEX))
{
LOG_verbose << "Seconds left until more bandwidth quota: " << timeLeft;
req->timeleft = timeLeft;
}
// check for gzip content encoding
WCHAR contentEncoding[16];
DWORD contentEncodingSize = sizeof(contentEncoding);
httpctx->gzip = WinHttpQueryHeaders(httpctx->hRequest,
WINHTTP_QUERY_CONTENT_ENCODING,
WINHTTP_HEADER_NAME_BY_INDEX,
&contentEncoding,
&contentEncodingSize,
WINHTTP_NO_HEADER_INDEX)
&& !wcscmp(contentEncoding, L"gzip");
// obtain original content length - always present if gzip is in use
DWORD contentLength;
DWORD contentLengthSize = sizeof(contentLength);
if (WinHttpQueryHeaders(httpctx->hRequest,
WINHTTP_QUERY_CUSTOM | WINHTTP_QUERY_FLAG_NUMBER,
L"Original-Content-Length",
&contentLength,
&contentLengthSize,
WINHTTP_NO_HEADER_INDEX))
{
LOG_verbose << "Content-Length: " << contentLength;
req->setcontentlength(contentLength);
if (httpctx->gzip)
{
LOG_verbose << "Using GZIP";
httpctx->z.zalloc = Z_NULL;
httpctx->z.zfree = Z_NULL;
httpctx->z.opaque = Z_NULL;
httpctx->z.avail_in = 0;
httpctx->z.next_in = Z_NULL;
inflateInit2(&httpctx->z, MAX_WBITS+16);
req->in.resize(contentLength);
httpctx->z.avail_out = contentLength;
httpctx->z.next_out = (unsigned char*)req->in.data();
}
else
{
LOG_verbose << "Not using GZIP";
}
}
else if (httpctx->gzip)
{
LOG_err << "Content is gzipped but length is missing";
httpio->cancel(req);
httpio->httpevent();
break;
}
else
{
// not zipped and no original size - check for Content-Length instead, plain data arriving (eg. keep-alive)
if (WinHttpQueryHeaders(httpctx->hRequest,
WINHTTP_QUERY_CUSTOM | WINHTTP_QUERY_FLAG_NUMBER,
L"Content-Length",
&contentLength,
&contentLengthSize,
WINHTTP_NO_HEADER_INDEX))
{
LOG_verbose << "Content-Length: " << contentLength;
req->setcontentlength(contentLength);
}
else
{
LOG_verbose << "Content-Length not available";
}
}
}
if (!WinHttpQueryDataAvailable(httpctx->hRequest, NULL))
{
LOG_err << "Unable to query data. Code: " << GetLastError();
httpio->cancel(req);
httpio->httpevent();
}
else if (httpio->waiter && httpio->noinetds)
{
httpio->inetstatus(true);
}
}
break;
}
case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR:
{
DWORD e = GetLastError();
LOG_err << "Request error. Code: " << e;
if (httpio->waiter && e != ERROR_WINHTTP_TIMEOUT)
{
httpio->inetstatus(false);
}
}
// fall through
case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE:
if (dwInternetStatus == WINHTTP_CALLBACK_STATUS_SECURE_FAILURE)
{
LOG_err << "Security check failed. Code: " << (*(DWORD*)lpvStatusInformation);
}
httpio->cancel(req);
httpio->httpevent();
break;
case WINHTTP_CALLBACK_STATUS_SENDING_REQUEST:
{
if (MegaClient::disablepkp || !req->protect)
{
break;
}
PCCERT_CONTEXT cert;
DWORD len = sizeof cert;
if (WinHttpQueryOption(httpctx->hRequest, WINHTTP_OPTION_SERVER_CERT_CONTEXT, &cert, &len))
{
CRYPT_BIT_BLOB* pkey = &cert->pCertInfo->SubjectPublicKeyInfo.PublicKey;
// this is an SSL connection: verify public key to prevent MITM attacks
if (pkey->cbData != 270
|| (memcmp(pkey->pbData, "\x30\x82\x01\x0a\x02\x82\x01\x01\x00" APISSLMODULUS1
"\x02" APISSLEXPONENTSIZE APISSLEXPONENT, 270)
&& memcmp(pkey->pbData, "\x30\x82\x01\x0a\x02\x82\x01\x01\x00" APISSLMODULUS2
"\x02" APISSLEXPONENTSIZE APISSLEXPONENT, 270)))
{
LOG_err << "Invalid public key. Possible MITM attack!!";
req->sslcheckfailed = true;
CertFreeCertificateContext(cert);
httpio->cancel(req);
httpio->httpevent();
break;
}
CertFreeCertificateContext(cert);
}
break;
}
case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE:
case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE:
if (httpctx->postpos < httpctx->postlen)
{
LOG_verbose << "Chunk written";
unsigned pos = httpctx->postpos;
unsigned t = httpctx->postlen - pos;
if (t > HTTP_POST_CHUNK_SIZE)
{
t = HTTP_POST_CHUNK_SIZE;
}
httpctx->postpos += t;
if (!WinHttpWriteData(httpctx->hRequest, (LPVOID)(httpctx->postdata + pos), t, NULL))
{
LOG_err << "Error writing data. Code: " << GetLastError();
req->httpio->cancel(req);
}
httpio->httpevent();
}
else
{
LOG_verbose << "Request written";
if (!WinHttpReceiveResponse(httpctx->hRequest, NULL))
{
LOG_err << "Error receiving response. Code: " << GetLastError();
httpio->cancel(req);
httpio->httpevent();
}
httpctx->postdata = NULL;
}
}
httpio->unlock();
}
// POST request to URL
void WinHttpIO::post(HttpReq* req, const char* data, unsigned len)
{
if (SimpleLogger::logCurrentLevel >= logDebug)
{
string safeurl = req->posturl;
size_t sid = safeurl.find("sid=");
if (sid != string::npos)
{
sid += 4;
size_t end = safeurl.find("&", sid);
if (end == string::npos)
{
end = safeurl.size();
}
memset((char *)safeurl.data() + sid, 'X', end - sid);
}
LOG_debug << "POST target URL: " << safeurl;
}
if (req->binary)
{
LOG_debug << req->logname << "[sending " << (data ? len : req->out->size()) << " bytes of raw data]";
}
else
{
LOG_debug << req->logname << "Sending: " << *req->out;
}
WinHttpContext* httpctx;
WCHAR szURL[8192];
WCHAR szHost[256];
URL_COMPONENTS urlComp = { sizeof urlComp };
urlComp.lpszHostName = szHost;
urlComp.dwHostNameLength = sizeof szHost / sizeof *szHost;
urlComp.dwUrlPathLength = (DWORD)-1;
urlComp.dwSchemeLength = (DWORD)-1;
httpctx = new WinHttpContext;
httpctx->httpio = this;
httpctx->req = req;
httpctx->gzip = false;
req->httpiohandle = (void*)httpctx;
if (MultiByteToWideChar(CP_UTF8, 0, req->posturl.c_str(), -1, szURL,
sizeof szURL / sizeof *szURL)
&& WinHttpCrackUrl(szURL, 0, 0, &urlComp))
{
if ((httpctx->hConnect = WinHttpConnect(hSession, szHost, urlComp.nPort, 0)))
{
httpctx->hRequest = WinHttpOpenRequest(httpctx->hConnect, L"POST",
urlComp.lpszUrlPath, NULL,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
(urlComp.nScheme == INTERNET_SCHEME_HTTPS)
? WINHTTP_FLAG_SECURE
: 0);
if (httpctx->hRequest)
{
if (proxyUsername.size())
{
LOG_verbose << "Setting proxy credentials";
WinHttpSetCredentials(httpctx->hRequest, WINHTTP_AUTH_TARGET_PROXY,
WINHTTP_AUTH_SCHEME_BASIC,
(LPWSTR)proxyUsername.data(), (LPWSTR)proxyPassword.data(), NULL);
}
WinHttpSetTimeouts(httpctx->hRequest, 58000, 58000, 0, 0);
WinHttpSetStatusCallback(httpctx->hRequest, asynccallback,
WINHTTP_CALLBACK_FLAG_DATA_AVAILABLE
| WINHTTP_CALLBACK_FLAG_READ_COMPLETE
| WINHTTP_CALLBACK_FLAG_HEADERS_AVAILABLE
| WINHTTP_CALLBACK_FLAG_REQUEST_ERROR
| WINHTTP_CALLBACK_FLAG_SECURE_FAILURE
| WINHTTP_CALLBACK_FLAG_SENDREQUEST_COMPLETE
| WINHTTP_CALLBACK_FLAG_SEND_REQUEST
| WINHTTP_CALLBACK_FLAG_WRITE_COMPLETE
| WINHTTP_CALLBACK_FLAG_HANDLES,
0);
LPCWSTR pwszHeaders = req->type == REQ_JSON || !req->buf
? L"Content-Type: application/json\r\nAccept-Encoding: gzip"
: L"Content-Type: application/octet-stream";
httpctx->postlen = int(data ? len : req->out->size());
httpctx->postdata = data ? data : req->out->data();
if (urlComp.nPort == 80)
{
LOG_verbose << "HTTP connection";
// HTTP connection: send a chunk of data immediately
httpctx->postpos = (httpctx->postlen < HTTP_POST_CHUNK_SIZE)
? httpctx->postlen
: HTTP_POST_CHUNK_SIZE;
}
else
{
LOG_verbose << "HTTPS connection";
// HTTPS connection: ignore certificate errors, send no data yet
DWORD flags = SECURITY_FLAG_IGNORE_CERT_CN_INVALID
| SECURITY_FLAG_IGNORE_CERT_DATE_INVALID
| SECURITY_FLAG_IGNORE_UNKNOWN_CA;
WinHttpSetOption(httpctx->hRequest, WINHTTP_OPTION_SECURITY_FLAGS, &flags, sizeof flags);
httpctx->postpos = 0;
}
if (WinHttpSendRequest(httpctx->hRequest, pwszHeaders,
DWORD(wcslen(pwszHeaders)),
(LPVOID)httpctx->postdata,
httpctx->postpos,
httpctx->postlen,
(DWORD_PTR)httpctx))
{
LOG_verbose << "Request sent";
req->status = REQ_INFLIGHT;
return;
}
LOG_err << "Error sending request: " << req->posturl << " Code: " << GetLastError();
}
else
{
LOG_err << "Error opening request: " << req->posturl << " Code: " << GetLastError();
}
}
else
{
LOG_err << "Error connecting to " << req->posturl << " Code: " << GetLastError();
httpctx->hRequest = NULL;
}
}
else
{
LOG_err << "Error parsing POST URL: " << req->posturl << " Code: " << GetLastError();
httpctx->hRequest = NULL;
httpctx->hConnect = NULL;
}
LOG_err << "Request failed";
req->status = REQ_FAILURE;
}
// cancel pending HTTP request
void WinHttpIO::cancel(HttpReq* req)
{
WinHttpContext* httpctx;
if ((httpctx = (WinHttpContext*)req->httpiohandle))
{
httpctx->req = NULL;
req->httpstatus = 0;
req->status = REQ_FAILURE;
req->httpiohandle = NULL;
if (httpctx->hConnect)
{
WinHttpCloseHandle(httpctx->hConnect);
}
if (httpctx->hRequest)
{
WinHttpCloseHandle(httpctx->hRequest);
}
}
}
// supply progress information on POST data
m_off_t WinHttpIO::postpos(void* handle)
{
return ((WinHttpContext*)handle)->postpos;
}
// process events
bool WinHttpIO::doio()
{
return false;
}
} // namespace
| 34.94773 | 181 | 0.475735 | shuryanc |
901a35832d897d880e5cd9bbfdd6b38dd7fe5609 | 4,263 | cpp | C++ | src/LongVector.cpp | TheReincarnator/glaziery | f688943163b73cea7034e929539fff8aa39d63e5 | [
"MIT"
] | null | null | null | src/LongVector.cpp | TheReincarnator/glaziery | f688943163b73cea7034e929539fff8aa39d63e5 | [
"MIT"
] | null | null | null | src/LongVector.cpp | TheReincarnator/glaziery | f688943163b73cea7034e929539fff8aa39d63e5 | [
"MIT"
] | null | null | null | /*
* This file is part of the Glaziery.
* Copyright Thomas Jacob.
*
* READ README.TXT BEFORE USE!!
*/
// Main header file
#include <Glaziery/src/Headers.h>
LongVector::LongVector() : x(0), y(0)
{
ASSERTION_COBJECT(this);
}
LongVector::LongVector(long x, long y) : x(x), y(y)
{
ASSERTION_COBJECT(this);
}
LongVector::LongVector(const LongVector & vector) : x(vector.x), y(vector.y)
{
ASSERTION_COBJECT(this);
}
LongVector::LongVector(const Vector & vector) : x(vector.x), y(vector.y)
{
ASSERTION_COBJECT(this);
}
LongVector LongVector::operator +() const
{
ASSERTION_COBJECT(this);
return LongVector(*this);
}
LongVector LongVector::operator +(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return LongVector(x + vector.x, y + vector.y);
}
void LongVector::operator +=(const LongVector & vector)
{
ASSERTION_COBJECT(this);
x += vector.x;
y += vector.y;
}
LongVector LongVector::operator -() const
{
ASSERTION_COBJECT(this);
return LongVector(-x, -y);
}
LongVector LongVector::operator -(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return LongVector(x - vector.x, y - vector.y);
}
void LongVector::operator -=(const LongVector & vector)
{
ASSERTION_COBJECT(this);
x -= vector.x;
y -= vector.y;
}
LongVector LongVector::operator *(long scale) const
{
ASSERTION_COBJECT(this);
return LongVector(x * scale, y * scale);
}
LongVector LongVector::operator *(double scale) const
{
ASSERTION_COBJECT(this);
return LongVector((long) (x * scale + 0.5), (long) (y * scale + 0.5));
}
void LongVector::operator *=(long scale)
{
ASSERTION_COBJECT(this);
x *= scale;
y *= scale;
}
void LongVector::operator *=(double scale)
{
ASSERTION_COBJECT(this);
x = (long) (x * scale + 0.5);
y = (long) (y * scale + 0.5);
}
LongVector LongVector::operator /(long scale) const
{
ASSERTION_COBJECT(this);
return LongVector(x / scale, y / scale);
}
LongVector LongVector::operator /(double scale) const
{
ASSERTION_COBJECT(this);
return LongVector((long) (x / scale + 0.5), (long) (y / scale + 0.5));
}
void LongVector::operator /=(long scale)
{
ASSERTION_COBJECT(this);
x /= scale;
y /= scale;
}
void LongVector::operator /=(double scale)
{
ASSERTION_COBJECT(this);
x = (long) (x / scale + 0.5);
y = (long) (y / scale + 0.5);
}
void LongVector::operator =(const LongVector & vector)
{
ASSERTION_COBJECT(this);
x = vector.x;
y = vector.y;
}
bool LongVector::operator ==(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x == vector.x && y == vector.y;
}
bool LongVector::operator !=(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x != vector.x || y != vector.y;
}
bool LongVector::operator >(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x > vector.x && y > vector.y;
}
bool LongVector::operator >=(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x >= vector.x && y >= vector.y;
}
bool LongVector::operator <(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x < vector.x && y < vector.y;
}
bool LongVector::operator <=(const LongVector & vector) const
{
ASSERTION_COBJECT(this);
return x <= vector.x && y <= vector.y;
}
LongVector LongVector::absolute() const
{
ASSERTION_COBJECT(this);
return LongVector(abs(x), abs(y));
}
bool LongVector::constrain(LongVector from, LongVector to)
{
ASSERTION_COBJECT(this);
if (from.x > to.x)
{
long buffer = from.x;
from.x = to.x;
to.x = buffer;
}
if (from.y > to.y)
{
long buffer = from.y;
from.y = to.y;
to.y = buffer;
}
bool changed = false;
if (x > to.x)
{
x = to.x;
changed = true;
}
if (y > to.y)
{
y = to.y;
changed = true;
}
if (x < from.x)
{
x = from.x;
changed = true;
}
if (y < from.y)
{
y = from.y;
changed = true;
}
return changed;
}
double LongVector::getLength()
{
ASSERTION_COBJECT(this);
return sqrt((double) (x*x + y*y));
}
#if defined(_DEBUG) && (defined(_AFX) || defined(_AFXDLL))
IMPLEMENT_DYNAMIC(LongVector, CObject);
#endif
bool LongVector::isZero() const
{
ASSERTION_COBJECT(this);
return x == 0 && y == 0;
}
String LongVector::toString()
{
ASSERTION_COBJECT(this);
String string;
string.Format("LongVector(%d,%d)", x, y);
return string;
}
| 17.052 | 76 | 0.665259 | TheReincarnator |
901dc2e6bc4b2cef7f026b31d38a488172ce7c11 | 12,444 | cpp | C++ | Source/Core/Visualization/Renderer/StochasticRenderingCompositor.cpp | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | Source/Core/Visualization/Renderer/StochasticRenderingCompositor.cpp | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | Source/Core/Visualization/Renderer/StochasticRenderingCompositor.cpp | GoTamura/KVS | 121ede0b9b81da56e9ea698a45ccfd71ff64ed41 | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************/
/**
* @file StochasticRenderingCompositor.cpp
* @author Naohisa Sakamoto
*/
/*----------------------------------------------------------------------------
*
* Copyright (c) Visualization Laboratory, Kyoto University.
* All rights reserved.
* See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details.
*
* $Id$
*/
/*****************************************************************************/
#include "StochasticRenderingCompositor.h"
#include <kvs/Assert>
#include <kvs/OpenGL>
#include <kvs/PaintEvent>
#include <kvs/EventHandler>
#include <kvs/ScreenBase>
#include <kvs/Scene>
#include <kvs/Camera>
#include <kvs/Light>
#include <kvs/Background>
#include <kvs/ObjectManager>
#include <kvs/RendererManager>
#include <kvs/IDManager>
#include "StochasticRendererBase.h"
#include "ParticleBasedRenderer.h"
namespace kvs
{
/*===========================================================================*/
/**
* @brief Constructs a new StochasticRenderingCompositor class.
* @param scene [in] pointer to the scene
*/
/*===========================================================================*/
StochasticRenderingCompositor::StochasticRenderingCompositor( kvs::Scene* scene ):
m_scene( scene ),
m_width( 0 ),
m_height( 0 ),
m_repetition_level( 1 ),
m_coarse_level( 1 ),
m_enable_lod( false ),
m_enable_refinement( false )
{
}
/*===========================================================================*/
/**
* @brief Updates the scene.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::update()
{
KVS_ASSERT( m_scene );
kvs::OpenGL::WithPushedMatrix p( GL_MODELVIEW );
p.loadIdentity();
{
m_scene->updateGLProjectionMatrix();
m_scene->updateGLViewingMatrix();
m_scene->updateGLLightParameters();
m_scene->background()->apply();
if ( m_scene->objectManager()->hasObject() )
{
this->draw();
}
else
{
m_scene->updateGLModelingMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Draws the objects with stochastic renderers.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::draw()
{
m_timer.start();
kvs::OpenGL::WithPushedAttrib p( GL_ALL_ATTRIB_BITS );
this->check_window_created();
this->check_window_resized();
this->check_object_changed();
// LOD control.
size_t repetitions = m_repetition_level;
kvs::Vec3 camera_position = m_scene->camera()->position();
kvs::Vec3 light_position = m_scene->light()->position();
kvs::Mat4 object_xform = this->object_xform();
if ( m_camera_position != camera_position ||
m_light_position != light_position ||
m_object_xform != object_xform )
{
if ( m_enable_lod )
{
repetitions = m_coarse_level;
}
m_camera_position = camera_position;
m_light_position = light_position;
m_object_xform = object_xform;
m_ensemble_buffer.clear();
}
// Setup engine.
this->engines_setup();
// Ensemble rendering.
const bool reset_count = !m_enable_refinement;
if ( reset_count ) m_ensemble_buffer.clear();
for ( size_t i = 0; i < repetitions; i++ )
{
m_ensemble_buffer.bind();
this->engines_draw();
m_ensemble_buffer.unbind();
m_ensemble_buffer.add();
}
m_ensemble_buffer.draw();
kvs::OpenGL::Finish();
m_timer.stop();
}
/*===========================================================================*/
/**
* @brief Check whether the window is created and initialize the parameters.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::check_window_created()
{
const bool window_created = m_width == 0 && m_height == 0;
if ( window_created )
{
const size_t width = m_scene->camera()->windowWidth();
const size_t height = m_scene->camera()->windowHeight();
m_width = width;
m_height = height;
m_ensemble_buffer.create( width, height );
m_ensemble_buffer.clear();
m_object_xform = this->object_xform();
m_camera_position = m_scene->camera()->position();
m_light_position = m_scene->light()->position();
this->engines_create();
}
}
/*===========================================================================*/
/**
* @brief Check whether the window is resized and update the parameters.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::check_window_resized()
{
const size_t width = m_scene->camera()->windowWidth();
const size_t height = m_scene->camera()->windowHeight();
const bool window_resized = m_width != width || m_height != height;
if ( window_resized )
{
m_width = width;
m_height = height;
m_ensemble_buffer.release();
m_ensemble_buffer.create( width, height );
m_ensemble_buffer.clear();
this->engines_update();
}
}
/*===========================================================================*/
/**
* @brief Check whether the object is changed and recreated the engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::check_object_changed()
{
typedef kvs::StochasticRendererBase Renderer;
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
const bool object_changed = stochastic_renderer->engine().object() != object;
if ( object_changed )
{
m_ensemble_buffer.clear();
if ( stochastic_renderer->engine().object() ) stochastic_renderer->engine().release();
stochastic_renderer->engine().setDepthTexture( m_ensemble_buffer.currentDepthTexture() );
stochastic_renderer->engine().setShader( &stochastic_renderer->shader() );
stochastic_renderer->engine().setRepetitionLevel( m_repetition_level );
stochastic_renderer->engine().setEnabledShading( stochastic_renderer->isEnabledShading() );
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().create( object, m_scene->camera(), m_scene->light() );
kvs::OpenGL::PopMatrix();
}
}
}
}
/*===========================================================================*/
/**
* @brief Returns the xform matrix of the active object.
* @return xform matrix
*/
/*===========================================================================*/
kvs::Mat4 StochasticRenderingCompositor::object_xform()
{
return m_scene->objectManager()->hasActiveObject() ?
m_scene->objectManager()->activeObject()->xform().toMatrix() :
m_scene->objectManager()->xform().toMatrix();
}
/*===========================================================================*/
/**
* @brief Calls the create method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_create()
{
typedef kvs::StochasticRendererBase Renderer;
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
stochastic_renderer->engine().setDepthTexture( m_ensemble_buffer.currentDepthTexture() );
stochastic_renderer->engine().setShader( &stochastic_renderer->shader() );
stochastic_renderer->engine().setRepetitionLevel( m_repetition_level );
stochastic_renderer->engine().setEnabledShading( stochastic_renderer->isEnabledShading() );
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().create( object, m_scene->camera(), m_scene->light() );
kvs::OpenGL::PopMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Calls the update method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_update()
{
typedef kvs::StochasticRendererBase Renderer;
kvs::Camera* camera = m_scene->camera();
kvs::Light* light = m_scene->light();
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().update( object, camera, light );
kvs::OpenGL::PopMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Calls the setup method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_setup()
{
typedef kvs::StochasticRendererBase Renderer;
kvs::Camera* camera = m_scene->camera();
kvs::Light* light = m_scene->light();
const bool reset_count = !m_enable_refinement;
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
if ( reset_count ) stochastic_renderer->engine().resetRepetitions();
stochastic_renderer->engine().setup( object, camera, light );
kvs::OpenGL::PopMatrix();
}
}
}
/*===========================================================================*/
/**
* @brief Calls the draw method of each engine.
*/
/*===========================================================================*/
void StochasticRenderingCompositor::engines_draw()
{
typedef kvs::StochasticRendererBase Renderer;
kvs::Camera* camera = m_scene->camera();
kvs::Light* light = m_scene->light();
const size_t size = m_scene->IDManager()->size();
for ( size_t i = 0; i < size; i++ )
{
kvs::IDManager::IDPair id = m_scene->IDManager()->id( i );
kvs::ObjectBase* object = m_scene->objectManager()->object( id.first );
kvs::RendererBase* renderer = m_scene->rendererManager()->renderer( id.second );
if ( Renderer* stochastic_renderer = Renderer::DownCast( renderer ) )
{
if ( object->isShown() )
{
kvs::OpenGL::PushMatrix();
m_scene->updateGLModelingMatrix( object );
stochastic_renderer->engine().draw( object, camera, light );
stochastic_renderer->engine().countRepetitions();
kvs::OpenGL::PopMatrix();
}
}
}
}
} // end of namespace kvs
| 35.758621 | 107 | 0.530698 | GoTamura |
901e7dc880e5df1f283d5bdf2aef82fec0d77ba6 | 2,081 | cpp | C++ | Common/dslThread.cpp | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | Common/dslThread.cpp | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | Common/dslThread.cpp | TotteKarlsson/dsl | 3807cbe5f90a3cd495979eafa8cf5485367b634c | [
"BSD-2-Clause"
] | null | null | null | #pragma hdrstop
#include "dslLogger.h"
#include "dslThread.h"
//---------------------------------------------------------------------------
namespace dsl
{
int Thread::mThreadCount = 0;
Thread::Thread(const std::string& label)
:
mID(-1),
mIsTimeToDie(false),
mLabel(label),
mIsStarted(false),
mIsFinished(false),
mIsWorking(false),
mIsPaused(false),
mExitStatus(0),
mThread(label)
{}
Thread::~Thread()
{}
void Thread::reset()
{
mIsTimeToDie = false;
mIsFinished = false;
mIsStarted = false;
mIsWorking = false;
mIsPaused = false;
mExitStatus = 0;
}
void Thread::stop()
{
if(!mIsStarted)
{
mIsFinished = true; //If clients ask if thread is finished..
}
mIsTimeToDie = true;
}
void Thread::pause()
{
mIsPaused = true;
}
void Thread::resume()
{
mIsPaused = false;
}
bool Thread::start(bool inThread)
{
if(inThread)
{
Thread::run();
}
else
{
run();
}
return true;
}
//----------------------------------------------------------------
void Thread::run()
{
//This starts and runs the thread
if(mIsWorking || this->isRunning())
{
Log(lDebug3) << "Tried to start a running thread ("<< mLabel <<")";
return;
}
Log(lDebug5) << "Entering Thread::Run function for thread: " << mLabel;
mIsTimeToDie = false;
mIsFinished = false;
//Start poco thread
mThread.start(*this);
}
string Thread::getState()
{
return "Not known";
}
string Thread::getUpTime()
{
return "Not known";
}
bool Thread::isAlive()
{
return !mIsFinished;
}
string Thread::getLabel()
{
return mLabel;
}
string Thread::getName()
{
return mLabel;
}
int Thread::getID()
{
return mID;
}
bool Thread::isTimeToDie()
{
return mIsTimeToDie;
}
bool Thread::isStarted()
{
return mIsStarted;
}
bool Thread::isWorking()
{
return mIsWorking;
}
bool Thread::isRunning()
{
return mThread.isRunning();
}
bool Thread::isFinished()
{
return mIsFinished;
}
bool Thread::isPaused()
{
return mIsPaused;
}
}
| 13.966443 | 77 | 0.570399 | TotteKarlsson |
901f216b738ef752e13af09fd49db08fcdc3d643 | 19,363 | cpp | C++ | test/unit/stack/intrusive_fcstack.cpp | Nemo1369/libcds | 6c96ab635067b2018b14afe5dd0251b9af3ffddf | [
"BSD-2-Clause"
] | null | null | null | test/unit/stack/intrusive_fcstack.cpp | Nemo1369/libcds | 6c96ab635067b2018b14afe5dd0251b9af3ffddf | [
"BSD-2-Clause"
] | 1 | 2017-11-12T06:43:27.000Z | 2017-11-12T06:43:27.000Z | test/unit/stack/intrusive_fcstack.cpp | Nemo1369/libcds | 6c96ab635067b2018b14afe5dd0251b9af3ffddf | [
"BSD-2-Clause"
] | 2 | 2020-10-01T04:12:27.000Z | 2021-07-01T07:46:19.000Z | /*
This file is a part of libcds - Concurrent Data Structures library
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2017
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cds_test/ext_gtest.h>
#include <cds/intrusive/fcstack.h>
#include <boost/intrusive/list.hpp>
namespace {
class IntrusiveFCStack : public ::testing::Test
{
protected:
template <typename Hook>
struct base_hook_item : public Hook
{
int nVal;
int nDisposeCount;
base_hook_item()
: nDisposeCount( 0 )
{}
};
template <typename Hook>
struct member_hook_item
{
int nVal;
int nDisposeCount;
Hook hMember;
member_hook_item()
: nDisposeCount( 0 )
{}
};
struct mock_disposer
{
template <typename T>
void operator ()( T * p )
{
++p->nDisposeCount;
}
};
template <class Stack>
void test()
{
typedef typename Stack::value_type value_type;
Stack stack;
ASSERT_TRUE( stack.empty());
value_type v1, v2, v3;
v1.nVal = 1;
v2.nVal = 2;
v3.nVal = 3;
ASSERT_TRUE( stack.push( v1 ));
ASSERT_TRUE( !stack.empty());
ASSERT_TRUE( stack.push( v2 ));
ASSERT_TRUE( !stack.empty());
ASSERT_TRUE( stack.push( v3 ));
ASSERT_TRUE( !stack.empty());
value_type * pv;
pv = stack.pop();
ASSERT_TRUE( pv != nullptr );
ASSERT_EQ( pv->nVal, 3 );
ASSERT_TRUE( !stack.empty());
pv = stack.pop();
ASSERT_TRUE( pv != nullptr );
ASSERT_EQ( pv->nVal, 2 );
ASSERT_TRUE( !stack.empty());
pv = stack.pop();
ASSERT_TRUE( pv != nullptr );
ASSERT_EQ( pv->nVal, 1 );
ASSERT_TRUE( stack.empty());
pv = stack.pop();
ASSERT_TRUE( pv == nullptr );
ASSERT_TRUE( stack.empty());
if ( !std::is_same<typename Stack::disposer, cds::intrusive::opt::v::empty_disposer>::value ) {
int v1disp = v1.nDisposeCount;
int v2disp = v2.nDisposeCount;
int v3disp = v3.nDisposeCount;
ASSERT_TRUE( stack.push( v1 ));
ASSERT_TRUE( stack.push( v2 ));
ASSERT_TRUE( stack.push( v3 ));
stack.clear();
ASSERT_TRUE( stack.empty());
EXPECT_EQ( v1.nDisposeCount, v1disp);
EXPECT_EQ( v2.nDisposeCount, v2disp);
EXPECT_EQ( v3.nDisposeCount, v3disp);
ASSERT_TRUE( stack.push( v1 ));
ASSERT_TRUE( stack.push( v2 ));
ASSERT_TRUE( stack.push( v3 ));
ASSERT_TRUE( !stack.empty());
stack.clear( true );
ASSERT_TRUE( stack.empty());
EXPECT_EQ( v1.nDisposeCount, v1disp + 1 );
EXPECT_EQ( v2.nDisposeCount, v2disp + 1 );
EXPECT_EQ( v3.nDisposeCount, v3disp + 1 );
}
}
};
TEST_F( IntrusiveFCStack, slist )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_empty_wait_strategy )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::empty wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_single_condvar )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_multi_condvar )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_multi_mutex_multi_condvar )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_single_condvar_2ms )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<2> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_single_mutex_multi_condvar_3ms )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<3> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_multi_mutex_multi_condvar_2ms )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<2> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_disposer )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public cds::intrusive::fcstack::traits
{
typedef mock_disposer disposer;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_mutex )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public cds::intrusive::fcstack::traits
{
typedef std::mutex lock_type;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_elimination )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public
cds::intrusive::fcstack::make_traits <
cds::opt::enable_elimination < true >
> ::type
{};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_elimination_disposer )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
struct stack_traits : public
cds::intrusive::fcstack::make_traits <
cds::opt::enable_elimination < true >,
cds::intrusive::opt::disposer< mock_disposer >,
cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<>>
> ::type
{};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_elimination_stat )
{
typedef base_hook_item< boost::intrusive::slist_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_empty_wait_strategy )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::empty wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_single_mutex_single_condvar )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_single_mutex_multi_condvar )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_multi_mutex_multi_condvar )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits: public cds::intrusive::fcstack::traits
{
typedef cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<> wait_strategy;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_disposer )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
struct stack_traits : public cds::intrusive::fcstack::traits
{
typedef mock_disposer disposer;
};
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >, stack_traits > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_elimination )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, slist_member_elimination_stat )
{
typedef member_hook_item< boost::intrusive::slist_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::slist_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::slist< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_multi_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_mutex )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::lock_type< std::mutex >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_elimination )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_elimination_stat )
{
typedef base_hook_item< boost::intrusive::list_base_hook<> > value_type;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::multi_mutex_multi_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_member )
{
typedef member_hook_item< boost::intrusive::list_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::list_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type, member_option > > stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_member_elimination )
{
typedef member_hook_item< boost::intrusive::list_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::list_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
>::type
> stack_type;
test<stack_type>();
}
TEST_F( IntrusiveFCStack, list_member_elimination_stat )
{
typedef member_hook_item< boost::intrusive::list_member_hook<> > value_type;
typedef boost::intrusive::member_hook<value_type, boost::intrusive::list_member_hook<>, &value_type::hMember> member_option;
typedef cds::intrusive::FCStack< value_type, boost::intrusive::list< value_type, member_option >,
cds::intrusive::fcstack::make_traits<
cds::opt::enable_elimination< true >
, cds::opt::stat< cds::intrusive::fcstack::stat<> >
, cds::opt::wait_strategy< cds::algo::flat_combining::wait_strategy::single_mutex_single_condvar<>>
>::type
> stack_type;
test<stack_type>();
}
} // namespace
| 41.462527 | 133 | 0.644063 | Nemo1369 |
901f523f1610f71839afbfbf0d99bc3d9df0ba9b | 3,248 | cpp | C++ | unit/goto-symex/symex_level0.cpp | tobireinhard/cbmc | fc165c119985adf8db9a13493f272a2def4e79fa | [
"BSD-4-Clause"
] | 412 | 2016-04-02T01:14:27.000Z | 2022-03-27T09:24:09.000Z | unit/goto-symex/symex_level0.cpp | tobireinhard/cbmc | fc165c119985adf8db9a13493f272a2def4e79fa | [
"BSD-4-Clause"
] | 4,671 | 2016-02-25T13:52:16.000Z | 2022-03-31T22:14:46.000Z | unit/goto-symex/symex_level0.cpp | tobireinhard/cbmc | fc165c119985adf8db9a13493f272a2def4e79fa | [
"BSD-4-Clause"
] | 266 | 2016-02-23T12:48:00.000Z | 2022-03-22T18:15:51.000Z | /*******************************************************************\
Module: Unit tests for symex_target_equation::validate
Author: Diffblue Ltd.
\*******************************************************************/
#include <testing-utils/use_catch.h>
#include <goto-symex/goto_symex_state.h>
#include <goto-symex/renaming_level.h>
#include <util/bitvector_types.h>
#include <util/namespace.h>
#include <util/symbol_table.h>
SCENARIO("Level 0 renaming", "[core][goto-symex][symex-level0]")
{
GIVEN(
"A symbol table with a thread local variable, a shared variable, "
"a guard, and a function")
{
symbol_tablet symbol_table;
namespacet ns{symbol_table};
const signedbv_typet int_type{32};
const symbol_exprt symbol_nonshared{"nonShared", int_type};
const ssa_exprt ssa_nonshared{symbol_nonshared};
symbol_table.insert([&] {
symbolt symbol;
symbol.name = symbol_nonshared.get_identifier();
symbol.type = symbol_nonshared.type();
symbol.value = symbol_nonshared;
symbol.is_thread_local = true;
return symbol;
}());
const symbol_exprt symbol_shared{"shared", int_type};
const ssa_exprt ssa_shared{symbol_shared};
symbol_table.insert([&] {
symbolt symbol;
symbol.name = symbol_shared.get_identifier();
symbol.type = symbol_shared.type();
symbol.value = symbol_shared;
symbol.is_thread_local = false;
return symbol;
}());
const symbol_exprt symbol_guard{goto_symex_statet::guard_identifier(),
bool_typet{}};
const ssa_exprt ssa_guard{symbol_guard};
symbol_table.insert([&] {
symbolt symbol;
symbol.name = symbol_guard.get_identifier();
symbol.type = symbol_guard.type();
symbol.value = symbol_guard;
symbol.is_thread_local = false;
return symbol;
}());
const code_typet code_type({}, int_type);
const symbol_exprt symbol_fun{"fun", code_type};
const ssa_exprt ssa_fun{symbol_fun};
symbol_table.insert([&] {
symbolt fun_symbol;
fun_symbol.name = symbol_fun.get_identifier();
fun_symbol.type = symbol_fun.type();
fun_symbol.value = symbol_fun;
fun_symbol.is_thread_local = true;
return fun_symbol;
}());
WHEN("The non-shared symbol is renamed")
{
auto renamed = symex_level0(ssa_nonshared, ns, 423);
THEN("Its L0 tag is set to the thread index")
{
REQUIRE(renamed.get().get_identifier() == "nonShared!423");
}
}
WHEN("The shared symbol is renamed")
{
auto renamed = symex_level0(ssa_shared, ns, 423);
THEN("Its L0 tag is unchanged")
{
REQUIRE(renamed.get().get_identifier() == "shared");
}
}
WHEN("The guard is renamed")
{
auto renamed = symex_level0(ssa_guard, ns, 423);
THEN("Its L0 tag is unchanged")
{
REQUIRE(
renamed.get().get_identifier() ==
goto_symex_statet::guard_identifier());
}
}
WHEN("The function is renamed")
{
auto renamed = symex_level0(ssa_fun, ns, 423);
THEN("Its L0 tag is unchanged")
{
REQUIRE(renamed.get().get_identifier() == "fun");
}
}
}
}
| 27.760684 | 74 | 0.6133 | tobireinhard |
9020e2d20878db755f7ca479491b7d5bffda3dd5 | 5,091 | cc | C++ | chromium/components/metrics/profiler/profiler_metrics_provider.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/components/metrics/profiler/profiler_metrics_provider.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/components/metrics/profiler/profiler_metrics_provider.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 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/metrics/profiler/profiler_metrics_provider.h"
#include <ctype.h>
#include <stddef.h>
#include <string>
#include <vector>
#include "base/stl_util.h"
#include "base/tracked_objects.h"
#include "components/metrics/metrics_log.h"
namespace metrics {
namespace {
// Maps a thread name by replacing trailing sequence of digits with "*".
// Examples:
// 1. "BrowserBlockingWorker1/23857" => "BrowserBlockingWorker1/*"
// 2. "Chrome_IOThread" => "Chrome_IOThread"
std::string MapThreadName(const std::string& thread_name) {
size_t i = thread_name.length();
while (i > 0 && isdigit(thread_name[i - 1])) {
--i;
}
if (i == thread_name.length())
return thread_name;
return thread_name.substr(0, i) + '*';
}
// Normalizes a source filename (which is platform- and build-method-dependent)
// by extracting the last component of the full file name.
// Example: "c:\b\build\slave\win\build\src\chrome\app\chrome_main.cc" =>
// "chrome_main.cc".
std::string NormalizeFileName(const std::string& file_name) {
const size_t offset = file_name.find_last_of("\\/");
return offset != std::string::npos ? file_name.substr(offset + 1) : file_name;
}
void WriteProfilerData(
const tracked_objects::ProcessDataPhaseSnapshot& process_data_phase,
base::ProcessId process_id,
ProfilerEventProto::TrackedObject::ProcessType process_type,
ProfilerEventProto* performance_profile) {
for (const auto& task : process_data_phase.tasks) {
const tracked_objects::DeathDataSnapshot& death_data = task.death_data;
ProfilerEventProto::TrackedObject* tracked_object =
performance_profile->add_tracked_object();
tracked_object->set_birth_thread_name_hash(
MetricsLog::Hash(MapThreadName(task.birth.thread_name)));
tracked_object->set_exec_thread_name_hash(
MetricsLog::Hash(MapThreadName(task.death_thread_name)));
tracked_object->set_source_file_name_hash(
MetricsLog::Hash(NormalizeFileName(task.birth.location.file_name)));
tracked_object->set_source_function_name_hash(
MetricsLog::Hash(task.birth.location.function_name));
tracked_object->set_source_line_number(task.birth.location.line_number);
tracked_object->set_exec_count(death_data.count);
tracked_object->set_exec_time_total(death_data.run_duration_sum);
tracked_object->set_exec_time_sampled(death_data.run_duration_sample);
tracked_object->set_queue_time_total(death_data.queue_duration_sum);
tracked_object->set_queue_time_sampled(death_data.queue_duration_sample);
tracked_object->set_process_type(process_type);
tracked_object->set_process_id(process_id);
}
}
} // namespace
ProfilerMetricsProvider::ProfilerMetricsProvider() {
}
ProfilerMetricsProvider::ProfilerMetricsProvider(
const base::Callback<bool(void)>& cellular_callback)
: cellular_callback_(cellular_callback) {
}
ProfilerMetricsProvider::~ProfilerMetricsProvider() {
}
void ProfilerMetricsProvider::ProvideGeneralMetrics(
ChromeUserMetricsExtension* uma_proto) {
DCHECK_EQ(tracked_objects::TIME_SOURCE_TYPE_WALL_TIME,
tracked_objects::GetTimeSourceType());
DCHECK_EQ(0, uma_proto->profiler_event_size());
for (auto& event : profiler_events_cache_) {
uma_proto->add_profiler_event()->Swap(&event.second);
}
profiler_events_cache_.clear();
}
void ProfilerMetricsProvider::RecordProfilerData(
const tracked_objects::ProcessDataPhaseSnapshot& process_data_phase,
base::ProcessId process_id,
ProfilerEventProto::TrackedObject::ProcessType process_type,
int profiling_phase,
base::TimeDelta phase_start,
base::TimeDelta phase_finish,
const ProfilerEvents& past_events) {
// Omit profiler data on connections where it's likely to cost the user money
// for us to upload it.
if (IsCellularLogicEnabled())
return;
if (tracked_objects::GetTimeSourceType() !=
tracked_objects::TIME_SOURCE_TYPE_WALL_TIME) {
// We currently only support the default time source, wall clock time.
return;
}
const bool new_phase = !ContainsKey(profiler_events_cache_, profiling_phase);
ProfilerEventProto* profiler_event = &profiler_events_cache_[profiling_phase];
if (new_phase) {
profiler_event->set_profile_version(
ProfilerEventProto::VERSION_SPLIT_PROFILE);
profiler_event->set_time_source(ProfilerEventProto::WALL_CLOCK_TIME);
profiler_event->set_profiling_start_ms(phase_start.InMilliseconds());
profiler_event->set_profiling_finish_ms(phase_finish.InMilliseconds());
for (const auto& event : past_events) {
profiler_event->add_past_session_event(event);
}
}
WriteProfilerData(process_data_phase, process_id, process_type,
profiler_event);
}
bool ProfilerMetricsProvider::IsCellularLogicEnabled() {
if (cellular_callback_.is_null())
return false;
return cellular_callback_.Run();
}
} // namespace metrics
| 35.110345 | 80 | 0.759379 | wedataintelligence |
9025836f7f09dec7a6699cfa2840b3256db101c9 | 27,997 | cpp | C++ | src/cellgrid.cpp | machinelevel/bens-game | e265d9a045426e71c86585503566e3572372f5a7 | [
"MIT"
] | null | null | null | src/cellgrid.cpp | machinelevel/bens-game | e265d9a045426e71c86585503566e3572372f5a7 | [
"MIT"
] | null | null | null | src/cellgrid.cpp | machinelevel/bens-game | e265d9a045426e71c86585503566e3572372f5a7 | [
"MIT"
] | null | null | null |
/************************************************************\
cellgrid.cpp
Files for controlling the grid of cells in Ben's project
\************************************************************/
#include <stdio.h>
#include <stdint.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#include <GL/gl.h>
#include <string.h>
#include "genincludes.h"
#include "upmath.h"
#include "camera.h"
#include "controls.h"
#include "timer.h"
#include "random.h"
#include "cellgrid.h"
#include "cellport.h"
#include "glider.h"
#include "texture.h"
#include "hud.h"
#include "slides.h"
#include "sound.h"
#include "wallmaps.h"
CellGrid *gCells = NULL;
const float hexContract = 0.866f; /**** sqrt(3)/2 ****/
float gHalfPipeRadius = 10.0f;
int gSizzleCycle = 0;
CellGrid::CellGrid(int32 hSize, int32 vSize)
{
hSize = vSize = 80;
mLifeUpdateTimer = 0.0f;
mLifeUpdateTimeInterval = 0.1f;
mLifeUpdateTimeInterval = 0.5f;
mHSize = hSize;
mVSize = vSize;
mCellSize = 2.0f;
mNumCells = hSize * vSize;
mCells = new OneCell[mNumCells];
pfSetVec3(mCenter, 0.0f, 0.0f, 0.0f);
Clear();
mNumWalls = 0;
}
void CellGrid::Clear(void)
{
extern int32 gBadHistorySamples;
int32 i;
gBadHistorySamples = 0;
for (i = 0; i < mNumCells; i++) {
mCells[i].shift = 0;
mCells[i].flags = 0;
mCells[i].goodTimer = 0;
}
}
#define MAP_WD 39
#define MAP_HT 19
void CellGrid::DrawBackdrop(void)
{
int i;
pfVec4 hue;
static float ctime[3] = {0,0,0};
float cfreq[3] = {0.01f,0.02f,0.03f};
float sval, cval;
float hSize = 200.0f;
float vSize = 200.0f;
for (i = 0; i < 3; i++) {
ctime[i] += 360.0f * DeltaTime * cfreq[i];
if (ctime[i] > 360.0f) ctime[i] -= 360.0f;
pfSinCos(ctime[i], &sval, &cval);
hue[i] = (sval+1.0f)*0.15f;
}
hue[3] = 1.0f;
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glDepthMask(false);
glBegin(GL_TRIANGLE_STRIP);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, vSize);
glColor4fv(hue); glVertex3f(-hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, hSize, vSize);
glColor4fv(hue); glVertex3f(-hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, -hSize, vSize);
glColor4fv(hue); glVertex3f( hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, -hSize, vSize);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, vSize);
glEnd();
glBegin(GL_TRIANGLE_STRIP);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, -vSize);
glColor4fv(hue); glVertex3f(-hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, hSize, -vSize);
glColor4fv(hue); glVertex3f(-hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f(-hSize, -hSize, -vSize);
glColor4fv(hue); glVertex3f( hSize, -hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, -hSize, -vSize);
glColor4fv(hue); glVertex3f( hSize, hSize, 0);
glColor4f(0,0,0,1); glVertex3f( hSize, hSize, -vSize);
glEnd();
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glDepthMask(true);
}
void CellGrid::SetupWalls(void)
{
char map[MAP_HT*MAP_WD+1], tag;
int32 i, j, wall = 0;
float xsize = 70, ysize = 60, x1, y1, x2, y2;
float xscale = xsize / (MAP_WD / 2);
float yscale = ysize / (MAP_HT / 2);
bool found;
int mapID;
mapID = 7 * gDifficultySetting;
mapID += gLevels[gCurrentLevel].mLevelNumber;
strcpy(map, gWallMaps[mapID]);
for (i = 0; i < MAP_HT*MAP_WD; i++) {
tag = map[i];
found = false;
if (tag != '.' && tag != '=' && tag != '|') {
for (j = i+1; j < MAP_HT*MAP_WD && !found; j++) {
if (map[j] == tag) {
x1 = ((i % MAP_WD) - (MAP_WD / 2)) * xscale;
y1 = ((i / MAP_WD) - (MAP_HT / 2)) * yscale;
x2 = ((j % MAP_WD) - (MAP_WD / 2)) * xscale;
y2 = ((j / MAP_WD) - (MAP_HT / 2)) * yscale;
pfSetVec3(mWalls[wall][0], x1, y1, 0);
pfSetVec3(mWalls[wall][1], x2, y2, 0);
wall++;
//map[i] = map[j] = '.';
found = true;
}
}
}
}
mNumWalls = wall;
}
void CellGrid::DrawWalls(void)
{
int32 i;
pfVec4 hue;
float *f1, *f2;
float zmin = 0.1f, zmax = 2.0f;
static float ttimer = 0.0f, toff = 0.0f;
float toffset1, toffset2;
float stretch;
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
UseLibTexture(TEXID_ZAP);
ttimer += 20.0f * DeltaTime;
if (ttimer > 1.0f) {
ttimer -= 1.0f;
toff += 0.25f;
if (toff >= 1.0f) toff = 0.0f;
}
glBegin(GL_QUADS);
for (i = 0; i < mNumWalls; i++) {
stretch = RANDOM_IN_RANGE(-2.0f, 1.0f);
toffset1 = toff;
toffset2 = toff + 0.25f;
f1 = (float*)mWalls[i][0];
f2 = (float*)mWalls[i][1];
// PFCOPY_VEC4(hue, healthFillColor[mWallTypes[i]]);
PFSET_VEC4(hue, 1.0f, 1.0f, 1.0f, 1.0f);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(0.0f, toffset1);
glVertex3f(f1[PF_X], f1[PF_Y], zmin - stretch);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(0.0f, toffset2);
glVertex3f(f1[PF_X], f1[PF_Y], zmax + stretch);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(1.0f, toffset2);
glVertex3f(f2[PF_X], f2[PF_Y], zmax + stretch);
hue[3] = RANDOM_IN_RANGE(0.5f, 1.0f);
glColor4fv(hue);
glTexCoord2f(1.0f, toffset1);
glVertex3f(f2[PF_X], f2[PF_Y], zmin - stretch);
}
glEnd();
glDisable(GL_TEXTURE_2D);
glBegin(GL_LINES);
for (i = 0; i < mNumWalls; i++) {
f1 = (float*)mWalls[i][0];
f2 = (float*)mWalls[i][1];
PFSET_VEC4(hue, 1.0f, 1.0f, 1.0f, 1.0f);
glColor4fv(hue);
glVertex3f(f1[PF_X], f1[PF_Y], zmin);
glVertex3f(f1[PF_X], f1[PF_Y], zmax);
glVertex3f(f2[PF_X], f2[PF_Y], zmax);
glVertex3f(f2[PF_X], f2[PF_Y], zmin);
}
glEnd();
}
void CellGrid::DrawHalfPipe(void)
{
int32 i;
pfVec4 hue = {1.0f, 1.0f, 1.0f, 0.5f};
float up, out, angle, sval, cval;
float lineAngle = 5.0f;
float xmin, xmax;
float ymin, ymax;
float zmin = 0.0f;
float u1 = 30.0f, v1 = 1.0f;
float lastUp, lastOut;
GetBounds(&xmin, &xmax, &ymin, &ymax);
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glDisable(GL_DEPTH_TEST);
glDepthMask(false);
UseLibTexture(TEXID_GRID);
for (angle = 0.0f; angle <= 90.0f; angle += lineAngle) {
pfSinCos(angle, &sval, &cval);
up = gHalfPipeRadius * (1.0f - cval);
out = gHalfPipeRadius * sval;
if (angle > 0.0f) {
glColor4fv(hue);
glBegin(GL_TRIANGLE_STRIP);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(xmin - out, ymin - out, zmin + up);
glTexCoord2f(0.0f, v1);
glVertex3f(xmin - lastOut, ymin - lastOut, zmin + lastUp);
glTexCoord2f(u1, 0.0f);
glVertex3f(xmax + out, ymin - out, zmin + up);
glTexCoord2f(u1, v1);
glVertex3f(xmax + lastOut, ymin - lastOut, zmin + lastUp);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(xmax + out, ymax + out, zmin + up);
glTexCoord2f(0.0f, v1);
glVertex3f(xmax + lastOut, ymax + lastOut, zmin + lastUp);
glTexCoord2f(u1, 0.0f);
glVertex3f(xmin - out, ymax + out, zmin + up);
glTexCoord2f(u1, v1);
glVertex3f(xmin - lastOut, ymax + lastOut, zmin + lastUp);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(xmin - out, ymin - out, zmin + up);
glTexCoord2f(0.0f, v1);
glVertex3f(xmin - lastOut, ymin - lastOut, zmin + lastUp);
glEnd();
}
lastUp = up;
lastOut = out;
}
glDepthMask(true);
}
void CellGrid::DrawCorners(void)
{
int32 i;
pfVec4 hue;
float *f1, *f2;
float xmin, xmax;
float ymin, ymax;
float zmin = 0.0f, zmax = 8.0f;
float x, y;
float close = 10.0f, dist;
float width = 2.0f;
static bool strobe = true;
strobe = !strobe;
glDisable(GL_CULL_FACE);
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
UseLibTexture(TEXID_ZAP);
GetBounds(&xmin, &xmax, &ymin, &ymax);
glBegin(GL_TRIANGLES);
// gx = gGlider->mMatrix[PF_T][PF_X];
// gy = gGlider->mMatrix[PF_T][PF_Y];
x = xmin;
y = ymin;
PFCOPY_VEC4(hue, healthFillColor[HEALTH_TYPE_ATTITUDE]);
hue[3] = 1.0f;
glColor4fv(hue);
glVertex3f(x, y, zmin);
hue[3] = 0.0f;
// dist = (x-gx)*(x-gx)+(y-gy)*(y-gy);
// if (dist < close*close) {
// gHealthLevel[HEALTH_TYPE_ATTITUDE] = 1.0f;
// hue[3] = 0.25f;
// }
glColor4fv(hue);
glVertex3f(x-width, y+width, zmax);
glVertex3f(x+width, y-width, zmax);
x = xmax;
y = ymin;
PFCOPY_VEC4(hue, healthFillColor[HEALTH_TYPE_HEALTH]);
hue[3] = 1.0f;
glColor4fv(hue);
glVertex3f(x, y, zmin);
hue[3] = 0.0f;
// dist = (x-gx)*(x-gx)+(y-gy)*(y-gy);
// if (dist < close*close) {
// gHealthLevel[HEALTH_TYPE_HEALTH] = 1.0f;
// hue[3] = 0.25f;
// }
glColor4fv(hue);
glVertex3f(x+width, y+width, zmax);
glVertex3f(x-width, y-width, zmax);
x = xmin;
y = ymax;
PFCOPY_VEC4(hue, healthFillColor[HEALTH_TYPE_AMMO]);
hue[3] = 1.0f;
glColor4fv(hue);
glVertex3f(x, y, zmin);
hue[3] = 0.0f;
// dist = (x-gx)*(x-gx)+(y-gy)*(y-gy);
// if (dist < close*close) {
// gHealthLevel[HEALTH_TYPE_AMMO] = 1.0f;
// hue[3] = 0.25f;
// }
glColor4fv(hue);
glVertex3f(x-width, y-width, zmax);
glVertex3f(x+width, y+width, zmax);
glEnd();
}
void CellGrid::Mutate(void)
{
int32 h, v;
OneCell *pcell;
for (v = 1; v < mVSize - 1; v++) {
for (h = 1; h < mHSize - 1; h++) {
pcell = &(mCells[h + (v * mHSize)]);
if (RANDOM0TO1 < 0.05f) SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
}
}
OneCell *CellGrid::GetHVCell(int32 h, int32 v, int32 *pIndex)
{
int32 index;
if (pIndex) *pIndex = -1;
if (h < 0 || h >= mHSize) return(NULL);
if (v < 0 || v >= mVSize) return(NULL);
index = (v * mHSize) + h;
if (pIndex) *pIndex = index;
return(mCells + index);
}
/**********************************************************\
CellGrid::GetClosestIndex
Given a position, return a pointer to the closest cell.
Also, fill pRow and pCol, for convenience, if they're
not NULL.
\**********************************************************/
OneCell *CellGrid::GetClosestCell(pfVec3 pos, int32 *pCol, int32 *pRow, int32 *pIndex)
{
float frow, fcol;
int32 row, col, index;
OneCell *pcell;
pfVec3 v;
pfSubVec3(v, pos, mCenter);
frow = ( v[PF_Y] / (mCellSize * hexContract)) + (mVSize / 2);
fcol = ( v[PF_X] / mCellSize) + (mHSize / 2);
frow += 0.5f;
fcol += 0.5f;
row = (int32)frow;
if (row & 1) fcol -= 0.5f;
col = (int32)fcol;
if (row < 0) row = 0;
if (col < 0) col = 0;
if (row > mVSize-1) row = mVSize-1;
if (col > mHSize-1) col = mHSize-1;
index = col + (mHSize * row);
pcell = &(mCells[index]);
if (pRow) *pRow = row;
if (pCol) *pCol = col;
if (pIndex) *pIndex = index;
return(pcell);
}
bool CellGrid::KillCellsInRange(pfVec3 center, int32 range, int32 flags)
{
bool retval = false;
int32 h, v, hc, vc, ic;
OneCell *pcell, *pcell2;
/**** Infect the nearby cells ****/
pcell = gCells->GetClosestCell(center, &hc, &vc, &ic);
if (pcell) {
for (v = vc - range; v <= vc + range; v++) {
for (h = hc - range; h <= hc + range; h++) {
pcell2 = gCells->GetHVCell(h, v, &ic);
if (pcell2) {
if (pcell2->shift & (CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT)) {
retval = true;
SETFLAG(pcell2->flags, CELL_FLAG_SHOT);
CLRFLAG(pcell2->shift, CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT);
}
}
}
}
}
return(retval);
}
void CellGrid::GetBounds(float *pXMin, float *pXMax, float *pYMin, float *pYMax)
{
if (pXMin) *pXMin = mCenter[PF_X] - (mCellSize * mHSize * 0.5f);
if (pXMax) *pXMax = mCenter[PF_X] + (mCellSize * mHSize * 0.5f);
if (pYMin) *pYMin = mCenter[PF_Y] - (mCellSize * mHSize * 0.5f * hexContract);
if (pYMax) *pYMax = mCenter[PF_Y] + (mCellSize * mHSize * 0.5f * hexContract);
}
void CellGrid::GetPosFromIndex(int32 index, pfVec3 dest)
{
int32 h, v;
float fieldH = mHSize * mCellSize;
float fieldV = mVSize * mCellSize * hexContract;
h = index % mHSize;
v = index / mHSize;
pfCopyVec3(dest, mCenter);
dest[PF_X] -= fieldH * 0.5f;
dest[PF_Y] -= fieldV * 0.5f;
// dest[PF_X] += x * mCellSize;
// dest[PF_Y] += y * mCellSize * hexContract;
if (1) { //hex grid
pfSetVec3(dest, dest[PF_X] + (h * mCellSize), dest[PF_Y] + (v * mCellSize * hexContract), dest[PF_Z]);
if (v & 1) dest[PF_X] += mCellSize * 0.5f;
} else { //rect grid
pfSetVec3(dest, dest[PF_X] + (h * mCellSize), dest[PF_Y] + (v * mCellSize), dest[PF_Z]);
}
}
void CellGrid::Think(void)
{
if (KeysDown['1']) mLifeUpdateTimeInterval += DeltaTime * 1.0f;
if (KeysDown['2']) mLifeUpdateTimeInterval -= DeltaTime * 1.0f;
if (mLifeUpdateTimeInterval < 0.05f) mLifeUpdateTimeInterval = 0.05f;
if (mLifeUpdateTimeInterval > 10.0f) mLifeUpdateTimeInterval = 10.0f;
LifeUpdate();
}
CellGrid::~CellGrid()
{
if (mCells) {
delete[] mCells;
mCells = NULL;
}
}
void CellGrid::Draw(void)
{
int32 h, v;
uint8 shift, flags;
pfVec3 pos, cpos, vertex, toCam, up, over;
OneCell *pcell;
float t, alt, alt1, alt2;
float *c1, *c2;
pfVec4 color, mix1, mix2;
pfVec4 hueGood = {0.0f, 1.0f, 1.0f, 1.0f};
pfVec4 hueDarkGood = {0.0f, 0.7f, 0.7f, 1.0f};
pfVec4 hueCancer = {1.0f, 0.0f, 0.0f, 1.0f};
pfVec4 hueHealthy = {1.0f, 1.0f, 1.0f, 0.2f};
pfVec4 hueDark = {0.7f, 0.0f, 0.0f, 1.0f};
pfVec4 hueBack = {0.3f, 0.3f, 0.8f, 1.0f};
// pfVec4 hueDark = {1.0f, 1.0f, 1.0f, 0.5f};
pfVec4 BhueCancer = {1.0f, 0.3f, 0.0f, 0.4f};
pfVec4 BhueHealthy = {1.0f, 1.0f, 1.0f, 0.0f};
pfVec4 BhueDark = {0.7f, 0.0f, 0.0f, 0.2f};
float bright;
float fieldH = mHSize * mCellSize;
float fieldV = mVSize * mCellSize * hexContract;
float sval, cval;
static float waveTime = 0.0f;
// int32 hClose, vClose, iClose;
pfVec3 camPos, posClose;
pfCopyVec3(camPos, GlobalCameraMatrix[PF_T]);
// GetClosestCell(gGlider->mMatrix[PF_T], &hClose, &vClose, &iClose);
// GetPosFromIndex(iClose, posClose);
waveTime += 0.1f * DeltaTime;
if (waveTime > 1.0f) waveTime -= 1.0f;
pfCopyVec3(pos, mCenter);
pos[PF_X] -= fieldH * 0.5f;
pos[PF_Y] -= fieldV * 0.5f;
pcell = mCells;
t = mLifeUpdateTimer / mLifeUpdateTimeInterval;
if (t < 0.0f) t = 0.0f;
if (t > 1.0f) t = 1.0f;
if (1) {
/**** draw the underlay ****/
glDisable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glDepthMask(true);
glColor4fv(hueBack);
glBegin(GL_QUADS);
glVertex3f(mCenter[PF_X] - (0.5f * fieldH), mCenter[PF_Y] - (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glVertex3f(mCenter[PF_X] + (0.5f * fieldH), mCenter[PF_Y] - (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glVertex3f(mCenter[PF_X] + (0.5f * fieldH), mCenter[PF_Y] + (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glVertex3f(mCenter[PF_X] - (0.5f * fieldH), mCenter[PF_Y] + (0.5f * fieldV), mCenter[PF_Z] - 0.1f);
glEnd();
}
DrawCorners();
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_DEPTH_TEST);
glDepthMask(true);
UseLibTexture(TEXID_CELL);
glBegin(GL_QUADS);
for (v = 0; v < mVSize; v++) {
pfSinCos((360.0f * waveTime) + (720.0f * (float)v/(float)mVSize), &sval, &cval);
if (!gOptionWaves) sval = cval = 0.0f;
for (h = 0; h < mHSize; h++) {
shift = pcell->shift;
flags = pcell->flags;
if (1) { //hex grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize * hexContract), pos[PF_Z]);
if (v & 1) cpos[PF_X] += mCellSize * 0.5f;
} else { //rect grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize), pos[PF_Z]);
}
cpos[PF_Z] += 0.6f * sval;
// if (h == hClose && v == vClose) {
// cpos[PF_Z] += 1.0f;
// }
#if 1
/******************\
L N
000 h-h
001 h-c
010 c-d
011 c-c
100 d-h
101 d-c
110 c-d
111 c-c
\******************/
// if (flags & CELL_FLAG_GOOD) {
// switch (shift & 0x07) {
// case 0: c1 = hueHealthy; c2 = hueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
// case 1: c1 = hueHealthy; c2 = hueGood; alt1 = 0.0f; alt2 = 1.0f; break;
// case 2: c1 = hueGood; c2 = hueDarkGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 3: c1 = hueGood; c2 = hueGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 4: c1 = hueDarkGood; c2 = hueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
// case 5: c1 = hueDarkGood; c2 = hueGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 6: c1 = hueGood; c2 = hueDarkGood; alt1 = 1.0f; alt2 = 1.0f; break;
// case 7: c1 = hueGood; c2 = hueGood; alt1 = 1.0f; alt2 = 1.0f; break;
// default: c1 = c2 = hueHealthy; break;
// }
// } else {
switch (shift & 0x07) {
case 0: c1 = hueHealthy; c2 = hueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
case 1: c1 = hueHealthy; c2 = hueCancer; alt1 = 0.0f; alt2 = 1.0f; break;
case 2: c1 = hueCancer; c2 = hueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 3: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 4: c1 = hueDark; c2 = hueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
case 5: c1 = hueDark; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 6: c1 = hueCancer; c2 = hueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 7: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
default: c1 = c2 = hueHealthy; break;
}
// }
#else
/******************\
L N
000 h-h
001 h-c
010 c-h
011 c-c
100 h-h
101 h-c
110 c-h
111 c-c
\******************/
switch (shift & 0x07) {
case 0: c1 = hueHealthy; c2 = hueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
case 1: c1 = hueHealthy; c2 = hueCancer; alt1 = 0.0f; alt2 = 1.0f; break;
case 2: c1 = hueCancer; c2 = hueHealthy; alt1 = 1.0f; alt2 = 1.0f; break;
case 3: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 4: c1 = hueHealthy; c2 = hueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
case 5: c1 = hueHealthy; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 6: c1 = hueCancer; c2 = hueHealthy; alt1 = 1.0f; alt2 = 1.0f; break;
case 7: c1 = hueCancer; c2 = hueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
default: c1 = c2 = hueHealthy; break;
}
#endif
/**** move bad cells up for a cool effect ****/
alt = ((1.0f - t) * alt1) + (t * alt2);
cpos[PF_Z] += alt;
pfScaleVec4(mix1, 1.0f - t, c1);
pfScaleVec4(mix2, t, c2);
PFADD_VEC4(color, mix1, mix2);
color[3] += 0.1f * sval;
if (color[3] < 0.0f) color[3] = 0.0f;
if (color[3] > 1.0f) color[3] = 1.0f;
if (gCells->mTotalBadCells == 0) {
if (RANDOM0TO1 < 0.005f) {
pfSetVec4(color, 1.0f, 1.0f, 1.0f, 1.0f);
}
}
if (flags & CELL_FLAG_BOSS) {
bright = RANDOM_IN_RANGE(0.4f, 0.5f);
color[0] = bright;
color[1] = color[2] = bright * 0.5f;
color[3] = 1.0f;
}
if (flags & CELL_FLAG_GOOD) {
float f = pcell->goodTimer;
if (f > 1.0f) f = 1.0f;
pfScaleVec4(mix1, 1.0f - f, color);
pfScaleVec4(mix2, f, hueGood);
PFADD_VEC4(color, mix1, mix2);
}
if (flags & CELL_FLAG_SHOT) {
bright = RANDOM_IN_RANGE(0.7f, 1.0f);
color[0] = color[1] = color[2] = bright;
color[3] = 1.0f;
}
glColor4fv(color);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(cpos[PF_X]-(0.5f*mCellSize), cpos[PF_Y]-(0.5f*mCellSize), cpos[PF_Z]);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(cpos[PF_X]+(0.5f*mCellSize), cpos[PF_Y]-(0.5f*mCellSize), cpos[PF_Z]);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(cpos[PF_X]+(0.5f*mCellSize), cpos[PF_Y]+(0.5f*mCellSize), cpos[PF_Z]);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(cpos[PF_X]-(0.5f*mCellSize), cpos[PF_Y]+(0.5f*mCellSize), cpos[PF_Z]);
pcell++;
}
}
glEnd();
if (1) {
/**** Draw the bubbles ****/
pcell = mCells;
glEnable(GL_DEPTH_TEST);
glDepthMask(false);
UseLibTexture(TEXID_BUBBLE);
glBegin(GL_QUADS);
for (v = 0; v < mVSize; v++) {
pfSinCos((360.0f * waveTime) + (720.0f * (float)v/(float)mVSize), &sval, &cval);
for (h = 0; h < mHSize; h++) {
shift = pcell->shift;
flags = pcell->flags;
if (/*(shift & 7) || */(flags & (CELL_FLAG_SHOT|CELL_FLAG_BOUNCE))) { /**** Only if cancer ****/
if (1) { //hex grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize * hexContract), pos[PF_Z]);
if (v & 1) cpos[PF_X] += mCellSize * 0.5f;
} else { //rect grid
pfSetVec3(cpos, pos[PF_X] + (h * mCellSize), pos[PF_Y] + (v * mCellSize), pos[PF_Z]);
}
cpos[PF_Z] += 0.3f * sval;
// cpos[PF_Z] += 0.25f * mCellSize;
switch (shift & 0x07) {
case 0: c1 = BhueHealthy; c2 = BhueHealthy; alt1 = 0.0f; alt2 = 0.0f; break;
case 1: c1 = BhueHealthy; c2 = BhueCancer; alt1 = 0.0f; alt2 = 1.0f; break;
case 2: c1 = BhueCancer; c2 = BhueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 3: c1 = BhueCancer; c2 = BhueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 4: c1 = BhueDark; c2 = BhueHealthy; alt1 = 1.0f; alt2 = 0.0f; break;
case 5: c1 = BhueDark; c2 = BhueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
case 6: c1 = BhueCancer; c2 = BhueDark; alt1 = 1.0f; alt2 = 1.0f; break;
case 7: c1 = BhueCancer; c2 = BhueCancer; alt1 = 1.0f; alt2 = 1.0f; break;
default: c1 = c2 = BhueHealthy; break;
}
/**** move bad cells up for a cool effect ****/
alt = ((1.0f - t) * alt1) + (t * alt2);
cpos[PF_Z] += alt;
pfScaleVec4(mix1, 1.0f - t, c1);
pfScaleVec4(mix2, t, c2);
PFADD_VEC4(color, mix1, mix2);
color[3] += 0.1f * sval;
if (color[3] < 0.0f) color[3] = 0.0f;
if (color[3] > 1.0f) color[3] = 1.0f;
// pfSetVec4(color, 1.0f, 1.0f, 1.0f, 0.5f);
if (flags & CELL_FLAG_SHOT) {
bright = RANDOM_IN_RANGE(0.7f, 1.0f);
color[0] = color[1] = color[2] = bright;
color[3] = 0.4f * (1.0f - t);
} else if (flags & CELL_FLAG_BOUNCE) {
bright = RANDOM_IN_RANGE(0.7f, 1.0f);
color[0] = color[1] = color[2] = bright;
color[3] = 0.4f;
}
glColor4fv(color);
/**** Now construct our up and over vectors ****/
pfSubVec3(toCam, camPos, cpos);
pfCrossVec3(over, toCam, GlobalCameraMatrix[PF_Z]);
pfCrossVec3(up, over, toCam);
pfNormalizeVec3(up);
pfNormalizeVec3(over);
if (flags & CELL_FLAG_SHOT) {
pfScaleVec3(up, (0.95f + t*5.0f) * mCellSize, up);
pfScaleVec3(over, (0.95f + t*5.0f) * mCellSize, over);
} else {
pfScaleVec3(up, (0.95f) * mCellSize, up);
pfScaleVec3(over, (0.95f) * mCellSize, over);
}
pfAddScaledVec3(vertex, cpos, -0.5f, up);
pfAddScaledVec3(vertex, vertex, -0.5f, over);
glTexCoord2f(0.0f, 0.0f);
glVertex3fv(vertex);
pfAddVec3(vertex, vertex, over);
glTexCoord2f(1.0f, 0.0f);
glVertex3fv(vertex);
pfAddVec3(vertex, vertex, up);
glTexCoord2f(1.0f, 1.0f);
glVertex3fv(vertex);
pfSubVec3(vertex, vertex, over);
glTexCoord2f(0.0f, 1.0f);
glVertex3fv(vertex);
}
pcell++;
}
}
glEnd();
}
}
void CellGrid::LifeUpdate(void)
{
int32 i, h, v, count, nugcount, wasShot = 0;
OneCell *pcell, *phi, *plo, *plolo;
for (i = 0; i < mNumCells; i++) {
CLRFLAG(mCells[i].flags, CELL_FLAG_BOSS);
wasShot |= (mCells[i].flags & CELL_FLAG_SHOT);
// if (mCells[i].shift & (CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT)) {
// } else {
// CLRFLAG(mCells[i].flags, CELL_FLAG_GOOD);
// }
}
if (wasShot && (gSizzleCycle < 1)) {
playSound2D(SOUND_SIZZLE_1, 0.85f, RANDOM_IN_RANGE(0.9f, 1.1f));
gSizzleCycle++;
}
/**** count up the bad cells ****/
mTotalBadCells = 0;
for (i = 0; i < mNumCells; i++) {
pcell = &(mCells[i]);
if (pcell->shift & (CELL_SHIFT_ON|CELL_SHIFT_ON_NEXT)) {
mTotalBadCells++;
}
if (pcell->flags & CELL_FLAG_GOOD) {
pcell->goodTimer -= DeltaTime;
if (pcell->goodTimer <= 0.0f) {
pcell->goodTimer = 0.0f;
CLRFLAG(pcell->flags, CELL_FLAG_GOOD);
} else {
CLRFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
}
}
mLifeUpdateTimer += DeltaTime;
while (1) {
if (mLifeUpdateTimer < mLifeUpdateTimeInterval) return;
mLifeUpdateTimer -= mLifeUpdateTimeInterval;
for (i = 0; i < mNumCells; i++) {
mCells[i].shift <<= 1;
CLRFLAG(mCells[i].flags, CELL_FLAG_SHOT|CELL_FLAG_BOUNCE|CELL_FLAG_BOSS);
}
gSizzleCycle = 0;
for (v = 1; v < mVSize - 1; v++) {
for (h = 1; h < mHSize - 1; h++) {
pcell = &(mCells[h + (v * mHSize)]);
phi = pcell - mHSize;
plo = pcell + mHSize;
plolo = plo + mHSize;
count = 0;
count += phi[-1].shift & CELL_SHIFT_ON;
count += phi[ 0].shift & CELL_SHIFT_ON;
count += phi[ 1].shift & CELL_SHIFT_ON;
count += pcell[-1].shift & CELL_SHIFT_ON;
count += pcell[ 1].shift & CELL_SHIFT_ON;
count += plo[-1].shift & CELL_SHIFT_ON;
count += plo[ 0].shift & CELL_SHIFT_ON;
count += plo[ 1].shift & CELL_SHIFT_ON;
count >>= 1; /**** because CELL_SHIFT_ON is actually bit 2 ****/
if (pcell->shift & CELL_SHIFT_ON) {
if (count == 2 || count == 3) {
SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
} else {
if (count == 3) {
SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
}
}
/**** Detect 2x2 "nuggets" and turn them into gliders ****/
if (pcell->shift & CELL_SHIFT_ON) {
if (h < mHSize-2 && v < mVSize-2) {
nugcount = 0;
nugcount += pcell[ 0].shift & CELL_SHIFT_ON;
nugcount += pcell[ 1].shift & CELL_SHIFT_ON;
nugcount += plo[ 0].shift & CELL_SHIFT_ON;
nugcount += plo[ 1].shift & CELL_SHIFT_ON;
nugcount >>= 1; /**** because CELL_SHIFT_ON is actually bit 2 ****/
if (nugcount == 4) {
nugcount = 0;
nugcount += phi[-1].shift & CELL_SHIFT_ON;
nugcount += phi[ 0].shift & CELL_SHIFT_ON;
nugcount += phi[ 1].shift & CELL_SHIFT_ON;
nugcount += phi[ 2].shift & CELL_SHIFT_ON;
nugcount += pcell[-1].shift & CELL_SHIFT_ON;
nugcount += pcell[ 2].shift & CELL_SHIFT_ON;
nugcount += plo[-1].shift & CELL_SHIFT_ON;
nugcount += plo[ 2].shift & CELL_SHIFT_ON;
nugcount += plolo[-1].shift & CELL_SHIFT_ON;
nugcount += plolo[ 0].shift & CELL_SHIFT_ON;
nugcount += plolo[ 1].shift & CELL_SHIFT_ON;
nugcount += plolo[ 2].shift & CELL_SHIFT_ON;
nugcount >>= 1; /**** because CELL_SHIFT_ON is actually bit 2 ****/
if (nugcount == 0) {
/**** okay, it's a nugget. ****/
if (h < mHSize/2) {
if (v < mVSize/2) {
CLRFLAG(pcell[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(phi[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plo[-1].shift, CELL_SHIFT_ON_NEXT);
} else {
CLRFLAG(plo[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plolo[0].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(pcell[-1].shift, CELL_SHIFT_ON_NEXT);
}
} else {
if (v < mVSize/2) {
CLRFLAG(pcell[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(phi[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plo[2].shift, CELL_SHIFT_ON_NEXT);
} else {
CLRFLAG(plo[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(plolo[1].shift, CELL_SHIFT_ON_NEXT);
SETFLAG(pcell[2].shift, CELL_SHIFT_ON_NEXT);
}
}
}
}
}
}
/**** if it's surrounded by "good" mutated cells, make it good. ****/
// if (pcell->shift & (CELL_SHIFT_ON_NEXT | CELL_SHIFT_ON)) {
// int goodCount = 0;
// goodCount += phi[-1].flags & CELL_FLAG_GOOD;
// goodCount += phi[ 0].flags & CELL_FLAG_GOOD;
// goodCount += phi[ 1].flags & CELL_FLAG_GOOD;
// goodCount += pcell[-1].flags & CELL_FLAG_GOOD;
// goodCount += pcell[ 1].flags & CELL_FLAG_GOOD;
// goodCount += plo[-1].flags & CELL_FLAG_GOOD;
// goodCount += plo[ 0].flags & CELL_FLAG_GOOD;
// goodCount += plo[ 1].flags & CELL_FLAG_GOOD;
// goodCount /= CELL_FLAG_GOOD;
//
// if (goodCount > 1) {
// SETFLAG(pcell->flags, CELL_FLAG_GOOD);
// }
// if (goodCount > 1) {
// CLRFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
// }
// }
// if (pcell->flags & CELL_FLAG_GOOD) {
// SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
// }
/**** some mutation ****/
// if (count > 0) {
// if (RANDOM0TO1 < 0.0005f) {
// SETFLAG(pcell->shift, CELL_SHIFT_ON_NEXT);
// }
// }
}
}
}
}
| 29.133195 | 105 | 0.596814 | machinelevel |
9025fcf2ddbcb62f201dd35e936fe3872a91cba3 | 5,426 | cxx | C++ | mod/maxgui.mod/fltkmaxgui.mod/src/Fl_Light_Button.cxx | jabdoa2/blitzmax | 0ada3c9a134178038c8f6ca67d5a004aa03f24f5 | [
"Zlib"
] | 146 | 2015-09-21T05:58:10.000Z | 2022-03-13T09:56:31.000Z | mod/maxgui.mod/fltkmaxgui.mod/src/Fl_Light_Button.cxx | jabdoa2/blitzmax | 0ada3c9a134178038c8f6ca67d5a004aa03f24f5 | [
"Zlib"
] | 20 | 2015-09-21T09:59:37.000Z | 2022-03-21T18:44:14.000Z | mod/maxgui.mod/fltkmaxgui.mod/src/Fl_Light_Button.cxx | jabdoa2/blitzmax | 0ada3c9a134178038c8f6ca67d5a004aa03f24f5 | [
"Zlib"
] | 62 | 2015-09-21T06:33:46.000Z | 2022-01-02T17:54:41.000Z | //
// "$Id: Fl_Light_Button.cxx 7903 2010-11-28 21:06:39Z matt $"
//
// Lighted button widget for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2010 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems on the following page:
//
// http://www.fltk.org/str.php
//
// Subclass of Fl_Button where the "box" indicates whether it is
// pushed or not, and the "down box" is drawn small and square on
// the left to indicate the current state.
// The default down_box of zero draws a rectangle designed to look
// just like Flame's buttons.
#include <FL/Fl.H>
#include <FL/Fl_Light_Button.H>
#include <FL/fl_draw.H>
#include "flstring.h"
void Fl_Light_Button::draw() {
if (box()) draw_box(this==Fl::pushed() ? fl_down(box()) : box(), color());
Fl_Color col = value() ? (active_r() ? selection_color() :
fl_inactive(selection_color())) : color();
int W;
int dx, dy;
W = labelsize();
dx = Fl::box_dx(box()) + 2;
dy = (h() - W) / 2;
// if (dy < 0) dy = 0; // neg. offset o.k. for vertical centering
if (down_box()) {
// draw other down_box() styles:
switch (down_box()) {
case FL_DOWN_BOX :
case FL_UP_BOX :
case _FL_PLASTIC_DOWN_BOX :
case _FL_PLASTIC_UP_BOX :
// Check box...
draw_box(down_box(), x()+dx, y()+dy, W, W, FL_BACKGROUND2_COLOR);
if (value()) {
if (Fl::scheme() && !strcmp(Fl::scheme(), "gtk+")) {
fl_color(FL_SELECTION_COLOR);
} else {
fl_color(col);
}
int tx = x() + dx + 3;
int tw = W - 6;
int d1 = tw/3;
int d2 = tw-d1;
int ty = y() + dy + (W+d2)/2-d1-2;
for (int n = 0; n < 3; n++, ty++) {
fl_line(tx, ty, tx+d1, ty+d1);
fl_line(tx+d1, ty+d1, tx+tw-1, ty+d1-d2+1);
}
}
break;
case _FL_ROUND_DOWN_BOX :
case _FL_ROUND_UP_BOX :
// Radio button...
draw_box(down_box(), x()+dx, y()+dy, W, W, FL_BACKGROUND2_COLOR);
if (value()) {
int tW = (W - Fl::box_dw(down_box())) / 2 + 1;
if ((W - tW) & 1) tW++; // Make sure difference is even to center
int tdx = dx + (W - tW) / 2;
int tdy = dy + (W - tW) / 2;
if (Fl::scheme() && !strcmp(Fl::scheme(), "gtk+")) {
fl_color(FL_SELECTION_COLOR);
tW --;
fl_pie(x() + tdx - 1, y() + tdy - 1, tW + 3, tW + 3, 0.0, 360.0);
fl_arc(x() + tdx - 1, y() + tdy - 1, tW + 3, tW + 3, 0.0, 360.0);
fl_color(fl_color_average(FL_WHITE, FL_SELECTION_COLOR, 0.2f));
} else fl_color(col);
switch (tW) {
// Larger circles draw fine...
default :
fl_pie(x() + tdx, y() + tdy, tW, tW, 0.0, 360.0);
break;
// Small circles don't draw well on many systems...
case 6 :
fl_rectf(x() + tdx + 2, y() + tdy, tW - 4, tW);
fl_rectf(x() + tdx + 1, y() + tdy + 1, tW - 2, tW - 2);
fl_rectf(x() + tdx, y() + tdy + 2, tW, tW - 4);
break;
case 5 :
case 4 :
case 3 :
fl_rectf(x() + tdx + 1, y() + tdy, tW - 2, tW);
fl_rectf(x() + tdx, y() + tdy + 1, tW, tW - 2);
break;
case 2 :
case 1 :
fl_rectf(x() + tdx, y() + tdy, tW, tW);
break;
}
if (Fl::scheme() && !strcmp(Fl::scheme(), "gtk+")) {
fl_color(fl_color_average(FL_WHITE, FL_SELECTION_COLOR, 0.5));
fl_arc(x() + tdx, y() + tdy, tW + 1, tW + 1, 60.0, 180.0);
}
}
break;
default :
draw_box(down_box(), x()+dx, y()+dy, W, W, col);
break;
}
} else {
// if down_box() is zero, draw light button style:
int hh = h()-2*dy - 2;
int ww = W/2+1;
int xx = dx;
if (w()<ww+2*xx) xx = (w()-ww)/2;
if (Fl::scheme() && !strcmp(Fl::scheme(), "plastic")) {
col = active_r() ? selection_color() : fl_inactive(selection_color());
fl_color(value() ? col : fl_color_average(col, FL_BLACK, 0.5f));
fl_pie(x()+xx, y()+dy+1, ww, hh, 0, 360);
} else {
draw_box(FL_THIN_DOWN_BOX, x()+xx, y()+dy+1, ww, hh, col);
}
dx = (ww + 2 * dx - W) / 2;
}
draw_label(x()+W+2*dx, y(), w()-W-2*dx, h());
if (Fl::focus() == this) draw_focus();
}
int Fl_Light_Button::handle(int event) {
switch (event) {
case FL_RELEASE:
if (box()) redraw();
default:
return Fl_Button::handle(event);
}
}
/**
Creates a new Fl_Light_Button widget using the given
position, size, and label string.
<P>The destructor deletes the check button.
*/
Fl_Light_Button::Fl_Light_Button(int X, int Y, int W, int H, const char* l)
: Fl_Button(X, Y, W, H, l) {
type(FL_TOGGLE_BUTTON);
selection_color(FL_YELLOW);
align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE);
}
//
// End of "$Id: Fl_Light_Button.cxx 7903 2010-11-28 21:06:39Z matt $".
//
| 31.005714 | 76 | 0.576668 | jabdoa2 |
902692ee3d6ef1f03b7ca71cec7c1f79eaa9fdc8 | 2,269 | cpp | C++ | src/cpp/sym_table.cpp | jacoburton104/perspective | 556ef5fc5c74ff5c56cafa6b89804aff80a11fbd | [
"Apache-2.0"
] | 1 | 2021-07-09T05:21:15.000Z | 2021-07-09T05:21:15.000Z | src/cpp/sym_table.cpp | netdebug/perspective | e725ea2b713a671544b2406189fe71358d7b66df | [
"Apache-2.0"
] | null | null | null | src/cpp/sym_table.cpp | netdebug/perspective | e725ea2b713a671544b2406189fe71358d7b66df | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
*
* Copyright (c) 2017, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms of
* the Apache License 2.0. The full license can be found in the LICENSE file.
*
*/
#include <perspective/first.h>
#include <perspective/base.h>
#include <perspective/sym_table.h>
#include <perspective/column.h>
#include <unordered_map>
#include <functional>
#include <mutex>
namespace perspective {
std::mutex sym_table_mutex;
t_symtable::t_symtable() {}
t_symtable::~t_symtable() {
for (auto& kv : m_mapping) {
free(const_cast<char*>(kv.second));
}
}
const t_char*
t_symtable::get_interned_cstr(const t_char* s) {
auto iter = m_mapping.find(s);
if (iter != m_mapping.end()) {
return iter->second;
}
auto scopy = strdup(s);
m_mapping[scopy] = scopy;
return scopy;
}
t_tscalar
t_symtable::get_interned_tscalar(const t_char* s) {
if (t_tscalar::can_store_inplace(s)) {
t_tscalar rval;
rval.set(s);
return rval;
}
t_tscalar rval;
rval.set(get_interned_cstr(s));
return rval;
}
t_tscalar
t_symtable::get_interned_tscalar(const t_tscalar& s) {
if (!s.is_str() || s.is_inplace())
return s;
t_tscalar rval;
rval.set(get_interned_cstr(s.get_char_ptr()));
return rval;
}
t_uindex
t_symtable::size() const {
return m_mapping.size();
}
static t_symtable*
get_symtable() {
static t_symtable* sym = 0;
if (!sym) {
sym = new t_symtable;
}
return sym;
}
const t_char*
get_interned_cstr(const t_char* s) {
std::lock_guard<std::mutex> guard(sym_table_mutex);
auto sym = get_symtable();
return sym->get_interned_cstr(s);
}
t_tscalar
get_interned_tscalar(const t_char* s) {
if (t_tscalar::can_store_inplace(s)) {
t_tscalar rval;
rval.set(s);
return rval;
}
t_tscalar rval;
rval.set(get_interned_cstr(s));
return rval;
}
t_tscalar
get_interned_tscalar(const t_tscalar& s) {
if (!s.is_str() || s.is_inplace())
return s;
t_tscalar rval;
rval.set(get_interned_cstr(s.get_char_ptr()));
return rval;
}
} // end namespace perspective
| 20.441441 | 79 | 0.633759 | jacoburton104 |
90269586b02cf0ef52946fff992f3bef1ec7606b | 1,041 | cpp | C++ | agent/lib/virtualAPfortest/testbed.cpp | Over42M/Fun5Ga | 7712fcae3968a80c3f7957457e5f0492fbd1f812 | [
"Apache-2.0"
] | 7 | 2017-04-26T12:28:22.000Z | 2021-02-09T18:59:50.000Z | agent/lib/virtualAPfortest/testbed.cpp | Over42M/Fun5Ga | 7712fcae3968a80c3f7957457e5f0492fbd1f812 | [
"Apache-2.0"
] | 1 | 2017-04-26T15:22:51.000Z | 2017-04-28T04:41:51.000Z | agent/lib/virtualAPfortest/testbed.cpp | Over42M/Fun5Ga | 7712fcae3968a80c3f7957457e5f0492fbd1f812 | [
"Apache-2.0"
] | 8 | 2017-06-01T08:42:16.000Z | 2020-07-23T12:30:19.000Z | /********************
@file ap_agent.cpp
@date 2015/12/2
@author 안계완
@brief processing message from mananger program
*********************/
#include <cstdlib>
#include <cstring>
#include <string>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <pthread.h>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include "../../headers/protocol.h"
#include "../../headers/hostap.h"
#include "../../headers/Report.h"
#include "../../headers/ctrCommand.h"
using namespace std;
const int max_length = 1024;
void* Thread_Sender(void *arg)
{
char* argv = (char *)arg;
int i = atoi(argv);
Report sender(2);
pthread_exit(0);
}
int main(int argc, char* argv[])
{
pthread_t sender;
srand((unsigned int)time(NULL));
cout << "Testbed" << endl;
cout << "Copyright 2015 Kyung Hee University Mobile Convergence Lab" << endl;
pthread_create(&sender, NULL, &Thread_Sender, (void *)argv[1]);
pthread_join(sender, NULL);
return 0;
}
| 18.927273 | 79 | 0.654179 | Over42M |
9027dece974ca506c9fc91946470fe05cd600b96 | 2,957 | hpp | C++ | modules/ieee/include/nt2/toolbox/ieee/function/scalar/ulp.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | 1 | 2022-03-24T03:35:10.000Z | 2022-03-24T03:35:10.000Z | modules/ieee/include/nt2/toolbox/ieee/function/scalar/ulp.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | null | null | null | modules/ieee/include/nt2/toolbox/ieee/function/scalar/ulp.hpp | brycelelbach/nt2 | 73d7e8dd390fa4c8d251c6451acdae65def70e0b | [
"BSL-1.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
/// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
/// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI
///
/// Distributed under the Boost Software License, Version 1.0
/// See accompanying file LICENSE.txt or copy at
/// http://www.boost.org/LICENSE_1_0.txt
//////////////////////////////////////////////////////////////////////////////
#ifndef NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_ULP_HPP_INCLUDED
#define NT2_TOOLBOX_IEEE_FUNCTION_SCALAR_ULP_HPP_INCLUDED
#include <nt2/sdk/constant/properties.hpp>
#include <nt2/sdk/constant/digits.hpp>
#include <nt2/sdk/constant/infinites.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/sdk/meta/as_bits.hpp>
#include <nt2/sdk/constant/eps_related.hpp>
#include <nt2/include/functions/prev.hpp>
#include <nt2/include/functions/min.hpp>
#include <nt2/include/functions/is_eqz.hpp>
#include <nt2/include/functions/abs.hpp>
/////////////////////////////////////////////////////////////////////////////
// Implementation when type A0 is arithmetic_
/////////////////////////////////////////////////////////////////////////////
NT2_REGISTER_DISPATCH(tag::ulp_, tag::cpu_,
(A0),
(arithmetic_<A0>)
)
namespace nt2 { namespace ext
{
template<class Dummy>
struct call<tag::ulp_(tag::arithmetic_),
tag::cpu_, Dummy> : callable
{
template<class Sig> struct result;
template<class This,class A0>
struct result<This(A0)> :
std::tr1::result_of<meta::arithmetic(A0)>{};
NT2_FUNCTOR_CALL(1)
{
return One<A0>();
}
};
} }
/////////////////////////////////////////////////////////////////////////////
// Implementation when type A0 is real_
/////////////////////////////////////////////////////////////////////////////
NT2_REGISTER_DISPATCH(tag::ulp_, tag::cpu_,
(A0),
(real_<A0>)
)
namespace nt2 { namespace ext
{
template<class Dummy>
struct call<tag::ulp_(tag::real_),
tag::cpu_, Dummy> : callable
{
template<class Sig> struct result;
template<class This,class A0>
struct result<This(A0)> :
std::tr1::result_of<meta::arithmetic(A0)>{};
NT2_FUNCTOR_CALL(1)
{
typedef typename meta::as_integer<A0,signed>::type int_type;
if (is_eqz(a0)) return Smallestposval<A0>();
const A0 x = nt2::abs(a0);
if (x == Inf<A0>()) return x; //Valmax<A0>()-prev(Valmax<A0>());
typename meta::as_bits<A0>::type aa = {x}, bb = aa;
--bb.bits;
++aa.bits;
return nt2::min(x-bb.value, aa.value-x);
// const A0 pred = predecessor(x);
// return (x == Inf<A0>()) ? pred-predecessor(x) : min(dist(pred, x), dist(x, successor(x)));
}
};
} }
#endif
// modified by jt the 26/12/2010
| 34.383721 | 103 | 0.524518 | brycelelbach |