hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8b445c6580dbee8e1f941bbbe65e52d77def3342 | 740 | cpp | C++ | jni/application/Object_Info.cpp | clarkdonald/eecs494game4 | c5101b4bbf7f620c3490dcfb88f5e72260ef8fa2 | [
"BSD-2-Clause"
] | null | null | null | jni/application/Object_Info.cpp | clarkdonald/eecs494game4 | c5101b4bbf7f620c3490dcfb88f5e72260ef8fa2 | [
"BSD-2-Clause"
] | null | null | null | jni/application/Object_Info.cpp | clarkdonald/eecs494game4 | c5101b4bbf7f620c3490dcfb88f5e72260ef8fa2 | [
"BSD-2-Clause"
] | null | null | null | #include "Object_Info.h"
#include <string>
using namespace Zeni;
Object_Info::Object_Info(const String & texture_, const Point2f &position_, const Vector2f &size_)
: Game_Object(position_, size_), texture(texture_)
{}
void Object_Info::render(const unsigned int &num_objects) const {
auto pos = get_position();
Game_Object::render(texture);
get_Fonts()["godofwar_20"].render_text(String(" x" + std::to_string(num_objects)),
Point2f(pos.x + 22.0f, pos.y + 4.0f),
get_Colors()["white"]);
}
void Object_Info::render(const Zeni::String &texture_) const {
Game_Object::render(texture_);
}
void Object_Info::render() const {
Game_Object::render(texture);
}
| 29.6 | 99 | 0.659459 | [
"render"
] |
8b4e9408f6070aaa5c1584d56982fe4128b375f9 | 2,272 | cpp | C++ | ToDoManager/src/Tasks.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | 6 | 2019-08-29T23:31:17.000Z | 2021-11-14T20:35:47.000Z | ToDoManager/src/Tasks.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | null | null | null | ToDoManager/src/Tasks.cpp | Electrux/CCPP-Code | 3c5e5b866cf050c11bced9651b112eb31dd2465d | [
"BSD-3-Clause"
] | 1 | 2019-09-01T12:22:58.000Z | 2019-09-01T12:22:58.000Z | #include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include "../include/Tasks.hpp"
#include "../include/StringFuncs.hpp"
Tasks::Tasks( std::string _filename )
{
this->_filename = _filename;
std::fstream file;
file.open( _filename, std::ios::in );
if( !file ) {
file.open( _filename, std::ios::out );
if( !file ) {
std::cerr << "Could not create/open file." << std::endl;
return;
}
file.close();
return;
}
std::string line;
while( std::getline( file, line ) ) {
Trim( line );
tasks.push_back( line );
}
file.close();
}
bool Tasks::NewTask( std::string & task )
{
if( !Trim( task ) )
return false;
tasks.push_back( task );
return UpdateFile();
}
bool Tasks::DeleteTask( int taskid )
{
if( !IsValidTask( taskid ) )
return false;
taskid--;
int ctr = 0;
for( auto it = tasks.begin(); it != tasks.end(); ++it ) {
if( ctr == taskid ) {
tasks.erase( it );
break;
}
ctr++;
}
return UpdateFile();
}
bool Tasks::ChangeTask( int taskid, std::string & newtask, std::string & oldtask )
{
if( !IsValidTask( taskid ) )
return false;
taskid--;
oldtask = tasks[ taskid ];
tasks[ taskid ] = newtask;
return UpdateFile();
}
std::string Tasks::GetTask( int taskid )
{
if( !IsValidTask( taskid ) )
return "";
taskid--;
return tasks[ taskid ];
}
void Tasks::ShowTasks()
{
if( tasks.empty() ) {
std::cout << "You have nothing to do! Hoorraay!!" << std::endl;
return;
}
std::cout << "\n\nTask ID\t\tTask\n" << std::endl;
int ctr = 1;
for( auto task : tasks ) {
std::cout << ctr << "\t\t" << task << std::endl;
ctr++;
}
std::cout << std::endl;
}
bool Tasks::IsValidTask( int taskid )
{
taskid--;
if( taskid > ( int )tasks.size() ) {
std::cerr << "Entered task ID exceeds total tasks!" << std::endl;
return false;
}
if( taskid < 0 ) {
std::cerr << "Entered task ID is less than zero!" << std::endl;
return false;
}
return true;
}
bool Tasks::UpdateFile()
{
std::fstream file;
file.open( _filename, std::ios::out | std::ios::trunc );
file.close();
file.open( _filename, std::ios::app );
for( auto task : tasks ) {
file << task << std::endl;
}
file.close();
return true;
}
size_t Tasks::CountTasks()
{
return tasks.size();
}
| 14.658065 | 82 | 0.598151 | [
"vector"
] |
332b6faf4cf9acf8ccfb5412160e089d56b50a54 | 1,134 | cpp | C++ | C++/692.top-k-frequent-words.cpp | WilliamZhaoz/github | 2aa0eb17e272249fc225cf2e9861c4c44bd0e265 | [
"MIT"
] | 1 | 2018-03-06T05:07:22.000Z | 2018-03-06T05:07:22.000Z | C++/692.top-k-frequent-words.cpp | WilliamZhaoz/github | 2aa0eb17e272249fc225cf2e9861c4c44bd0e265 | [
"MIT"
] | 1 | 2021-12-24T16:41:02.000Z | 2021-12-24T16:41:02.000Z | C++/692.top-k-frequent-words.cpp | WilliamZhaoz/github | 2aa0eb17e272249fc225cf2e9861c4c44bd0e265 | [
"MIT"
] | null | null | null | struct cmp {
bool operator()(const pair<int, string> &a, const pair<int, string> &b) {
if (a.first == b.first) {
int al = a.second.size(), bl = b.second.size(), i = 0, j = 0;
while (i < al && j < bl) {
if (a.second[i] != b.second[j]) {
return a.second[i] < b.second[j];
}
i++; j++;
}
return i == al;
}
return a.first > b.first;
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> m;
for (auto word : words) {
m[word]++;
}
priority_queue<pair<int, string>, vector<pair<int, string>>, cmp> q;
for (auto p : m) {
q.push(pair<int, string>(p.second, p.first));
if (q.size() > k) {
q.pop();
}
}
vector<string> res;
while (!q.empty()) {
res.push_back(q.top().second);
q.pop();
}
reverse(res.begin(), res.end());
return res;
}
};
| 27 | 77 | 0.421517 | [
"vector"
] |
332bdd21c36ff618fca03d661f8a58b17efd5f1b | 10,819 | cpp | C++ | src/components/performance_counters/papi/server/papi.cpp | brycelelbach/hpx | 94582f5dc26e889cdcf80913975ff33b7f975285 | [
"BSL-1.0"
] | 3 | 2017-04-06T16:36:38.000Z | 2018-05-19T11:28:54.000Z | src/components/performance_counters/papi/server/papi.cpp | atrantan/hpx | 6c214b2f3e3fc58648513c9f1cfef37fde59333c | [
"BSL-1.0"
] | 1 | 2018-08-13T17:42:55.000Z | 2018-08-13T18:20:23.000Z | src/components/performance_counters/papi/server/papi.cpp | atrantan/hpx | 6c214b2f3e3fc58648513c9f1cfef37fde59333c | [
"BSL-1.0"
] | 2 | 2018-05-25T06:33:50.000Z | 2019-02-25T20:09:13.000Z | // Copyright (c) 2007-2011 Hartmut Kaiser
// Copyright (c) 2011-2012 Maciej Brodowicz
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <hpx/config.hpp>
#if defined(HPX_HAVE_PAPI)
#include <hpx/runtime.hpp>
#include <hpx/runtime/components/server/component.hpp>
#include <hpx/runtime/components/derived_component_factory.hpp>
#include <hpx/runtime/actions/continuation.hpp>
#include <hpx/util/thread_mapper.hpp>
#include <hpx/util/high_resolution_clock.hpp>
#include <hpx/components/performance_counters/papi/server/papi.hpp>
#include <hpx/components/performance_counters/papi/util/papi.hpp>
#include <hpx/exception.hpp>
#include <boost/format.hpp>
#include <boost/version.hpp>
#include <cstdint>
#include <functional>
#include <mutex>
#include <string>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
namespace papi_ns = hpx::performance_counters::papi;
typedef hpx::components::component<
papi_ns::server::papi_counter
> papi_counter_type;
HPX_REGISTER_DERIVED_COMPONENT_FACTORY_DYNAMIC(
papi_counter_type, papi_counter, "base_performance_counter");
///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace performance_counters { namespace papi { namespace server
{
#define NS_STR "hpx::performance_counters::papi::server::"
///////////////////////////////////////////////////////////////////////////
// static members
papi_counter_base::mutex_type papi_counter_base::base_mtx_;
papi_counter_base::ttable_type papi_counter_base::thread_state_;
using hpx::performance_counters::papi::util::papi_call;
///////////////////////////////////////////////////////////////////////////
// methods
thread_counters::thread_counters(std::uint32_t tix):
thread_index_(tix), evset_(PAPI_NULL)
{
char const *locstr =
"hpx::performance_counters::papi::server::thread_counters()";
hpx::util::thread_mapper& tm =
hpx::get_runtime().get_thread_mapper();
papi_call(PAPI_create_eventset(&evset_),
"could not create PAPI event set", locstr);
papi_call(PAPI_assign_eventset_component(evset_, 0),
"cannot assign component index to event set", locstr);
long tid = tm.get_thread_id(tix);
if (tid == tm.invalid_tid)
HPX_THROW_EXCEPTION(hpx::bad_parameter,
NS_STR "thread_counters::thread_counters()",
"unable to retrieve correct OS thread ID for profiling "
"(perhaps thread was not registered)");
papi_call(PAPI_attach(evset_, tm.get_thread_id(tix)),
"failed to attach thread to PAPI event set", locstr);
tm.register_callback(tix,
std::bind1st(std::mem_fun(&thread_counters::terminate), this));
}
thread_counters::~thread_counters()
{
{
std::lock_guard<mutex_type> m(mtx_);
finalize();
}
// callback cancellation moved outside the mutex to avoid potential deadlock
hpx::get_runtime().get_thread_mapper().revoke_callback(thread_index_);
}
bool thread_counters::add_event(papi_counter *cnt)
{
stop_all();
if (PAPI_add_event(evset_, cnt->get_event()) != PAPI_OK)
return false;
counts_.push_back(cnt->get_value());
cnttab_.push_back(cnt);
cnt->update_index(counts_.size()-1);
return start_all();
}
bool thread_counters::remove_event(papi_counter *cnt)
{
if (!stop_all() || PAPI_cleanup_eventset(evset_) != PAPI_OK)
return false;
// store the most recent value
int rmix = cnt->get_counter_index();
cnt->update_state(timestamp_, counts_[rmix], PAPI_COUNTER_STOPPED);
// erase entries corresponding to removed event
counts_.erase(counts_.begin()+rmix);
cnttab_.erase(cnttab_.begin()+rmix);
// For the lack of better strategy the remaining events are added in the
// same order as before. This avoids reordering of remaining counter
// values and at least some surprises on architectures with asymmetric
// functionality of counting registers.
unsigned i = 0;
while (i < counts_.size())
{
papi_counter *c = cnttab_[i];
if (PAPI_add_event(evset_, c->get_event()) != PAPI_OK)
{ // failed to add event
c->update_state(timestamp_, counts_[c->get_counter_index()],
PAPI_COUNTER_SUSPENDED);
counts_.erase(counts_.begin()+i);
cnttab_.erase(cnttab_.begin()+i);
continue;
}
// update indices of remaining counters
c->update_index(i++);
}
return start_all();
}
bool thread_counters::read_value(papi_counter *cnt, bool reset)
{
{
std::lock_guard<papi_counter_base::mutex_type> lk(cnt->get_global_mtx());
if (PAPI_accum(evset_, &counts_[0]) != PAPI_OK) return false;
}
timestamp_ = static_cast<std::int64_t>(hpx::get_system_uptime());
cnt->update_state(timestamp_, counts_[cnt->get_counter_index()]);
if (reset) counts_[cnt->get_counter_index()] = 0;
return true;
}
bool thread_counters::terminate(std::uint32_t tix)
{
std::lock_guard<mutex_type> m(mtx_);
return finalize();
}
bool thread_counters::start_all()
{
if (counts_.empty()) return true; // nothing to count
return PAPI_start(evset_) == PAPI_OK;
}
bool thread_counters::stop_all()
{
int stat;
if (PAPI_state(evset_, &stat) != PAPI_OK) return false;
if ((stat & PAPI_RUNNING) != 0)
{
std::vector<long long> tmp(counts_.size());
if (PAPI_stop(evset_, &tmp[0]) != PAPI_OK) return false;
// accumulate existing counts before modifying event set
if (PAPI_accum(evset_, &counts_[0]) != PAPI_OK) return false;
timestamp_ = static_cast<std::int64_t>(hpx::get_system_uptime());
}
return true;
}
bool thread_counters::finalize()
{
if (evset_ != PAPI_NULL)
{
if (stop_all())
{
for (std::uint32_t i = 0; i < cnttab_.size(); ++i)
{ // retrieve the most recent values for the still active counters
papi_counter *c = cnttab_[i];
if (c->get_status() == PAPI_COUNTER_ACTIVE)
c->update_state(timestamp_, counts_[i], PAPI_COUNTER_TERMINATED);
else c->update_status(PAPI_COUNTER_TERMINATED);
}
}
// release event set resources
return PAPI_destroy_eventset(&evset_) == PAPI_OK;
}
return true;
}
///////////////////////////////////////////////////////////////////////////
thread_counters *papi_counter_base::get_thread_counters(std::uint32_t tix)
{
std::lock_guard<mutex_type> m(base_mtx_);
// create entry for the thread associated with the counter if it doesn't exist
ttable_type::iterator it = thread_state_.find(tix);
if (it == thread_state_.end())
return thread_state_[tix] = new thread_counters(tix);
else
return it->second;
}
///////////////////////////////////////////////////////////////////////////
papi_counter::papi_counter(hpx::performance_counters::counter_info const& info):
base_type_holder(info), event_(PAPI_NULL), index_(-1),
value_(0), timestamp_(-1), status_(PAPI_COUNTER_STOPPED)
{
char const *locstr = NS_STR "papi_counter()";
// extract path elements from counter name
counter_path_elements cpe;
get_counter_path_elements(info.fullname_, cpe);
// convert event name to code and check availability
{
std::lock_guard<papi_counter_base::mutex_type> lk(this->get_global_mtx());
papi_call(PAPI_event_name_to_code(
const_cast<char *>(cpe.countername_.c_str()),
const_cast<int *>(&event_)),
cpe.countername_+" does not seem to be a valid event name",
locstr);
papi_call(
PAPI_query_event(event_),
"event "+cpe.countername_+" is not available on this platform",
locstr);
}
// find OS thread associated with the counter
std::string label;
std::uint32_t tix = util::get_counter_thread(cpe, label);
if (tix == hpx::util::thread_mapper::invalid_index)
{
HPX_THROW_EXCEPTION(hpx::no_success, locstr,
"could not find thread "+label);
}
// associate low level counters object
counters_ = get_thread_counters(tix);
if (!counters_)
{
HPX_THROW_EXCEPTION(hpx::no_success, locstr,
"failed to find low level counters for thread "+label);
}
// counting is not enabled here; it has to be started explicitly
}
hpx::performance_counters::counter_value papi_counter::get_counter_value(bool reset)
{
std::lock_guard<thread_counters::mutex_type> m(counters_->get_lock());
if (status_ == PAPI_COUNTER_ACTIVE)
counters_->read_value(this, reset);
hpx::performance_counters::counter_value value;
if (timestamp_ != -1) copy_value(value);
else value.status_ = hpx::performance_counters::status_invalid_data;
// clear local copy
if (reset) value_ = 0;
value.count_ = ++invocation_count_;
return value;
}
bool papi_counter::start()
{
std::lock_guard<papi_counter_base::mutex_type> lk(get_global_mtx());
if (status_ == PAPI_COUNTER_ACTIVE) return true;
if (counters_->add_event(this))
{
status_ = PAPI_COUNTER_ACTIVE;
return true;
}
status_ = PAPI_COUNTER_SUSPENDED;
return false;
}
bool papi_counter::stop()
{
std::lock_guard<thread_counters::mutex_type> m(counters_->get_lock());
return stop_counter();
}
void papi_counter::reset()
{
std::lock_guard<thread_counters::mutex_type> m(counters_->get_lock());
reset_counter();
}
void papi_counter::finalize()
{
std::lock_guard<thread_counters::mutex_type> m(counters_->get_lock());
stop_counter();
base_type_holder::finalize();
base_type::finalize();
}
}}}}
#endif
| 35.241042 | 89 | 0.59377 | [
"object",
"vector"
] |
332ccfde3f0527a08862f66a4d36da4b3e0bda48 | 22,524 | cpp | C++ | dbms/src/Storages/AlterCommands.cpp | vicdashkov/ClickHouse | 3d604357008150d91314120730691c5795cd7d65 | [
"Apache-2.0"
] | null | null | null | dbms/src/Storages/AlterCommands.cpp | vicdashkov/ClickHouse | 3d604357008150d91314120730691c5795cd7d65 | [
"Apache-2.0"
] | null | null | null | dbms/src/Storages/AlterCommands.cpp | vicdashkov/ClickHouse | 3d604357008150d91314120730691c5795cd7d65 | [
"Apache-2.0"
] | null | null | null | #include <Storages/AlterCommands.h>
#include <Storages/IStorage.h>
#include <DataTypes/DataTypeFactory.h>
#include <DataTypes/DataTypesNumber.h>
#include <DataTypes/NestedUtils.h>
#include <Interpreters/Context.h>
#include <Interpreters/SyntaxAnalyzer.h>
#include <Interpreters/ExpressionAnalyzer.h>
#include <Interpreters/ExpressionActions.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTAlterQuery.h>
#include <Parsers/ASTColumnDeclaration.h>
#include <Common/typeid_cast.h>
namespace DB
{
namespace ErrorCodes
{
extern const int ILLEGAL_COLUMN;
extern const int BAD_ARGUMENTS;
extern const int LOGICAL_ERROR;
}
std::optional<AlterCommand> AlterCommand::parse(const ASTAlterCommand * command_ast)
{
const DataTypeFactory & data_type_factory = DataTypeFactory::instance();
if (command_ast->type == ASTAlterCommand::ADD_COLUMN)
{
AlterCommand command;
command.type = AlterCommand::ADD_COLUMN;
const auto & ast_col_decl = typeid_cast<const ASTColumnDeclaration &>(*command_ast->col_decl);
command.column_name = ast_col_decl.name;
if (ast_col_decl.type)
{
command.data_type = data_type_factory.get(ast_col_decl.type);
}
if (ast_col_decl.default_expression)
{
command.default_kind = columnDefaultKindFromString(ast_col_decl.default_specifier);
command.default_expression = ast_col_decl.default_expression;
}
if (command_ast->column)
command.after_column = typeid_cast<const ASTIdentifier &>(*command_ast->column).name;
command.if_not_exists = command_ast->if_not_exists;
return command;
}
else if (command_ast->type == ASTAlterCommand::DROP_COLUMN && !command_ast->partition)
{
if (command_ast->clear_column)
throw Exception("\"ALTER TABLE table CLEAR COLUMN column\" queries are not supported yet. Use \"CLEAR COLUMN column IN PARTITION\".", ErrorCodes::NOT_IMPLEMENTED);
AlterCommand command;
command.type = AlterCommand::DROP_COLUMN;
command.column_name = typeid_cast<const ASTIdentifier &>(*(command_ast->column)).name;
command.if_exists = command_ast->if_exists;
return command;
}
else if (command_ast->type == ASTAlterCommand::MODIFY_COLUMN)
{
AlterCommand command;
command.type = AlterCommand::MODIFY_COLUMN;
const auto & ast_col_decl = typeid_cast<const ASTColumnDeclaration &>(*command_ast->col_decl);
command.column_name = ast_col_decl.name;
if (ast_col_decl.type)
{
command.data_type = data_type_factory.get(ast_col_decl.type);
}
if (ast_col_decl.default_expression)
{
command.default_kind = columnDefaultKindFromString(ast_col_decl.default_specifier);
command.default_expression = ast_col_decl.default_expression;
}
if (ast_col_decl.comment)
{
const auto & ast_comment = typeid_cast<ASTLiteral &>(*ast_col_decl.comment);
command.comment = ast_comment.value.get<String>();
}
command.if_exists = command_ast->if_exists;
return command;
}
else if (command_ast->type == ASTAlterCommand::COMMENT_COLUMN)
{
AlterCommand command;
command.type = COMMENT_COLUMN;
const auto & ast_identifier = typeid_cast<ASTIdentifier &>(*command_ast->column);
command.column_name = ast_identifier.name;
const auto & ast_comment = typeid_cast<ASTLiteral &>(*command_ast->comment);
command.comment = ast_comment.value.get<String>();
command.if_exists = command_ast->if_exists;
return command;
}
else if (command_ast->type == ASTAlterCommand::MODIFY_ORDER_BY)
{
AlterCommand command;
command.type = AlterCommand::MODIFY_ORDER_BY;
command.order_by = command_ast->order_by;
return command;
}
else
return {};
}
/// the names are the same if they match the whole name or name_without_dot matches the part of the name up to the dot
static bool namesEqual(const String & name_without_dot, const DB::NameAndTypePair & name_type)
{
String name_with_dot = name_without_dot + ".";
return (name_with_dot == name_type.name.substr(0, name_without_dot.length() + 1) || name_without_dot == name_type.name);
}
void AlterCommand::apply(ColumnsDescription & columns_description, ASTPtr & order_by_ast, ASTPtr & primary_key_ast) const
{
if (type == ADD_COLUMN)
{
if (columns_description.getAll().contains(column_name))
throw Exception{"Cannot add column " + column_name + ": column with this name already exists", ErrorCodes::ILLEGAL_COLUMN};
const auto add_column = [this] (NamesAndTypesList & columns)
{
auto insert_it = columns.end();
if (!after_column.empty())
{
/// We are trying to find first column from end with name `column_name` or with a name beginning with `column_name` and ".".
/// For example "fruits.bananas"
/// names are considered the same if they completely match or `name_without_dot` matches the part of the name to the point
const auto reverse_insert_it = std::find_if(columns.rbegin(), columns.rend(),
std::bind(namesEqual, std::cref(after_column), std::placeholders::_1));
if (reverse_insert_it == columns.rend())
throw Exception("Wrong column name. Cannot find column " + after_column + " to insert after",
ErrorCodes::ILLEGAL_COLUMN);
else
{
/// base returns an iterator that is already offset by one element to the right
insert_it = reverse_insert_it.base();
}
}
columns.emplace(insert_it, column_name, data_type);
};
if (default_kind == ColumnDefaultKind::Default)
add_column(columns_description.ordinary);
else if (default_kind == ColumnDefaultKind::Materialized)
add_column(columns_description.materialized);
else if (default_kind == ColumnDefaultKind::Alias)
add_column(columns_description.aliases);
else
throw Exception{"Unknown ColumnDefaultKind value", ErrorCodes::LOGICAL_ERROR};
if (default_expression)
columns_description.defaults.emplace(column_name, ColumnDefault{default_kind, default_expression});
/// Slow, because each time a list is copied
columns_description.ordinary = Nested::flatten(columns_description.ordinary);
}
else if (type == DROP_COLUMN)
{
/// look for a column in list and remove it if present, also removing corresponding entry from column_defaults
const auto remove_column = [&columns_description, this] (NamesAndTypesList & columns)
{
auto removed = false;
NamesAndTypesList::iterator column_it;
while (columns.end() != (column_it = std::find_if(columns.begin(), columns.end(),
std::bind(namesEqual, std::cref(column_name), std::placeholders::_1))))
{
removed = true;
column_it = columns.erase(column_it);
columns_description.defaults.erase(column_name);
}
return removed;
};
if (!remove_column(columns_description.ordinary) &&
!remove_column(columns_description.materialized) &&
!remove_column(columns_description.aliases))
{
throw Exception("Wrong column name. Cannot find column " + column_name + " to drop",
ErrorCodes::ILLEGAL_COLUMN);
}
}
else if (type == MODIFY_COLUMN)
{
if (!is_mutable())
{
auto & comments = columns_description.comments;
if (comment.empty())
{
if (auto it = comments.find(column_name); it != comments.end())
comments.erase(it);
}
else
columns_description.comments[column_name] = comment;
return;
}
const auto default_it = columns_description.defaults.find(column_name);
const auto had_default_expr = default_it != std::end(columns_description.defaults);
const auto old_default_kind = had_default_expr ? default_it->second.kind : ColumnDefaultKind{};
/// target column list
auto & new_columns =
default_kind == ColumnDefaultKind::Default ? columns_description.ordinary
: default_kind == ColumnDefaultKind::Materialized ? columns_description.materialized
: columns_description.aliases;
/// find column or throw exception
const auto find_column = [this] (NamesAndTypesList & columns)
{
const auto it = std::find_if(columns.begin(), columns.end(),
std::bind(namesEqual, std::cref(column_name), std::placeholders::_1));
if (it == columns.end())
throw Exception("Wrong column name. Cannot find column " + column_name + " to modify",
ErrorCodes::ILLEGAL_COLUMN);
return it;
};
/// if default types differ, remove column from the old list, then add to the new list
if (default_kind != old_default_kind)
{
/// source column list
auto & old_columns =
old_default_kind == ColumnDefaultKind::Default ? columns_description.ordinary
: old_default_kind == ColumnDefaultKind::Materialized ? columns_description.materialized
: columns_description.aliases;
const auto old_column_it = find_column(old_columns);
new_columns.emplace_back(*old_column_it);
old_columns.erase(old_column_it);
/// do not forget to change the default type of old column
if (had_default_expr)
columns_description.defaults[column_name].kind = default_kind;
}
/// find column in one of three column lists
const auto column_it = find_column(new_columns);
column_it->type = data_type;
if (!default_expression && had_default_expr)
/// new column has no default expression, remove it from column_defaults along with it's type
columns_description.defaults.erase(column_name);
else if (default_expression && !had_default_expr)
/// new column has a default expression while the old one had not, add it it column_defaults
columns_description.defaults.emplace(column_name, ColumnDefault{default_kind, default_expression});
else if (had_default_expr)
/// both old and new columns have default expression, update it
columns_description.defaults[column_name].expression = default_expression;
}
else if (type == MODIFY_ORDER_BY)
{
if (!primary_key_ast)
{
/// Primary and sorting key become independent after this ALTER so we have to
/// save the old ORDER BY expression as the new primary key.
primary_key_ast = order_by_ast->clone();
}
order_by_ast = order_by;
}
else if (type == COMMENT_COLUMN)
{
columns_description.comments[column_name] = comment;
}
else
throw Exception("Wrong parameter type in ALTER query", ErrorCodes::LOGICAL_ERROR);
}
bool AlterCommand::is_mutable() const
{
if (type == COMMENT_COLUMN)
return false;
if (type == MODIFY_COLUMN)
return data_type.get() || default_expression;
// TODO: возможно, здесь нужно дополнить
return true;
}
void AlterCommands::apply(ColumnsDescription & columns_description, ASTPtr & order_by_ast, ASTPtr & primary_key_ast) const
{
auto new_columns_description = columns_description;
auto new_order_by_ast = order_by_ast;
auto new_primary_key_ast = primary_key_ast;
for (const AlterCommand & command : *this)
if (!command.ignore)
command.apply(new_columns_description, new_order_by_ast, new_primary_key_ast);
columns_description = std::move(new_columns_description);
order_by_ast = std::move(new_order_by_ast);
primary_key_ast = std::move(new_primary_key_ast);
}
void AlterCommands::validate(const IStorage & table, const Context & context)
{
auto all_columns = table.getColumns().getAll();
auto defaults = table.getColumns().defaults;
std::vector<std::pair<NameAndTypePair, AlterCommand *>> defaulted_columns{};
auto default_expr_list = std::make_shared<ASTExpressionList>();
default_expr_list->children.reserve(defaults.size());
for (AlterCommand & command : *this)
{
if (command.type == AlterCommand::ADD_COLUMN || command.type == AlterCommand::MODIFY_COLUMN)
{
const auto & column_name = command.column_name;
const auto column_it = std::find_if(std::begin(all_columns), std::end(all_columns),
std::bind(namesEqual, std::cref(command.column_name), std::placeholders::_1));
if (command.type == AlterCommand::ADD_COLUMN)
{
if (std::end(all_columns) != column_it)
{
if (command.if_not_exists)
command.ignore = true;
else
throw Exception{"Cannot add column " + column_name + ": column with this name already exists", ErrorCodes::ILLEGAL_COLUMN};
}
}
else if (command.type == AlterCommand::MODIFY_COLUMN)
{
if (std::end(all_columns) == column_it)
{
if (command.if_exists)
command.ignore = true;
else
throw Exception{"Wrong column name. Cannot find column " + column_name + " to modify", ErrorCodes::ILLEGAL_COLUMN};
}
if (!command.ignore)
{
all_columns.erase(column_it);
defaults.erase(column_name);
}
}
if (!command.ignore)
{
/// we're creating dummy DataTypeUInt8 in order to prevent the NullPointerException in ExpressionActions
all_columns.emplace_back(column_name, command.data_type ? command.data_type : std::make_shared<DataTypeUInt8>());
if (command.default_expression)
{
if (command.data_type)
{
const auto &final_column_name = column_name;
const auto tmp_column_name = final_column_name + "_tmp";
const auto column_type_raw_ptr = command.data_type.get();
default_expr_list->children.emplace_back(setAlias(
makeASTFunction("CAST", std::make_shared<ASTIdentifier>(tmp_column_name),
std::make_shared<ASTLiteral>(column_type_raw_ptr->getName())),
final_column_name));
default_expr_list->children.emplace_back(setAlias(command.default_expression->clone(), tmp_column_name));
defaulted_columns.emplace_back(NameAndTypePair{column_name, command.data_type}, &command);
}
else
{
/// no type explicitly specified, will deduce later
default_expr_list->children.emplace_back(
setAlias(command.default_expression->clone(), column_name));
defaulted_columns.emplace_back(NameAndTypePair{column_name, nullptr}, &command);
}
}
}
}
else if (command.type == AlterCommand::DROP_COLUMN)
{
for (const auto & default_column : defaults)
{
const auto & default_expression = default_column.second.expression;
ASTPtr query = default_expression;
auto syntax_result = SyntaxAnalyzer(context, {}).analyze(query, all_columns);
const auto actions = ExpressionAnalyzer(query, syntax_result, context).getActions(true);
const auto required_columns = actions->getRequiredColumns();
if (required_columns.end() != std::find(required_columns.begin(), required_columns.end(), command.column_name))
throw Exception(
"Cannot drop column " + command.column_name + ", because column " + default_column.first +
" depends on it", ErrorCodes::ILLEGAL_COLUMN);
}
auto found = false;
for (auto it = std::begin(all_columns); it != std::end(all_columns);)
{
if (namesEqual(command.column_name, *it))
{
found = true;
it = all_columns.erase(it);
}
else
++it;
}
for (auto it = std::begin(defaults); it != std::end(defaults);)
{
if (namesEqual(command.column_name, { it->first, nullptr }))
it = defaults.erase(it);
else
++it;
}
if (!found)
{
if (command.if_exists)
command.ignore = true;
else
throw Exception("Wrong column name. Cannot find column " + command.column_name + " to drop",
ErrorCodes::ILLEGAL_COLUMN);
}
}
else if (command.type == AlterCommand::COMMENT_COLUMN)
{
const auto column_it = std::find_if(std::begin(all_columns), std::end(all_columns),
std::bind(namesEqual, std::cref(command.column_name), std::placeholders::_1));
if (column_it == std::end(all_columns))
{
if (command.if_exists)
command.ignore = true;
else
throw Exception{"Wrong column name. Cannot find column " + command.column_name + " to comment", ErrorCodes::ILLEGAL_COLUMN};
}
}
}
/** Existing defaulted columns may require default expression extensions with a type conversion,
* therefore we add them to defaulted_columns to allow further processing */
for (const auto & col_def : defaults)
{
const auto & column_name = col_def.first;
const auto column_it = std::find_if(all_columns.begin(), all_columns.end(), [&] (const NameAndTypePair & name_type)
{ return namesEqual(column_name, name_type); });
const auto tmp_column_name = column_name + "_tmp";
const auto & column_type_ptr = column_it->type;
default_expr_list->children.emplace_back(setAlias(
makeASTFunction("CAST", std::make_shared<ASTIdentifier>(tmp_column_name),
std::make_shared<ASTLiteral>(column_type_ptr->getName())),
column_name));
default_expr_list->children.emplace_back(setAlias(col_def.second.expression->clone(), tmp_column_name));
defaulted_columns.emplace_back(NameAndTypePair{column_name, column_type_ptr}, nullptr);
}
ASTPtr query = default_expr_list;
auto syntax_result = SyntaxAnalyzer(context, {}).analyze(query, all_columns);
const auto actions = ExpressionAnalyzer(query, syntax_result, context).getActions(true);
const auto block = actions->getSampleBlock();
/// set deduced types, modify default expression if necessary
for (auto & defaulted_column : defaulted_columns)
{
const auto & name_and_type = defaulted_column.first;
AlterCommand * & command_ptr = defaulted_column.second;
const auto & column_name = name_and_type.name;
const auto has_explicit_type = nullptr != name_and_type.type;
/// default expression on old column
if (has_explicit_type)
{
const auto & explicit_type = name_and_type.type;
const auto & tmp_column = block.getByName(column_name + "_tmp");
const auto & deduced_type = tmp_column.type;
// column not specified explicitly in the ALTER query may require default_expression modification
if (!explicit_type->equals(*deduced_type))
{
const auto default_it = defaults.find(column_name);
/// column has no associated alter command, let's create it
if (!command_ptr)
{
/// add a new alter command to modify existing column
this->emplace_back(AlterCommand{
AlterCommand::MODIFY_COLUMN, column_name, explicit_type,
default_it->second.kind, default_it->second.expression
});
command_ptr = &this->back();
}
command_ptr->default_expression = makeASTFunction("CAST", command_ptr->default_expression->clone(),
std::make_shared<ASTLiteral>(explicit_type->getName()));
}
}
else
{
/// just set deduced type
command_ptr->data_type = block.getByName(column_name).type;
}
}
}
void AlterCommands::apply(ColumnsDescription & columns_description) const
{
auto out_columns_description = columns_description;
ASTPtr out_order_by;
ASTPtr out_primary_key;
apply(out_columns_description, out_order_by, out_primary_key);
if (out_order_by)
throw Exception("Storage doesn't support modifying ORDER BY expression", ErrorCodes::NOT_IMPLEMENTED);
if (out_primary_key)
throw Exception("Storage doesn't support modifying PRIMARY KEY expression", ErrorCodes::NOT_IMPLEMENTED);
columns_description = std::move(out_columns_description);
}
bool AlterCommands::is_mutable() const
{
for (const auto & param : *this)
{
if (param.is_mutable())
return true;
}
return false;
}
}
| 40.804348 | 175 | 0.613523 | [
"vector"
] |
33313ff72b3d7b024468530abf1974f010249730 | 4,697 | cpp | C++ | Google/HashCode/E.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | 2 | 2018-12-11T14:37:24.000Z | 2022-01-23T18:11:54.000Z | Google/HashCode/E.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | Google/HashCode/E.cpp | Mindjolt2406/Competitive-Programming | d000d98bf7005ee4fb809bcea2f110e4c4793b80 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define mt make_tuple
#define mp make_pair
#define pu push_back
#define INF 1000000001
#define MOD 1000000007
#define EPS 1e-6
#define ll long long int
#define ld long double
#define fi first
#define se second
#define all(v) v.begin(),v.end()
#define pr(v) { for(int i=0;i<v.size();i++) { v[i]==INF? cout<<"INF " : cout<<v[i]<<" "; } cout<<endl;}
#define t1(x) cerr<<#x<<" : "<<x<<endl
#define t2(x, y) cerr<<#x<<" : "<<x<<" "<<#y<<" : "<<y<<endl
#define t3(x, y, z) cerr<<#x<<" : " <<x<<" "<<#y<<" : "<<y<<" "<<#z<<" : "<<z<<endl
#define t4(a,b,c,d) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<endl
#define t5(a,b,c,d,e) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<endl
#define t6(a,b,c,d,e,f) cerr<<#a<<" : "<<a<<" "<<#b<<" : "<<b<<" "<<#c<<" : "<<c<<" "<<#d<<" : "<<d<<" "<<#e<<" : "<<e<<" "<<#f<<" : "<<f<<endl
#define GET_MACRO(_1,_2,_3,_4,_5,_6,NAME,...) NAME
#define t(...) GET_MACRO(__VA_ARGS__,t6,t5, t4, t3, t2, t1)(__VA_ARGS__)
#define _ cerr<<"here"<<endl;
#define __ {ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);}
using namespace std;
template<class A, class B> ostream& operator<<(ostream& out, const pair<A, B> &a){ return out<<"("<<a.first<<", "<<a.second<<")";}
template <int> ostream& operator<<(ostream& os, const vector<int>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { if(v[i]!=INF) os << v[i]; else os << "INF";if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; }
template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { os << "["; for (int i = 0; i < v.size(); ++i) { os << v[i]; ;if (i != v.size() - 1) os << ", "; } os << "]\n"; return os; }
void B()
{
}
int main()
{
__;
int n_books, n_lib, days;
cin >> n_books >> n_lib >> days;
// Check various conditions
set<int> diff_books;
vector<int> book_freq(n_books);
// ----------------
vector<vector<int> > library(n_lib);
vector<vector<int> > book_lib(n_books);
vector<int> book_score(n_books);
// < signup, scan/day , index>
vector<vector<int> > lib_info(n_lib);
int max_score = 0;
for(int i=0;i<n_books;i++) {cin >> book_score[i]; max_score += book_score[i];}
for(int i=0;i<n_lib;i++)
{
int n,signup,scan;
cin >> n >> signup >> scan;
lib_info[i] = {signup,scan,i,n};
for(int j=0;j<n;j++)
{
int temp;
cin >> temp;
library[i].push_back(temp);
book_lib[temp].pu(i);
}
}
for(int i=0;i<n_lib;i++)
{
vector<pair<int,int> > lib_i;
for(int j=0;j<library[i].size();j++)
{
lib_i.pu(mp(book_score[library[i][j]],library[i][j]));
}
sort(lib_i.begin(),lib_i.end());
reverse(lib_i.begin(),lib_i.end());
for(int j=0;j<library[i].size();j++)
{
library[i][j] = lib_i[j].se;
}
}
// int max1 = 0;
int score = 0;
vector<bool> taken(n_books),taken2(n_books);
vector<vector<int> > lib_ans(n_lib);
set<int> taken_lib;
int cnt = 0;
vector<pair<int,int> > best;
for(int i=0;i<n_lib;i++)
{
// t(i);
bool thi = false;
if(lib_info[i][0] == 1)
{
int temp_score = 0;
for(int j=0;j<library[i].size();j++)
{
if(!taken[library[i][j]])
{
thi = true;
temp_score += book_score[library[i][j]];
lib_ans[i].pu(library[i][j]);
taken_lib.insert(i);
taken[library[i][j]] = true;
}
}
if(thi)
{
cnt += lib_info[i][0];
score += temp_score;
}
}
else if(lib_info[i][0] == 2)
{
int temp_score = 0;
for(int j=0;j<library[i].size();j++)
{
if(!taken[library[i][j]])
{
thi = true;
temp_score += book_score[library[i][j]];
taken[library[i][j]] = true;
}
}
if(thi)
{
best.pu(mp(temp_score,i));
}
}
// _;
}
// _;
sort(best.begin(),best.end());
reverse(best.begin(),best.end());
for(int i=0;i<min((int)best.size(),44);i++)
{
score += best[i].fi;
cnt += 2;
taken_lib.insert(best[i].se);
}
t(score,max_score,cnt);
cout << taken_lib.size() << endl;
int score_ans = 0;
for(int i=0;i<n_lib;i++)
{
if(taken_lib.count(i))
{
cout << i << " " << library[i].size() << endl;
for(int j=0;j<library[i].size();j++)
{
cout << library[i][j] << " ";
score_ans += book_score[library[i][j]];
}
cout << endl;
}
}
// int books_cnt = 0;
// for(int i=0;i<taken2.size();i++) if(taken2[i]) books_cnt++;
return 0;
}
| 26.240223 | 226 | 0.491803 | [
"vector"
] |
333386c7d5e16bbb1c08f625c278e395326afee2 | 3,860 | cc | C++ | engine/source/io/fileStreamObject.cc | odaymichael/Torque2D | 43d5fbaa0719e0f29825975a582ea4fa479896af | [
"MIT"
] | 1 | 2016-12-23T13:04:08.000Z | 2016-12-23T13:04:08.000Z | engine/source/io/fileStreamObject.cc | odaymichael/Torque2D | 43d5fbaa0719e0f29825975a582ea4fa479896af | [
"MIT"
] | null | null | null | engine/source/io/fileStreamObject.cc | odaymichael/Torque2D | 43d5fbaa0719e0f29825975a582ea4fa479896af | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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 "console/console.h"
#include "fileStreamObject.h"
//////////////////////////////////////////////////////////////////////////
// Local Globals
//////////////////////////////////////////////////////////////////////////
static const struct
{
const char *strMode;
FileStream::AccessMode mode;
} gModeMap[]=
{
{ "read", FileStream::Read },
{ "write", FileStream::Write },
{ "readwrite", FileStream::ReadWrite },
{ "writeappend", FileStream::WriteAppend },
{ NULL, (FileStream::AccessMode)0 }
};
//////////////////////////////////////////////////////////////////////////
// Constructor/Destructor
//////////////////////////////////////////////////////////////////////////
FileStreamObject::FileStreamObject()
{
}
FileStreamObject::~FileStreamObject()
{
close();
}
IMPLEMENT_CONOBJECT(FileStreamObject);
//////////////////////////////////////////////////////////////////////////
bool FileStreamObject::onAdd()
{
// [tom, 2/12/2007] Skip over StreamObject's onAdd() so that we can
// be instantiated from script.
return SimObject::onAdd();
}
//////////////////////////////////////////////////////////////////////////
// Public Methods
//////////////////////////////////////////////////////////////////////////
bool FileStreamObject::open(const char *filename, FileStream::AccessMode mode)
{
close();
if(! mFileStream.open(filename, mode))
return false;
mStream = &mFileStream;
return true;
}
void FileStreamObject::close()
{
mFileStream.close();
mStream = NULL;
}
//////////////////////////////////////////////////////////////////////////
// Console Methods
//////////////////////////////////////////////////////////////////////////
ConsoleMethod(FileStreamObject, open, bool, 4, 4, "(filename, mode) Open a file. Mode can be one of Read, Write, ReadWrite or WriteAppend.")
{
FileStream::AccessMode mode;
bool found = false;
for(S32 i = 0;gModeMap[i].strMode;++i)
{
if(dStricmp(gModeMap[i].strMode, argv[3]) == 0)
{
mode = gModeMap[i].mode;
found = true;
break;
}
}
if(! found)
{
Con::errorf("FileStreamObject::open - Mode must be one of Read, Write, ReadWrite or WriteAppend.");
return false;
}
char buffer[1024];
Con::expandPath(buffer, sizeof(buffer), argv[2]);
return object->open(buffer, mode);
}
ConsoleMethod(FileStreamObject, close, void, 2, 2, "() Close the file.")
{
object->close();
}
| 31.900826 | 141 | 0.523575 | [
"object"
] |
3333f03386ea73ac9c23c2f302a34fbf1b2d56c1 | 25,271 | cc | C++ | examples/pxScene2d/external/libnode-v8.9.4/src/string_bytes.cc | maciej-barczak-red/pxCore | a4c320cfa0f8c5629d7de34ddb2c393b18ac2a50 | [
"Apache-2.0"
] | 2 | 2019-08-12T16:00:15.000Z | 2020-08-29T15:39:23.000Z | examples/pxScene2d/external/libnode-v8.9.4/src/string_bytes.cc | maciej-barczak-red/pxCore | a4c320cfa0f8c5629d7de34ddb2c393b18ac2a50 | [
"Apache-2.0"
] | 2 | 2019-03-22T11:02:32.000Z | 2019-04-05T19:03:41.000Z | node/src/string_bytes.cc | isabella232/node-packer | d9eb8414eb84984d75cd014f9735f8581859fafa | [
"MIT"
] | 1 | 2020-11-18T19:12:00.000Z | 2020-11-18T19:12:00.000Z | // Copyright Joyent, Inc. and other Node contributors.
//
// 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 "string_bytes.h"
#include "base64.h"
#include "node_internals.h"
#include "node_buffer.h"
#include <limits.h>
#include <string.h> // memcpy
#include <vector>
// When creating strings >= this length v8's gc spins up and consumes
// most of the execution time. For these cases it's more performant to
// use external string resources.
#define EXTERN_APEX 0xFBEE9
// TODO(addaleax): These should all have better error messages. In particular,
// they should mention what the actual limits are.
#define SB_MALLOC_FAILED_ERROR \
v8::Exception::Error(OneByteString(isolate, "\"toString()\" failed"))
#define SB_STRING_TOO_LONG_ERROR \
v8::Exception::Error(OneByteString(isolate, "\"toString()\" failed"))
#define SB_BUFFER_CREATION_ERROR \
v8::Exception::Error(OneByteString(isolate, "\"toString()\" failed"))
#define SB_BUFFER_SIZE_EXCEEDED_ERROR \
v8::Exception::Error(OneByteString(isolate, "\"toString()\" failed"))
namespace node {
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::String;
using v8::Value;
namespace {
template <typename ResourceType, typename TypeName>
class ExternString: public ResourceType {
public:
~ExternString() override {
free(const_cast<TypeName*>(data_));
isolate()->AdjustAmountOfExternalAllocatedMemory(-byte_length());
}
const TypeName* data() const override {
return data_;
}
size_t length() const override {
return length_;
}
int64_t byte_length() const {
return length() * sizeof(*data());
}
static MaybeLocal<Value> NewFromCopy(Isolate* isolate,
const TypeName* data,
size_t length,
Local<Value>* error) {
if (length == 0)
return String::Empty(isolate);
if (length < EXTERN_APEX)
return NewSimpleFromCopy(isolate, data, length, error);
TypeName* new_data = node::UncheckedMalloc<TypeName>(length);
if (new_data == nullptr) {
*error = SB_MALLOC_FAILED_ERROR;
return MaybeLocal<Value>();
}
memcpy(new_data, data, length * sizeof(*new_data));
return ExternString<ResourceType, TypeName>::New(isolate,
new_data,
length,
error);
}
// uses "data" for external resource, and will be free'd on gc
static MaybeLocal<Value> New(Isolate* isolate,
TypeName* data,
size_t length,
Local<Value>* error) {
if (length == 0)
return String::Empty(isolate);
if (length < EXTERN_APEX) {
MaybeLocal<Value> str = NewSimpleFromCopy(isolate, data, length, error);
free(data);
return str;
}
ExternString* h_str = new ExternString<ResourceType, TypeName>(isolate,
data,
length);
MaybeLocal<Value> str = NewExternal(isolate, h_str);
isolate->AdjustAmountOfExternalAllocatedMemory(h_str->byte_length());
if (str.IsEmpty()) {
delete h_str;
*error = SB_STRING_TOO_LONG_ERROR;
return MaybeLocal<Value>();
}
return str.ToLocalChecked();
}
inline Isolate* isolate() const { return isolate_; }
private:
ExternString(Isolate* isolate, const TypeName* data, size_t length)
: isolate_(isolate), data_(data), length_(length) { }
static MaybeLocal<Value> NewExternal(Isolate* isolate,
ExternString* h_str);
// This method does not actually create ExternString instances.
static MaybeLocal<Value> NewSimpleFromCopy(Isolate* isolate,
const TypeName* data,
size_t length,
Local<Value>* error);
Isolate* isolate_;
const TypeName* data_;
size_t length_;
};
typedef ExternString<String::ExternalOneByteStringResource,
char> ExternOneByteString;
typedef ExternString<String::ExternalStringResource,
uint16_t> ExternTwoByteString;
template <>
MaybeLocal<Value> ExternOneByteString::NewExternal(
Isolate* isolate, ExternOneByteString* h_str) {
return String::NewExternalOneByte(isolate, h_str).FromMaybe(Local<Value>());
}
template <>
MaybeLocal<Value> ExternTwoByteString::NewExternal(
Isolate* isolate, ExternTwoByteString* h_str) {
return String::NewExternalTwoByte(isolate, h_str).FromMaybe(Local<Value>());
}
template <>
MaybeLocal<Value> ExternOneByteString::NewSimpleFromCopy(Isolate* isolate,
const char* data,
size_t length,
Local<Value>* error) {
MaybeLocal<String> str =
String::NewFromOneByte(isolate,
reinterpret_cast<const uint8_t*>(data),
v8::NewStringType::kNormal,
length);
if (str.IsEmpty()) {
*error = SB_STRING_TOO_LONG_ERROR;
return MaybeLocal<Value>();
}
return str.ToLocalChecked();
}
template <>
MaybeLocal<Value> ExternTwoByteString::NewSimpleFromCopy(Isolate* isolate,
const uint16_t* data,
size_t length,
Local<Value>* error) {
MaybeLocal<String> str =
String::NewFromTwoByte(isolate,
data,
v8::NewStringType::kNormal,
length);
if (str.IsEmpty()) {
*error = SB_STRING_TOO_LONG_ERROR;
return MaybeLocal<Value>();
}
return str.ToLocalChecked();
}
} // anonymous namespace
// supports regular and URL-safe base64
const int8_t unbase64_table[256] =
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
static const int8_t unhex_table[256] =
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
static inline unsigned unhex(uint8_t x) {
return unhex_table[x];
}
template <typename TypeName>
static size_t hex_decode(char* buf,
size_t len,
const TypeName* src,
const size_t srcLen) {
size_t i;
for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) {
unsigned a = unhex(src[i * 2 + 0]);
unsigned b = unhex(src[i * 2 + 1]);
if (!~a || !~b)
return i;
buf[i] = (a << 4) | b;
}
return i;
}
bool StringBytes::GetExternalParts(Local<Value> val,
const char** data,
size_t* len) {
if (Buffer::HasInstance(val)) {
*data = Buffer::Data(val);
*len = Buffer::Length(val);
return true;
}
if (!val->IsString())
return false;
Local<String> str = val.As<String>();
if (str->IsExternalOneByte()) {
const String::ExternalOneByteStringResource* ext;
ext = str->GetExternalOneByteStringResource();
*data = ext->data();
*len = ext->length();
return true;
} else if (str->IsExternal()) {
const String::ExternalStringResource* ext;
ext = str->GetExternalStringResource();
*data = reinterpret_cast<const char*>(ext->data());
*len = ext->length() * sizeof(*ext->data());
return true;
}
return false;
}
size_t StringBytes::WriteUCS2(char* buf,
size_t buflen,
Local<String> str,
int flags,
size_t* chars_written) {
uint16_t* const dst = reinterpret_cast<uint16_t*>(buf);
size_t max_chars = (buflen / sizeof(*dst));
size_t nchars;
size_t alignment = reinterpret_cast<uintptr_t>(dst) % sizeof(*dst);
if (alignment == 0) {
nchars = str->Write(dst, 0, max_chars, flags);
*chars_written = nchars;
return nchars * sizeof(*dst);
}
uint16_t* aligned_dst =
reinterpret_cast<uint16_t*>(buf + sizeof(*dst) - alignment);
CHECK_EQ(reinterpret_cast<uintptr_t>(aligned_dst) % sizeof(*dst), 0);
// Write all but the last char
nchars = str->Write(aligned_dst, 0, max_chars - 1, flags);
// Shift everything to unaligned-left
memmove(dst, aligned_dst, nchars * sizeof(*dst));
// One more char to be written
uint16_t last;
if (nchars == max_chars - 1 && str->Write(&last, nchars, 1, flags) != 0) {
memcpy(buf + nchars * sizeof(*dst), &last, sizeof(last));
nchars++;
}
*chars_written = nchars;
return nchars * sizeof(*dst);
}
size_t StringBytes::Write(Isolate* isolate,
char* buf,
size_t buflen,
Local<Value> val,
enum encoding encoding,
int* chars_written) {
HandleScope scope(isolate);
const char* data = nullptr;
size_t nbytes = 0;
const bool is_extern = GetExternalParts(val, &data, &nbytes);
const size_t external_nbytes = nbytes;
CHECK(val->IsString() == true);
Local<String> str = val.As<String>();
if (nbytes > buflen)
nbytes = buflen;
int flags = String::HINT_MANY_WRITES_EXPECTED |
String::NO_NULL_TERMINATION |
String::REPLACE_INVALID_UTF8;
switch (encoding) {
case ASCII:
case LATIN1:
if (is_extern && str->IsOneByte()) {
memcpy(buf, data, nbytes);
} else {
uint8_t* const dst = reinterpret_cast<uint8_t*>(buf);
nbytes = str->WriteOneByte(dst, 0, buflen, flags);
}
if (chars_written != nullptr)
*chars_written = nbytes;
break;
case BUFFER:
case UTF8:
nbytes = str->WriteUtf8(buf, buflen, chars_written, flags);
break;
case UCS2: {
size_t nchars;
if (is_extern && !str->IsOneByte()) {
memcpy(buf, data, nbytes);
nchars = nbytes / sizeof(uint16_t);
} else {
nbytes = WriteUCS2(buf, buflen, str, flags, &nchars);
}
if (chars_written != nullptr)
*chars_written = nchars;
// Node's "ucs2" encoding wants LE character data stored in
// the Buffer, so we need to reorder on BE platforms. See
// http://nodejs.org/api/buffer.html regarding Node's "ucs2"
// encoding specification
if (IsBigEndian())
SwapBytes16(buf, nbytes);
break;
}
case BASE64:
if (is_extern) {
nbytes = base64_decode(buf, buflen, data, external_nbytes);
} else {
String::Value value(str);
nbytes = base64_decode(buf, buflen, *value, value.length());
}
if (chars_written != nullptr) {
*chars_written = nbytes;
}
break;
case HEX:
if (is_extern) {
nbytes = hex_decode(buf, buflen, data, external_nbytes);
} else {
String::Value value(str);
nbytes = hex_decode(buf, buflen, *value, value.length());
}
if (chars_written != nullptr) {
*chars_written = nbytes;
}
break;
default:
CHECK(0 && "unknown encoding");
break;
}
return nbytes;
}
bool StringBytes::IsValidString(Local<String> string,
enum encoding enc) {
if (enc == HEX && string->Length() % 2 != 0)
return false;
// TODO(bnoordhuis) Add BASE64 check?
return true;
}
// Quick and dirty size calculation
// Will always be at least big enough, but may have some extra
// UTF8 can be as much as 3x the size, Base64 can have 1-2 extra bytes
size_t StringBytes::StorageSize(Isolate* isolate,
Local<Value> val,
enum encoding encoding) {
HandleScope scope(isolate);
size_t data_size = 0;
bool is_buffer = Buffer::HasInstance(val);
if (is_buffer && (encoding == BUFFER || encoding == LATIN1)) {
return Buffer::Length(val);
}
Local<String> str = val->ToString(isolate);
switch (encoding) {
case ASCII:
case LATIN1:
data_size = str->Length();
break;
case BUFFER:
case UTF8:
// A single UCS2 codepoint never takes up more than 3 utf8 bytes.
// It is an exercise for the caller to decide when a string is
// long enough to justify calling Size() instead of StorageSize()
data_size = 3 * str->Length();
break;
case UCS2:
data_size = str->Length() * sizeof(uint16_t);
break;
case BASE64:
data_size = base64_decoded_size_fast(str->Length());
break;
case HEX:
CHECK(str->Length() % 2 == 0 && "invalid hex string length");
data_size = str->Length() / 2;
break;
default:
CHECK(0 && "unknown encoding");
break;
}
return data_size;
}
size_t StringBytes::Size(Isolate* isolate,
Local<Value> val,
enum encoding encoding) {
HandleScope scope(isolate);
size_t data_size = 0;
bool is_buffer = Buffer::HasInstance(val);
if (is_buffer && (encoding == BUFFER || encoding == LATIN1))
return Buffer::Length(val);
const char* data;
if (GetExternalParts(val, &data, &data_size))
return data_size;
Local<String> str = val->ToString(isolate);
switch (encoding) {
case ASCII:
case LATIN1:
data_size = str->Length();
break;
case BUFFER:
case UTF8:
data_size = str->Utf8Length();
break;
case UCS2:
data_size = str->Length() * sizeof(uint16_t);
break;
case BASE64: {
String::Value value(str);
data_size = base64_decoded_size(*value, value.length());
break;
}
case HEX:
data_size = str->Length() / 2;
break;
default:
CHECK(0 && "unknown encoding");
break;
}
return data_size;
}
static bool contains_non_ascii_slow(const char* buf, size_t len) {
for (size_t i = 0; i < len; ++i) {
if (buf[i] & 0x80)
return true;
}
return false;
}
static bool contains_non_ascii(const char* src, size_t len) {
if (len < 16) {
return contains_non_ascii_slow(src, len);
}
const unsigned bytes_per_word = sizeof(uintptr_t);
const unsigned align_mask = bytes_per_word - 1;
const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask;
if (unaligned > 0) {
const unsigned n = bytes_per_word - unaligned;
if (contains_non_ascii_slow(src, n))
return true;
src += n;
len -= n;
}
#if defined(_WIN64) || defined(_LP64)
const uintptr_t mask = 0x8080808080808080ll;
#else
const uintptr_t mask = 0x80808080l;
#endif
const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
if (srcw[i] & mask)
return true;
}
const unsigned remainder = len & align_mask;
if (remainder > 0) {
const size_t offset = len - remainder;
if (contains_non_ascii_slow(src + offset, remainder))
return true;
}
return false;
}
static void force_ascii_slow(const char* src, char* dst, size_t len) {
for (size_t i = 0; i < len; ++i) {
dst[i] = src[i] & 0x7f;
}
}
static void force_ascii(const char* src, char* dst, size_t len) {
if (len < 16) {
force_ascii_slow(src, dst, len);
return;
}
const unsigned bytes_per_word = sizeof(uintptr_t);
const unsigned align_mask = bytes_per_word - 1;
const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask;
const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask;
if (src_unalign > 0) {
if (src_unalign == dst_unalign) {
const unsigned unalign = bytes_per_word - src_unalign;
force_ascii_slow(src, dst, unalign);
src += unalign;
dst += unalign;
len -= src_unalign;
} else {
force_ascii_slow(src, dst, len);
return;
}
}
#if defined(_WIN64) || defined(_LP64)
const uintptr_t mask = ~0x8080808080808080ll;
#else
const uintptr_t mask = ~0x80808080l;
#endif
const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src);
uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst);
for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) {
dstw[i] = srcw[i] & mask;
}
const unsigned remainder = len & align_mask;
if (remainder > 0) {
const size_t offset = len - remainder;
force_ascii_slow(src + offset, dst + offset, remainder);
}
}
static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) {
// We know how much we'll write, just make sure that there's space.
CHECK(dlen >= slen * 2 &&
"not enough space provided for hex encode");
dlen = slen * 2;
for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) {
static const char hex[] = "0123456789abcdef";
uint8_t val = static_cast<uint8_t>(src[i]);
dst[k + 0] = hex[val >> 4];
dst[k + 1] = hex[val & 15];
}
return dlen;
}
#define CHECK_BUFLEN_IN_RANGE(len) \
do { \
if ((len) > Buffer::kMaxLength) { \
*error = SB_BUFFER_SIZE_EXCEEDED_ERROR; \
return MaybeLocal<Value>(); \
} \
} while (0)
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
const char* buf,
size_t buflen,
enum encoding encoding,
Local<Value>* error) {
CHECK_NE(encoding, UCS2);
CHECK_BUFLEN_IN_RANGE(buflen);
*error = Local<Value>();
if (!buflen && encoding != BUFFER) {
return String::Empty(isolate);
}
MaybeLocal<String> val;
switch (encoding) {
case BUFFER:
{
auto maybe_buf = Buffer::Copy(isolate, buf, buflen);
if (maybe_buf.IsEmpty()) {
*error = SB_BUFFER_CREATION_ERROR;
return MaybeLocal<Value>();
}
return maybe_buf.ToLocalChecked();
}
case ASCII:
if (contains_non_ascii(buf, buflen)) {
char* out = node::UncheckedMalloc(buflen);
if (out == nullptr) {
*error = SB_MALLOC_FAILED_ERROR;
return MaybeLocal<Value>();
}
force_ascii(buf, out, buflen);
return ExternOneByteString::New(isolate, out, buflen, error);
} else {
return ExternOneByteString::NewFromCopy(isolate, buf, buflen, error);
}
case UTF8:
val = String::NewFromUtf8(isolate,
buf,
v8::NewStringType::kNormal,
buflen);
if (val.IsEmpty()) {
*error = SB_STRING_TOO_LONG_ERROR;
return MaybeLocal<Value>();
}
return val.ToLocalChecked();
case LATIN1:
return ExternOneByteString::NewFromCopy(isolate, buf, buflen, error);
case BASE64: {
size_t dlen = base64_encoded_size(buflen);
char* dst = node::UncheckedMalloc(dlen);
if (dst == nullptr) {
*error = SB_MALLOC_FAILED_ERROR;
return MaybeLocal<Value>();
}
size_t written = base64_encode(buf, buflen, dst, dlen);
CHECK_EQ(written, dlen);
return ExternOneByteString::New(isolate, dst, dlen, error);
}
case HEX: {
size_t dlen = buflen * 2;
char* dst = node::UncheckedMalloc(dlen);
if (dst == nullptr) {
*error = SB_MALLOC_FAILED_ERROR;
return MaybeLocal<Value>();
}
size_t written = hex_encode(buf, buflen, dst, dlen);
CHECK_EQ(written, dlen);
return ExternOneByteString::New(isolate, dst, dlen, error);
}
default:
CHECK(0 && "unknown encoding");
break;
}
UNREACHABLE();
}
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
const uint16_t* buf,
size_t buflen,
Local<Value>* error) {
CHECK_BUFLEN_IN_RANGE(buflen);
*error = Local<Value>();
// Node's "ucs2" encoding expects LE character data inside a
// Buffer, so we need to reorder on BE platforms. See
// http://nodejs.org/api/buffer.html regarding Node's "ucs2"
// encoding specification
std::vector<uint16_t> dst;
if (IsBigEndian()) {
dst.assign(buf, buf + buflen);
size_t nbytes = buflen * sizeof(dst[0]);
SwapBytes16(reinterpret_cast<char*>(&dst[0]), nbytes);
buf = &dst[0];
}
return ExternTwoByteString::NewFromCopy(isolate, buf, buflen, error);
}
MaybeLocal<Value> StringBytes::Encode(Isolate* isolate,
const char* buf,
enum encoding encoding,
Local<Value>* error) {
const size_t len = strlen(buf);
MaybeLocal<Value> ret;
if (encoding == UCS2) {
// In Node, UCS2 means utf16le. The data must be in little-endian
// order and must be aligned on 2-bytes. This returns an empty
// value if it's not aligned and ensures the appropriate byte order
// on big endian architectures.
const bool be = IsBigEndian();
if (len % 2 != 0)
return ret;
std::vector<uint16_t> vec(len / 2);
for (size_t i = 0, k = 0; i < len; i += 2, k += 1) {
const uint8_t hi = static_cast<uint8_t>(buf[i + 0]);
const uint8_t lo = static_cast<uint8_t>(buf[i + 1]);
vec[k] = be ?
static_cast<uint16_t>(hi) << 8 | lo
: static_cast<uint16_t>(lo) << 8 | hi;
}
ret = vec.empty() ?
static_cast< Local<Value> >(String::Empty(isolate))
: StringBytes::Encode(isolate, &vec[0], vec.size(), error);
} else {
ret = StringBytes::Encode(isolate, buf, len, encoding, error);
}
return ret;
}
} // namespace node
| 30.705954 | 80 | 0.557556 | [
"vector"
] |
3335884364bac4f78df8bbccb3aaef1213bca58e | 66,528 | cpp | C++ | src/tool-cint.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 19 | 2016-06-18T02:03:56.000Z | 2022-02-23T17:26:32.000Z | src/tool-cint.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 43 | 2017-03-09T07:32:12.000Z | 2022-03-23T20:18:35.000Z | src/tool-cint.cpp | johnnymac647/humlib | c67954045fb5570915d6a1c75d9a1e36cc9bdf93 | [
"BSD-2-Clause"
] | 5 | 2019-11-14T22:24:02.000Z | 2021-09-07T18:27:21.000Z | //
// Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Sun Dec 26 17:03:54 PST 2010
// Last Modified: Tue May 30 15:35:10 CEST 2017
// Filename: tool-cint.cpp
// URL: https://github.com/craigsapp/minHumdrum/blob/master/src/tool-cint.cpp
// Syntax: C++11; humlib
// vim: syntax=cpp ts=3 noexpandtab nowrap
//
// Description: Calculates counterpoint interval modules in polyphonic
// music.
//
#include "tool-cint.h"
#include "HumRegex.h"
#include "Convert.h"
#include <algorithm>
using namespace std;
namespace hum {
// START_MERGE
#define EMPTY_ID ""
#define REST 0
#define RESTINT -1000000
#define RESTSTRING "R"
#define INTERVAL_HARMONIC 1
#define INTERVAL_MELODIC 2
#define MARKNOTES 1
/////////////////////////////////
//
// Tool_cint::Tool_cint -- Set the recognized options for the tool.
//
Tool_cint::Tool_cint(void) {
define("base-40|base40|b40|40=b", "display pitches/intervals in base-40");
define("base-12|base12|b12|12=b", "display pitches/intervals in base-12");
define("base-7|base7|b7|7|diatonic=b", "display pitches/intervals in base-7");
define("g|grid|pitch|pitches=b", "display pitch grid used to calculate modules");
define("r|rhythm=b", "display rhythmic positions of notes");
define("f|filename=b", "display filenames with --count");
define("raw=b", "display only modules without formatting");
define("raw2=b", "display only modules formatted for Vishesh");
define("c|uncross=b", "uncross crossed voices when creating modules");
define("k|koption=s:", "Select only two spines to analyze");
define("C|comma=b", "separate intervals by comma rather than space");
define("retro|retrospective=b", "Retrospective module display in the score");
define("suspension|suspensions=b", "mark suspensions");
define("rows|row=b", "display lattices in row form");
define("dur|duration=b", "display durations appended to harmonic interval note attacks");
define("id=b", "ids are echoed in module data");
define("L|interleaved-lattice=b", "display interleaved lattices");
define("q|harmonic-parentheses=b", "put square brackets around harmonic intervals");
define("h|harmonic-marker=b", "put h character after harmonic intervals");
define("m|melodic-marker=b", "put m character after melodic intervals");
define("y|melodic-parentheses=b", "put curly braces around melodic intervals");
define("p|parentheses=b", "put parentheses around modules intervals");
define("l|lattice=b", "calculate lattice");
define("loc|location=b", "displayLocation");
define("s|sustain=b", "display sustain/attack states of notes");
define("o|octave=b", "reduce compound intervals to within an octave");
define("H|no-harmonic=b", "don't display harmonic intervals");
define("M|no-melodic=b", "don't display melodic intervals");
define("t|top=b", "display top melodic interval of modules");
define("T|top-only=b", "display only top melodic interval of modules");
define("U|no-melodic-unisons=b", "no melodic perfect unisons");
define("attacks|attack=b", "start/stop module chains on pairs of note attacks");
define("z|zero=b", "display diatonic intervals with 0 offset");
define("N|note-marker=s:@", "pass-through note marking character");
define("x|xoption=b", "display attack/sustain information on harmonic intervals only");
define("n|chain=i:1", "number of sequential modules");
define("R|no-rest|no-rests|norest|norests=b", "number of sequential modules");
define("O|octave-all=b", "transpose all harmonic intervals to within an octave");
define("chromatic=b", "display intervals as diatonic intervals with chromatic alterations");
define("search=s:", "search string");
define("mark=b", "mark matches notes from searches in data");
define("count=b", "count matched modules from search query");
define("debug=b"); // determine bad input line num
define("author=b"); // author of program
define("version=b"); // compilation info
define("example=b"); // example usages
define("help=b"); // short description
}
/////////////////////////////////
//
// Tool_cint::run -- Primary interfaces to the tool.
//
bool Tool_cint::run(HumdrumFileSet& infiles) {
bool status = true;
for (int i=0; i<infiles.getCount(); i++) {
status &= run(infiles[i]);
}
return status;
}
bool Tool_cint::run(const string& indata, ostream& out) {
HumdrumFile infile(indata);
bool status = run(infile);
if (hasAnyText()) {
getAllText(out);
} else {
out << infile;
}
return status;
}
bool Tool_cint::run(HumdrumFile& infile, ostream& out) {
bool status = run(infile);
if (hasAnyText()) {
getAllText(out);
} else {
out << infile;
}
return status;
}
//
// In-place processing of file:
//
bool Tool_cint::run(HumdrumFile& infile) {
processFile(infile);
if (hasAnyText()) {
// getAllText(cout);
} else {
// Re-load the text for each line from their tokens.
cout << infile;
}
return true;
}
///////////////////////////////////////////////////////////////////////////
//
// NoteNode class functions:
//
NoteNode::NoteNode(const NoteNode& anode) {
b40 = anode.b40;
line = anode.line;
spine = anode.spine;
measure = anode.measure;
serial = anode.serial;
mark = anode.mark;
notemarker = anode.notemarker;
beatsize = anode.beatsize;
duration = 0;
protected_id = anode.protected_id;
}
NoteNode& NoteNode::operator=(NoteNode& anode) {
if (this == &anode) {
return *this;
}
b40 = anode.b40;
line = anode.line;
spine = anode.spine;
measure = anode.measure;
serial = anode.serial;
mark = anode.mark;
notemarker = anode.notemarker;
beatsize = anode.beatsize;
duration = anode.duration;
protected_id = anode.protected_id;
return *this;
}
void NoteNode::setId(const string& anid) {
protected_id = anid;
}
NoteNode::~NoteNode(void) {
// do nothing
}
void NoteNode::clear(void) {
mark = measure = serial = b40 = 0;
beatsize = 0.0;
notemarker = 0;
line = spine = -1;
protected_id = "";
}
string NoteNode::getId(void) {
return protected_id;
}
///////////////////////////////////////////////////////////////////////////
//
// Tool_cint functions:
//
//////////////////////////////
//
// Tool_cint::processFile -- Do requested analysis on a given file.
//
int Tool_cint::processFile(HumdrumFile& infile) {
initialize();
vector<vector<NoteNode> > notes;
vector<string> names;
vector<int> ktracks;
vector<HTp> kstarts;
vector<int> reverselookup;
infile.getSpineStartList(kstarts, "**kern");
ktracks.resize(kstarts.size());
for (int i=0; i<(int)kstarts.size(); i++) {
ktracks[i] = kstarts[i]->getTrack();
}
if (koptionQ) {
adjustKTracks(ktracks, getString("koption"));
}
notes.resize(ktracks.size());
reverselookup.resize(infile.getTrackCount()+1);
fill(reverselookup.begin(), reverselookup.end(), -1);
vector<vector<string> > retrospective;
if (retroQ) {
initializeRetrospective(retrospective, infile, ktracks);
}
// if (locationQ || rhythmQ || durationQ) {
// infile.analyzeRhythm();
// }
int i;
for (i=0; i<(int)ktracks.size(); i++) {
reverselookup[ktracks[i]] = i;
// notes[i].reserve(infile.getLineCount());
notes[i].resize(0);
}
getNames(names, reverselookup, infile);
HumRegex pre;
extractNoteArray(notes, infile, ktracks, reverselookup);
if (pitchesQ) {
printPitchGrid(notes, infile);
exit(0);
}
int count = 0;
if (latticeQ) {
printLattice(notes, infile, ktracks, reverselookup, Chaincount);
} else if (interleavedQ) {
printLatticeInterleaved(notes, infile, ktracks, reverselookup,
Chaincount);
} else if (suspensionsQ) {
count = printCombinationsSuspensions(notes, infile, ktracks,
reverselookup, Chaincount, retrospective);
} else {
count = printCombinations(notes, infile, ktracks, reverselookup,
Chaincount, retrospective, SearchString);
}
// handle search results here
if (markQ) {
if (count > 0) {
addMarksToInputData(infile, notes, ktracks, reverselookup);
}
infile.createLinesFromTokens();
m_humdrum_text << infile;
m_humdrum_text << "!!!RDF**kern: @ = matched note, color=\"#ff0000\"\n";
}
if (debugQ) {
int j;
for (i=0; i<(int)retrospective[0].size(); i++) {
for (j=0; j<(int)retrospective.size(); j++) {
m_humdrum_text << retrospective[j][i];
if (j < (int)retrospective.size() - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << "\n";
}
}
return count;
}
//////////////////////////////
//
// Tool_cint::adjustKTracks -- Select only two spines to do analysis on.
//
void Tool_cint::adjustKTracks(vector<int>& ktracks, const string& koption) {
HumRegex pre;
if (!pre.search(koption, "(\\$|\\$?\\d*)[^\\$\\d]+(\\$|\\$?\\d*)")) {
return;
}
int number1 = 0;
int number2 = 0;
HumRegex pre2;
if (pre2.search(pre.getMatch(1), "\\d+")) {
number1 = pre.getMatchInt(1);
if (pre.getMatch(1).find('$') != string::npos) {
number1 = (int)ktracks.size() - number1;
}
} else {
number1 = (int)ktracks.size();
}
if (pre2.search(pre.getMatch(2), "\\d+")) {
number2 = pre.getMatchInt(2);
if (pre.getMatch(2).find('$') != string::npos) {
number2 = (int)ktracks.size() - number2;
}
} else {
number2 = (int)ktracks.size();
}
number1--;
number2--;
int track1 = ktracks[number1];
int track2 = ktracks[number2];
ktracks.resize(2);
ktracks[0] = track1;
ktracks[1] = track2;
}
//////////////////////////////
//
// Tool_cint::initializeRetrospective --
//
void Tool_cint::initializeRetrospective(vector<vector<string> >& retrospective,
HumdrumFile& infile, vector<int>& ktracks) {
int columns = (int)ktracks.size();
columns = columns * (columns + 1) / 2; // triangle number of analysis cols.
retrospective.resize(columns);
int i, j;
for (i=0; i<(int)retrospective.size(); i++) {
retrospective[i].resize(infile.getLineCount());
}
string token;
for (i=0; i<infile.getLineCount(); i++) {
if (infile[i].isLocalComment()) {
token = "!";
} else if (infile[i].isGlobalComment()) {
token = "!";
} else if (infile[i].isReference()) {
token = "!!";
} else if (infile[i].isBarline()) {
token = *infile.token(i, 0);
} else if (infile[i].isData()) {
token = ".";
} else if (infile[i].isInterpretation()) {
token = "*";
if (infile[i].isExclusiveInterpretation()) {
token = "**cint";
}
}
for (j=0; j<(int)retrospective.size(); j++) {
retrospective[j][i] = token;
}
}
if (debugQ) {
for (i=0; i<(int)retrospective[0].size(); i++) {
for (j=0; j<(int)retrospective.size(); j++) {
m_humdrum_text << retrospective[j][i];
if (j < (int)retrospective.size() - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << "\n";
}
}
}
//////////////////////////////
//
// Tool_cint::printCombinationsSuspensions --
//
// have to do something with sbuffer
//
int Tool_cint::printCombinationsSuspensions(vector<vector<NoteNode> >& notes,
HumdrumFile& infile, vector<int>& ktracks, vector<int>& reverselookup,
int n, vector<vector<string> >& retrospective) {
string sbuffer;
int oldcountQ = countQ;
countQ = 1; // mostly used to suppress intermediate output
int countsum = 0;
searchQ = 1; // turn on searching
// Suspensions with length-2 modules
n = 2; // -n 2
xoptionQ = 1; // -x
sbuffer = "";
sbuffer += "^7xs 1 6sx -2 8xx$";
sbuffer += "|^2sx -2 3xs 2 1xx$";
sbuffer += "|^7xs 1 6sx 2 6xx$";
sbuffer += "|^11xs 1 10sx -5 15xx$";
sbuffer += "|^4xs 1 3sx -5 8xx$";
sbuffer += "|^2sx -2 3xs 2 3xx$";
// "9xs 1 8sx -2 10xx" archetype: Jos1405 m10 A&B
sbuffer += "|^9xs 1 8sx -2 10xx$";
// "4xs 1 3sx 5xx" archetype: Jos1713 m87-88 A&B
sbuffer += "|^4xs 1 3sx -2 5xx$";
// "11xs 1 10sx 4 8xx" archetype: Jos1402 m23-24 S&B
sbuffer += "|^11xs 1 10sx 4 8xx$";
countsum += printCombinations(notes, infile, ktracks, reverselookup, n,
retrospective, sbuffer);
// Suspensions with length-3 modules /////////////////////////////////
n = 3; // -n 3
xoptionQ = 1; // -x
sbuffer = "";
// "7xs 1 6sx 1 5sx 1 6sx" archetype: Jos2721 m27-78 S&T
sbuffer += "^7xs 1 6sx 1 5sx 1 6sx$";
// "7xs 1 6sx 1 6sx -2 8xx" archetype: Rue2018 m38-88 S&T
sbuffer += "|^7xs 1 6sx 1 6sx -2 8xx$";
// "11xs 1 10sx 1 10sx -5 15xx" archetype: Rue2018 m38-88 S&B
sbuffer += "|^11xs 1 10sx 1 10sx -5 15xx$";
countsum += printCombinations(notes, infile, ktracks, reverselookup, n,
retrospective, sbuffer);
// Suspensions with length-5 modules /////////////////////////////////
n = 5; // -n 2
xoptionQ = 1; // -x
sbuffer = "";
// "8xs 1 7sx 1 7sx 1 6sx 1 6sx 1 5sx -1 8xx" archetype: Duf3015a m94 S&T
sbuffer += "^8xs 1 7sx 1 7sx 1 6sx 1 5sx -2 8xx$";
countsum += printCombinations(notes, infile, ktracks, reverselookup, n,
retrospective, sbuffer);
// Suspensions with rests modules
// done with multiple searches. Mark the notes in the score if required.
countQ = oldcountQ;
return countsum;
}
//////////////////////////////
//
// Tool_cint::printCombinations --
//
int Tool_cint::printCombinations(vector<vector<NoteNode> >& notes,
HumdrumFile& infile, vector<int>& ktracks, vector<int>& reverselookup,
int n, vector<vector<string> >& retrospective, const string& searchstring) {
int i;
int currentindex = 0;
int matchcount = 0;
for (i=0; i<infile.getLineCount(); i++) {
if (!infile[i].hasSpines()) {
// print all lines here which do not contain spine
// information.
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
m_humdrum_text << infile[i] << "\n";
}
continue;
}
// At this point there are only four types of lines:
// (1) data lines
// (2) interpretation lines (lines starting with *)
// (3) local comment lines (lines starting with single !)
// (4) barlines
if (infile[i].isInterpretation()) {
string pattern = "*";
if (infile.token(i, 0)->compare(0, 2, "**") == 0) {
pattern = "**cint";
} else if (*infile.token(i, 0) == "*-") {
pattern = "*-";
} else if (infile.token(i, 0)->compare(0, 2, "*>") == 0) {
pattern = *infile.token(i, 0);
}
printAsCombination(infile, i, ktracks, reverselookup, pattern);
} else if (infile[i].isLocalComment()) {
printAsCombination(infile, i, ktracks, reverselookup, "!");
} else if (infile[i].isBarline()) {
printAsCombination(infile, i, ktracks, reverselookup, *infile.token(i, 0));
} else {
// print combination data
currentindex = printModuleCombinations(infile, i, ktracks,
reverselookup, n, currentindex, notes, matchcount, retrospective, searchstring);
}
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
m_humdrum_text << "\n";
}
}
return matchcount;
}
//////////////////////////////
//
// Tool_cint::printModuleCombinations --
//
int Tool_cint::printModuleCombinations(HumdrumFile& infile, int line, vector<int>& ktracks,
vector<int>& reverselookup, int n, int currentindex,
vector<vector<NoteNode> >& notes, int& matchcount,
vector<vector<string> >& retrospective, const string& searchstring) {
int fileline = line;
string filename = infile.getFilename();
while ((currentindex < (int)notes[0].size())
&& (fileline > notes[0][currentindex].line)) {
currentindex++;
}
if (currentindex >= (int)notes[0].size()) {
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
m_humdrum_text << ".";
printAsCombination(infile, line, ktracks, reverselookup, ".");
}
return currentindex;
}
if (notes[0][currentindex].line != fileline) {
// This section occurs when two voices are both sustaining
// at the start of the module. Print a "." to indicate that
// the counterpoint module is continuing from a previous line.
printAsCombination(infile, line, ktracks, reverselookup, ".");
return currentindex;
}
// found the index into notes which matches to the current fileline.
if (currentindex + n >= (int)notes[0].size()) {
// asking for chain longer than rest of available data.
printAsCombination(infile, line, ktracks, reverselookup, ".");
return currentindex;
}
// printAsCombination(infile, line, ktracks, reverselookup, ".");
// return currentindex;
int tracknext;
int track;
int j, jj;
int count = 0;
for (j=0; j<infile[line].getFieldCount(); j++) {
if (!infile.token(line, j)->isKern()) {
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
continue;
}
track = infile.token(line, j)->getTrack();
if (j < infile[line].getFieldCount() - 1) {
tracknext = infile.token(line, j+1)->getTrack();
} else {
tracknext = -23525;
}
if (track == tracknext) {
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
continue;
}
// print the **kern spine, then check to see if there
// is some **cint data to print
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
m_humdrum_text << infile.token(line, j);
}
if ((track != ktracks.back()) && (reverselookup[track] >= 0)) {
count = (int)ktracks.size() - reverselookup[track] - 1;
for (jj = 0; jj<count; jj++) {
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
m_humdrum_text << "\t";
}
int part1 = reverselookup[track];
int part2 = part1+1+jj;
// m_humdrum_text << part1 << "," << part2;
matchcount += printCombinationModulePrepare(m_humdrum_text, filename,
notes, n, currentindex, part1, part2, retrospective, infile,
searchstring);
}
}
if (!(raw2Q || rawQ || markQ || retroQ || countQ)) {
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
}
return currentindex;
}
//////////////////////////////
//
// Tool_cint::printCombinationModulePrepare --
//
int Tool_cint::printCombinationModulePrepare(ostream& out, const string& filename,
vector<vector<NoteNode> >& notes, int n, int startline, int part1,
int part2, vector<vector<string> >& retrospective,
HumdrumFile& infile, const string& searchstring) {
int count = 0;
HumRegex hre;
stringstream tempstream;
int match;
char notemarker = '\0';
// ggg
int status = printCombinationModule(tempstream, filename, notes,
n, startline, part1, part2, retrospective, notemarker);
if (status) {
if (raw2Q || rawQ) {
tempstream << "\n";
}
if (NoteMarker && (notemarker == NoteMarker)) {
out << (char)NoteMarker;
}
if (searchQ) {
// Check to see if the extracted module matches to the
// search query.
match = hre.search(tempstream.str(), searchstring);
if (match) {
count++;
if (locationQ) {
int line = notes[0][startline].line;
double loc = infile[line].getDurationFromStart().getFloat() /
infile[infile.getLineCount()-1].getDurationFromStart().getFloat();
loc = int(100.0 * loc + 0.5)/100.0;
m_humdrum_text << "!!LOCATION:"
<< "\t" << loc
<< "\tm" << getMeasure(infile, line)
<< "\tv" << ((int)notes.size() - part2)
<< ":v" << ((int)notes.size() - part1)
<< "\t" << infile.getFilename()
<< endl;
}
if (raw2Q || rawQ) {
out << tempstream.str();
// newline already added somewhere previously.
// m_humdrum_text << "\n";
} else {
// mark notes of the matched module(s) in the note array
// for later marking in input score.
status = printCombinationModule(tempstream, filename,
notes, n, startline, part1, part2, retrospective,
notemarker, MARKNOTES);
if (status && (raw2Q || rawQ)) {
tempstream << "\n";
}
}
}
} else {
if (retroQ) {
int column = getTriangleIndex((int)notes.size(), part1, part2);
retrospective[column][status] = tempstream.str();
} else {
out << tempstream.str();
}
}
} else {
if (!(raw2Q || rawQ || markQ || retroQ || countQ || searchQ)) {
out << ".";
}
}
return count;
}
//////////////////////////////
//
// Tool_cint::getMeasure -- return the last measure number of the given line index.
//
int Tool_cint::getMeasure(HumdrumFile& infile, int line) {
int measure = 0;
HumRegex hre;
for (int i=line; i>=0; i--) {
if (!infile[i].isBarline()) {
continue;
}
if (hre.search(*infile.token(i, 0), "=(\\d+)")) {
measure = hre.getMatchInt(1);
return measure;
}
}
return 0;
}
//////////////////////////////
//
// Tool_cint::getTriangleIndex --
//
int Tool_cint::getTriangleIndex(int number, int num1, int num2) {
// int triangle = number * (number + 1) / 2;
// intermediate code, not active yet
return 0;
}
//////////////////////////////
//
// Tool_cint::addMarksToInputData -- mark notes in the score which matched
// to the search query.
//
void Tool_cint::addMarksToInputData(HumdrumFile& infile,
vector<vector<NoteNode> >& notes, vector<int>& ktracks,
vector<int>& reverselookup) {
// first carry all marks from sustained portions of notes onto their
// note attacks.
int i, j;
int mark = 0;
int track = 0;
int markpitch = -1;
for (i=0; i<(int)notes.size(); i++) {
mark = 0;
for (j=(int)notes[i].size()-1; j>=0; j--) {
if (mark && (-markpitch == notes[i][j].b40)) {
// In the sustain region between a note
// attack and the marked sustain. Mark the
// sustained region as well (don't know
// if this behavior might change in the
// future.
notes[i][j].mark = mark;
continue;
}
if (mark && (markpitch == notes[i][j].b40)) {
// At the start of a notes which was marked.
// Mark the attack since only note attacks
// will be marked in the score
notes[i][j].mark = mark;
mark = 0;
continue;
}
if (mark && (markpitch != notes[i][j].b40)) {
// something strange happened. Probably
// an open tie which was not started
// properly, so just clear mark.
mark = 0;
}
if (notes[i][j].mark) {
mark = 1;
markpitch = abs(notes[i][j].b40);
} else {
mark = 0;
}
}
}
// a forward loop here into notes array to continue
// marks to end of sutained region of marked notes
for (i=0; i<(int)notes.size(); i++) {
for (j=0; j<(int)notes[i].size(); j++) {
if (notes[i][j].mark) {
markpitch = -abs(notes[i][j].b40);
continue;
} else if (notes[i][j].b40 == markpitch) {
notes[i][j].mark = 1;
continue;
} else {
markpitch = -1;
}
}
}
// print mark information:
// for (j=0; j<(int)notes[0].size(); j++) {
// for (i=0; i<(int)notes.size(); i++) {
// m_humdrum_text << notes[i][j].b40;
// if (notes[i][j].mark) {
// m_humdrum_text << "m";
// }
// m_humdrum_text << " ";
// }
// m_humdrum_text << "\n";
// }
// now go through the input score placing user-markers onto notes
// which were marked in the note array.
int currentindex = 0;
for (i=0; i<infile.getLineCount(); i++) {
if (!infile[i].isData()) {
continue;
}
while ((currentindex < (int)notes[0].size())
&& (i > notes[0][currentindex].line)) {
currentindex++;
}
if (currentindex >= (int)notes[0].size()) {
continue;
}
if (notes[0][currentindex].line != i) {
continue;
}
for (j=0; j<infile[i].getFieldCount(); j++) {
if (!infile.token(i, j)->isKern()) {
continue;
}
if (*infile.token(i, j) == ".") {
// Don't mark null tokens.
continue;
}
track = infile.token(i, j)->getTrack();
if (reverselookup[track] < 0) {
continue;
}
if (notes[reverselookup[track]][currentindex].mark != 0) {
markNote(infile, i, j);
}
}
}
}
//////////////////////////////
//
// Tool_cint::markNote --
//
void Tool_cint::markNote(HumdrumFile& infile, int line, int col) {
// string text = *infile.token(line, col);
// text += "@";
// infile.token(line, col)->setText(text);
*infile.token(line, col) += "@";
}
//////////////////////////////
//
// Tool_cint::getOctaveAdjustForCombinationModule -- Find the minim harmonic interval in
// the module chain. If it is greater than an octave, then move it down
// below an octave. If the minimum is an octave, then don't do anything.
// Not considering crossed voices.
//
int Tool_cint::getOctaveAdjustForCombinationModule(vector<vector<NoteNode> >& notes, int n,
int startline, int part1, int part2) {
// if the current two notes are both sustains, then skip
if ((notes[part1][startline].b40 <= 0) &&
(notes[part2][startline].b40 <= 0)) {
return 0;
}
if (norestsQ) {
if (notes[part1][startline].b40 == 0) {
return 0;
}
if (notes[part2][startline].b40 == 0) {
return 0;
}
}
int i;
int count = 0;
int attackcount = 0;
int hint;
vector<int> hintlist;
hintlist.reserve(1000);
for (i=startline; i<(int)notes[0].size(); i++) {
if ((notes[part1][i].b40 <= 0) && (notes[part2][i].b40 <= 0)) {
// skip notes if both are sustained
continue;
}
if (attackQ && ((notes[part1][i].b40 <= 0) ||
(notes[part2][i].b40 <= 0))) {
if (attackcount == 0) {
// not at the start of a pair of attacks.
return 0;
}
}
// consider harmonic interval
if ((notes[part2][i].b40 != 0) && (notes[part1][i].b40 != 0)) {
hint = abs(notes[part2][i].b40) - abs(notes[part1][i].b40);
if (uncrossQ && (hint < 0)) {
hint = -hint;
}
hintlist.push_back(hint);
}
// if count matches n, then exit loop
if ((count == n) && !attackQ) {
break;
}
count++;
if ((notes[part1][i].b40 > 0) && (notes[part2][i].b40 > 0)) {
// keep track of double attacks
if (attackcount >= n) {
break;
} else {
attackcount++;
}
}
}
int minimum = 100000;
for (i=0; i<(int)hintlist.size(); i++) {
if (hintlist[i] < minimum) {
minimum = hintlist[i];
}
}
if (minimum > 1000) {
// no intervals found to consider
return 0;
}
if ((minimum >= 0) && (minimum <= 40)) {
// nothing to do
return 0;
}
if (minimum > 40) {
return -(minimum/40);
} else if (minimum < 0) {
// don't go positive, this will invert the interval.
return (-minimum)/40;
}
//int octaveadjust = -(minimum / 40);
//if (attackQ && (attackcount == n)) {
// return octaveadjust;
//} else if (count == n) {
// return octaveadjust;
//} else {
// // did not find the required number of modules.
// return 0;
//}
return 0;
}
//////////////////////////////
//
// Tool_cint::printCombinationModule -- Similar to printLatticeModule, but harmonic
// intervals will not be triggered by a pair of sustained notes.
// Print a counterpoint module or module chain given the start notes
// and pair of parts to calculate the module (chains) from. Will not
// print anything if the chain length is longer than the note array.
// The n parameter will be ignored if --attacks option is used
// (--attacks will gnereate a variable length module chain).
//
int Tool_cint::printCombinationModule(ostream& out, const string& filename,
vector<vector<NoteNode> >& notes, int n, int startline, int part1,
int part2, vector<vector<string> >& retrospective, char& notemarker,
int markstate) {
notemarker = '\0';
if (norestsQ) {
if (notes[part1][startline].b40 == 0) {
return 0;
}
if (notes[part2][startline].b40 == 0) {
return 0;
}
}
stringstream idstream;
// int crossing = 0;
//int oldcrossing = 0;
int octaveadjust = 0; // used for -o option
if (octaveQ) {
octaveadjust = getOctaveAdjustForCombinationModule(notes, n, startline,
part1, part2);
}
ostream *outp = &out;
// if (rawQ && !searchQ) {
// outp = &m_humdrum_text;
// }
if (n + startline >= (int)notes[0].size()) { // [20150202]
// definitely nothing to do
return 0;
}
if ((int)notes.size() == 0) {
// nothing to do
return 0;
}
// if the current two notes are both sustains, then skip
if ((notes[part1][startline].b40 <= 0) &&
(notes[part2][startline].b40 <= 0)) {
return 0;
}
if (raw2Q) {
// print pitch of first bottom note
if (filenameQ) {
(*outp) << "file_" << filename;
(*outp) << " ";
}
(*outp) << "v_" << part1 << " v_" << part2 << " ";
if (base12Q) {
(*outp) << "base12_";
(*outp) << Convert::base40ToMidiNoteNumber(abs(notes[part1][startline].b40));
} else if (base40Q) {
(*outp) << "base40_";
(*outp) << abs(notes[part1][startline].b40);
} else {
(*outp) << "base7_";
(*outp) << Convert::base40ToDiatonic(abs(notes[part1][startline].b40));
}
(*outp) << " ";
}
if (parenQ) {
(*outp) << "(";
}
int i;
int count = 0;
int countm = 0;
int attackcount = 0;
int idstart = 0;
int lastindex = -1;
int retroline = 0;
for (i=startline; i<(int)notes[0].size(); i++) {
if ((notes[part1][i].b40 <= 0) && (notes[part2][i].b40 <= 0)) {
// skip notes if both are sustained
continue;
}
if (norestsQ) {
if (notes[part1][i].b40 == 0) {
return 0;
}
if (notes[part2][i].b40 == 0) {
return 0;
}
}
if (attackQ && ((notes[part1][i].b40 <= 0) ||
(notes[part2][i].b40 <= 0))) {
if (attackcount == 0) {
// not at the start of a pair of attacks.
return 0;
}
}
// print the melodic intervals (if not the first item in chain)
if ((count > 0) && !nomelodicQ) {
if (mparenQ) {
(*outp) << "{";
}
if (nounisonsQ) {
// suppress modules which contain melodic perfect unisons:
if ((notes[part1][i].b40 != 0) &&
(abs(notes[part1][i].b40) == abs(notes[part1][lastindex].b40))) {
return 0;
}
if ((notes[part2][i].b40 != 0) &&
(abs(notes[part2][i].b40) == abs(notes[part2][lastindex].b40))) {
return 0;
}
}
// bottom melodic interval:
if (!toponlyQ) {
printInterval((*outp), notes[part1][lastindex],
notes[part1][i], INTERVAL_MELODIC);
if (mmarkerQ) {
(*outp) << "m";
}
}
// print top melodic interval here if requested
if (topQ || toponlyQ) {
if (!toponlyQ) {
printSpacer((*outp));
}
// top melodic interval:
printInterval((*outp), notes[part2][lastindex],
notes[part2][i], INTERVAL_MELODIC);
if (mmarkerQ) {
(*outp) << "m";
}
}
if (mparenQ) {
(*outp) << "}";
}
printSpacer((*outp));
}
countm++;
// print harmonic interval
if (!noharmonicQ) {
if (hparenQ) {
(*outp) << "[";
}
if (markstate) {
notes[part1][i].mark = 1;
notes[part2][i].mark = 1;
} else {
// oldcrossing = crossing;
//crossing = printInterval((*outp), notes[part1][i],
// notes[part2][i], INTERVAL_HARMONIC, octaveadjust);
printInterval((*outp), notes[part1][i],
notes[part2][i], INTERVAL_HARMONIC, octaveadjust);
}
if (durationQ) {
if (notes[part1][i].isAttack()) {
(*outp) << "D" << notes[part1][i].duration;
}
if (notes[part2][i].isAttack()) {
(*outp) << "d" << notes[part1][i].duration;
}
}
if (hmarkerQ) {
(*outp) << "h";
}
if (hparenQ) {
(*outp) << "]";
}
}
// prepare the ids string if requested
if (idQ) {
// if (count == 0) {
// insert both first two notes, even if sustain.
if (idstart != 0) { idstream << ':'; }
idstart++;
idstream << notes[part1][i].getId() << ':'
<< notes[part2][i].getId();
// } else {
// // only insert IDs if an attack
// if (notes[part1][i].b40 > 0) {
// if (idstart != 0) { idstream << ':'; }
// idstart++;
// idstream << notes[part1][i].getId();
// }
// if (notes[part2][i].b40 > 0) {
// if (idstart != 0) { idstream << ':'; }
// idstart++;
// idstream << notes[part2][i].getId();
// }
// }
}
// keep track of notemarker state
if (notes[part1][i].notemarker == NoteMarker) {
notemarker = NoteMarker;
}
if (notes[part2][i].notemarker == NoteMarker) {
notemarker = NoteMarker;
}
// if count matches n, then exit loop
if ((count == n) && !attackQ) {
retroline = i;
break;
} else {
if (!noharmonicQ) {
printSpacer((*outp));
}
}
lastindex = i;
count++;
if ((notes[part1][i].b40 > 0) && (notes[part2][i].b40 > 0)) {
// keep track of double attacks
if (attackcount >= n) {
retroline = i;
break;
} else {
attackcount++;
}
}
}
if (parenQ) {
(*outp) << ")";
}
if (idQ && idstart) {
idstream << ends;
(*outp) << " ID:" << idstream.str();
}
if (attackQ && (attackcount == n)) {
return retroline;
} else if ((countm>1) && (count == n)) {
return retroline;
} else if (n == 0) {
return retroline;
} else {
// did not print the required number of modules.
return 0;
}
return 0;
}
//////////////////////////////
//
// Tool_cint::printAsCombination --
//
void Tool_cint::printAsCombination(HumdrumFile& infile, int line, vector<int>& ktracks,
vector<int>& reverselookup, const string& interstring) {
if (raw2Q || rawQ || markQ || retroQ || countQ) {
return;
}
vector<int> done(ktracks.size(), 0);
int track;
int tracknext;
int count;
int j, jj;
for (j=0; j<infile[line].getFieldCount(); j++) {
if (!infile.token(line, j)->isKern()) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
continue;
}
track = infile.token(line, j)->getTrack();
if (j < infile[line].getFieldCount() - 1) {
tracknext = infile.token(line, j+1)->getTrack();
} else {
tracknext = -23525;
}
if (track == tracknext) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
continue;
}
// print the **kern spine, then check to see if there
// is some **cint data to print
// ggg
m_humdrum_text << infile.token(line, j);
if (reverselookup[track] >= 0) {
count = (int)ktracks.size() - reverselookup[track] - 1;
for (jj=0; jj<count; jj++) {
m_humdrum_text << "\t" << interstring;
}
}
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
}
//////////////////////////////
//
// Tool_cint::printLatticeInterleaved --
//
void Tool_cint::printLatticeInterleaved(vector<vector<NoteNode> >& notes,
HumdrumFile& infile, vector<int>& ktracks, vector<int>& reverselookup,
int n) {
int currentindex = 0;
int i;
for (i=0; i<infile.getLineCount(); i++) {
if (!infile[i].hasSpines()) {
// print all lines here which do not contain spine
// information.
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile[i] << "\n";
}
continue;
}
// At this point there are only four types of lines:
// (1) data lines
// (2) interpretation lines (lines starting with *)
// (3) local comment lines (lines starting with single !)
// (4) barlines
if (infile[i].isInterpretation()) {
string pattern = "*";
if (infile.token(i, 0)->compare(0, 2, "**") == 0) {
pattern = "**cint";
} else if (infile.token(i, 0)->compare("*-") == 0) {
pattern = "*-";
} else if (infile.token(i, 0)->compare(0, 2, "*>") == 0) {
pattern = *infile.token(i, 0);
}
printInterleaved(infile, i, ktracks, reverselookup, pattern);
} else if (infile[i].isLocalComment()) {
printInterleaved(infile, i, ktracks, reverselookup, "!");
} else if (infile[i].isBarline()) {
printInterleaved(infile, i, ktracks, reverselookup, *infile.token(i, 0));
} else {
// print interleaved data
currentindex = printInterleavedLattice(infile, i, ktracks,
reverselookup, n, currentindex, notes);
}
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\n";
}
}
}
//////////////////////////////
//
// Tool_cint::printInterleavedLattice --
//
int Tool_cint::printInterleavedLattice(HumdrumFile& infile, int line, vector<int>& ktracks,
vector<int>& reverselookup, int n, int currentindex,
vector<vector<NoteNode> >& notes) {
int fileline = line;
while ((currentindex < (int)notes[0].size())
&& (fileline > notes[0][currentindex].line)) {
currentindex++;
}
if (currentindex >= (int)notes[0].size()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << ".";
printInterleaved(infile, line, ktracks, reverselookup, ".");
}
return currentindex;
}
if (notes[0][currentindex].line != fileline) {
// should never get here.
printInterleaved(infile, line, ktracks, reverselookup, "?");
return currentindex;
}
// found the index into notes which matches to the current fileline.
if (currentindex + n >= (int)notes[0].size()) {
// asking for chain longer than rest of available data.
printInterleaved(infile, line, ktracks, reverselookup, ".");
return currentindex;
}
int tracknext;
int track;
int j;
for (j=0; j<infile[line].getFieldCount(); j++) {
if (!infile.token(line, j)->isKern()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
continue;
}
track = infile.token(line, j)->getTrack();
if (j < infile[line].getFieldCount() - 1) {
tracknext = infile.token(line, j+1)->getTrack();
} else {
tracknext = -23525;
}
if (track == tracknext) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
continue;
}
// print the **kern spine, then check to see if there
// is some **cint data to print
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile.token(line, j);
}
if ((track != ktracks.back()) && (reverselookup[track] >= 0)) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\t";
}
int part1 = reverselookup[track];
int part2 = part1+1;
// m_humdrum_text << part1 << "," << part2;
printLatticeModule(m_humdrum_text, notes, n, currentindex, part1, part2);
}
if (!(rawQ || raw2Q)) {
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
}
return currentindex;
}
//////////////////////////////
//
// Tool_cint::printInterleaved --
//
void Tool_cint::printInterleaved(HumdrumFile& infile, int line, vector<int>& ktracks,
vector<int>& reverselookup, const string& interstring) {
vector<int> done(ktracks.size(), 0);
int track;
int tracknext;
int j;
for (j=0; j<infile[line].getFieldCount(); j++) {
if (!infile.token(line, j)->isKern()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
continue;
}
track = infile.token(line, j)->getTrack();
if (j < infile[line].getFieldCount() - 1) {
tracknext = infile.token(line, j+1)->getTrack();
} else {
tracknext = -23525;
}
if (track == tracknext) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile.token(line, j);
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
continue;
}
// print the **kern spine, then check to see if there
// is some **cint data to print
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile.token(line, j);
if ((track != ktracks.back()) && (reverselookup[track] >= 0)) {
m_humdrum_text << "\t" << interstring;
}
if (j < infile[line].getFieldCount() - 1) {
m_humdrum_text << "\t";
}
}
}
}
//////////////////////////////
//
// Tool_cint::printLattice --
//
void Tool_cint::printLattice(vector<vector<NoteNode> >& notes, HumdrumFile& infile,
vector<int>& ktracks, vector<int>& reverselookup, int n) {
int i;
int ii = 0;
for (i=0; i<infile.getLineCount(); i++) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << infile[i];
}
if (infile.token(i, 0)->compare(0, 2, "**") == 0) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\t**cint\n";
}
continue;
}
if (infile[i].isData()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\t";
}
if (rowsQ) {
ii = printLatticeItemRows(notes, n, ii, i);
} else {
ii = printLatticeItem(notes, n, ii, i);
}
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\n";
}
continue;
}
if (infile[i].isBarline()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\t" << infile.token(i, 0) << "\n";
}
continue;
}
if (infile[i].isInterpretation()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\t*\n";
}
continue;
}
if (infile[i].isLocalComment()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << "\t!\n";
}
continue;
}
}
}
//////////////////////////////
//
// Tool_cint::printLatticeModule -- print a counterpoint module or module chain given
// the start notes and pair of parts to calculate the module
// (chains) from. Will not print anything if the chain length
// is longer than the note array.
//
int Tool_cint::printLatticeModule(ostream& out, vector<vector<NoteNode> >& notes, int n,
int startline, int part1, int part2) {
if (n + startline >= (int)notes[0].size()) {
return 0;
}
if (parenQ) {
out << "(";
}
int i;
for (i=0; i<n; i++) {
// print harmonic interval
if (hparenQ) {
out << "[";
}
printInterval(out, notes[part1][startline+i],
notes[part2][startline+i], INTERVAL_HARMONIC);
if (hmarkerQ) {
out << "h";
}
if (hparenQ) {
out << "]";
}
printSpacer(out);
// print melodic interal(s)
if (mparenQ) {
out << "{";
}
// bottom melodic interval:
if (!toponlyQ) {
printInterval(out, notes[part1][startline+i],
notes[part1][startline+i+1], INTERVAL_MELODIC);
}
// print top melodic interval here if requested
if (topQ || toponlyQ) {
if (!toponlyQ) {
printSpacer(out);
}
// top melodic interval:
printInterval(out, notes[part2][startline+i],
notes[part2][startline+i+1], INTERVAL_MELODIC);
if (mmarkerQ) {
out << "m";
}
}
if (mparenQ) {
out << "}";
}
printSpacer(out);
}
// print last harmonic interval
if (hparenQ) {
out << "[";
}
printInterval(out, notes[part1][startline+n],
notes[part2][startline+n], INTERVAL_HARMONIC);
if (hmarkerQ) {
out << "h";
}
if (hparenQ) {
out << "]";
}
if (parenQ) {
out << ")";
}
return 1;
}
//////////////////////////////
//
// Tool_cint::printLatticeItemRows -- Row form of the lattice.
//
int Tool_cint::printLatticeItemRows(vector<vector<NoteNode> >& notes, int n,
int currentindex, int fileline) {
while ((currentindex < (int)notes[0].size())
&& (fileline > notes[0][currentindex].line)) {
currentindex++;
}
if (currentindex >= (int)notes[0].size()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << ".";
}
return currentindex;
}
if (notes[0][currentindex].line != fileline) {
// should never get here.
if (!(rawQ || raw2Q)) {
m_humdrum_text << "?";
}
return currentindex;
}
// found the index into notes which matches to the current fileline.
if (currentindex + n >= (int)notes[0].size()) {
// asking for chain longer than rest of available data.
if (!(rawQ || raw2Q)) {
m_humdrum_text << ".";
}
return currentindex;
}
stringstream tempstream;
int j;
int counter = 0;
for (j=0; j<(int)notes.size()-1; j++) {
// iterate through each part, printing the module
// for adjacent parts.
counter += printLatticeModule(tempstream, notes, n, currentindex, j, j+1);
if (j < (int)notes.size()-2) {
printSpacer(tempstream);
}
}
if (!(rawQ || raw2Q)) {
if (counter == 0) {
m_humdrum_text << ".";
} else {
m_humdrum_text << tempstream.str();
}
}
return currentindex;
}
//////////////////////////////
//
// Tool_cint::printLatticeItem --
//
int Tool_cint::printLatticeItem(vector<vector<NoteNode> >& notes, int n, int currentindex,
int fileline) {
while ((currentindex < (int)notes[0].size())
&& (fileline > notes[0][currentindex].line)) {
currentindex++;
}
if (currentindex >= (int)notes[0].size()) {
if (!(rawQ || raw2Q)) {
m_humdrum_text << ".";
}
return currentindex;
}
if (notes[0][currentindex].line != fileline) {
// should never get here.
if (!(rawQ || raw2Q)) {
m_humdrum_text << "??";
}
return currentindex;
}
// found the index into notes which matches to the current fileline.
if (currentindex + n >= (int)notes[0].size()) {
// asking for chain longer than rest of available data.
if (!(rawQ || raw2Q)) {
m_humdrum_text << ".";
}
return currentindex;
}
int count;
int melcount;
int j;
if (parenQ) {
m_humdrum_text << "(";
}
for (count = 0; count < n; count++) {
// print harmonic intervals
if (hparenQ) {
m_humdrum_text << "[";
}
for (j=0; j<(int)notes.size()-1; j++) {
printInterval(m_humdrum_text, notes[j][currentindex+count],
notes[j+1][currentindex+count], INTERVAL_HARMONIC);
if (j < (int)notes.size()-2) {
printSpacer(m_humdrum_text);
}
}
if (hparenQ) {
m_humdrum_text << "]";
}
printSpacer(m_humdrum_text);
// print melodic intervals
if (mparenQ) {
m_humdrum_text << "{";
}
melcount = (int)notes.size()-1;
if (topQ) {
melcount++;
}
for (j=0; j<melcount; j++) {
printInterval(m_humdrum_text, notes[j][currentindex+count],
notes[j][currentindex+count+1], INTERVAL_MELODIC);
if (j < melcount-1) {
printSpacer(m_humdrum_text);
}
}
if (mparenQ) {
m_humdrum_text << "}";
}
printSpacer(m_humdrum_text);
}
// print last sequence of harmonic intervals
if (hparenQ) {
m_humdrum_text << "[";
}
for (j=0; j<(int)notes.size()-1; j++) {
printInterval(m_humdrum_text, notes[j][currentindex+n],
notes[j+1][currentindex+n], INTERVAL_HARMONIC);
if (j < (int)notes.size()-2) {
printSpacer(m_humdrum_text);
}
}
if (hparenQ) {
m_humdrum_text << "]";
}
if (parenQ) {
m_humdrum_text << ")";
}
if ((rawQ || raw2Q)) {
m_humdrum_text << "\n";
}
return currentindex;
}
//////////////////////////////
//
// Tool_cint::printInterval --
//
int Tool_cint::printInterval(ostream& out, NoteNode& note1, NoteNode& note2,
int type, int octaveadjust) {
if ((note1.b40 == REST) || (note2.b40 == REST)) {
out << RESTSTRING;
return 0;
}
int cross = 0;
int pitch1 = abs(note1.b40);
int pitch2 = abs(note2.b40);
int interval = pitch2 - pitch1;
if ((type == INTERVAL_HARMONIC) && (interval < 0)) {
cross = 1;
if (uncrossQ) {
interval = -interval;
}
} else {
interval = interval + octaveadjust * 40;
}
if ((type == INTERVAL_HARMONIC) && (octaveallQ)) {
if (interval <= -40) {
interval = interval + 4000;
}
if (interval > 40) {
if (interval % 40 == 0) {
interval = 40;
} else {
interval = interval % 40;
}
} else if (interval < 0) {
interval = interval + 40;
}
}
if (base12Q && !chromaticQ) {
interval = Convert::base40ToMidiNoteNumber(interval + 40*4 + 2) - 12*5;
if ((type == INTERVAL_HARMONIC) && (octaveallQ)) {
if (interval <= -12) {
interval = interval + 1200;
}
if (interval > 12) {
if (interval % 12 == 0) {
interval = 12;
} else {
interval = interval % 12;
}
} else if (interval < 0) {
interval = interval + 12;
}
}
interval = interval + octaveadjust * 12;
} else if (base7Q && !chromaticQ) {
interval = Convert::base40ToDiatonic(interval + 40*4 + 2) - 7*4;
if ((type == INTERVAL_HARMONIC) && (octaveallQ)) {
if (interval <= -7) {
interval = interval + 700;
}
if (interval > 7) {
if (interval % 7 == 0) {
interval = 7;
} else {
interval = interval % 7;
}
} else if (interval < 0) {
interval = interval + 7;
}
}
interval = interval + octaveadjust * 7;
}
if (chromaticQ) {
out << Convert::base40ToIntervalAbbr(interval);
} else {
int negative = 1;
if (interval < 0) {
negative = -1;
interval = -interval;
}
if (base7Q && !zeroQ) {
out << negative * (interval+1);
} else {
out << negative * interval;
}
}
if (sustainQ || ((type == INTERVAL_HARMONIC) && xoptionQ)) {
// print sustain/attack information of intervals.
if (note1.b40 < 0) {
out << "s";
} else {
out << "x";
}
if (note2.b40 < 0) {
out << "s";
} else {
out << "x";
}
}
return cross;
}
//////////////////////////////
//
// Tool_cint::printSpacer -- space or comma...
//
void Tool_cint::printSpacer(ostream& out) {
out << Spacer;
}
//////////////////////////////
//
// Tool_cint::printPitchGrid -- print the pitch grid from which all counterpoint
// modules are calculated.
//
void Tool_cint::printPitchGrid(vector<vector<NoteNode> >& notes, HumdrumFile& infile) {
int i = 0;
int j = 0;
int pitch;
int abspitch;
int newpitch;
int partcount;
int line;
double beat;
if (base40Q) {
partcount = (int)notes.size();
if (rhythmQ) {
m_humdrum_text << "**absq\t";
m_humdrum_text << "**bar\t";
m_humdrum_text << "**beat\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "**b40";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
for (i=0; i<(int)notes[0].size(); i++) {
if (rhythmQ) {
line = notes[0][i].line;
beat = infile[line].getDurationFromBarline().getFloat() * notes[0][i].beatsize + 1;
m_humdrum_text << infile[line].getDurationFromStart().getFloat() << "\t";
m_humdrum_text << notes[0][i].measure << "\t";
m_humdrum_text << beat << "\t";
}
for (j=0; j<(int)notes.size(); j++) {
if (notes[j][i].notemarker) {
m_humdrum_text << (char)notes[j][i].notemarker;
}
m_humdrum_text << notes[j][i].b40;
if (j < (int)notes.size()-1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
}
if (rhythmQ) {
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "*-";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
} else if (base7Q) {
partcount = (int)notes.size();
if (rhythmQ) {
m_humdrum_text << "**absq\t";
m_humdrum_text << "**bar\t";
m_humdrum_text << "**beat\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "**b7";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
for (i=0; i<(int)notes[0].size(); i++) {
if (rhythmQ) {
line = notes[0][i].line;
beat = infile[line].getDurationFromBarline().getFloat() * notes[0][i].beatsize + 1;
m_humdrum_text << infile[line].getDurationFromStart().getFloat() << "\t";
m_humdrum_text << notes[0][i].measure << "\t";
m_humdrum_text << beat << "\t";
}
for (j=0; j<(int)notes.size(); j++) {
if (notes[j][i].notemarker) {
m_humdrum_text << (char)notes[j][i].notemarker;
}
pitch = notes[j][i].b40;
abspitch = abs(pitch);
if (pitch == 0) {
// print rest
m_humdrum_text << 0;
} else {
newpitch = Convert::base40ToDiatonic(abspitch);
if (pitch < 0) {
newpitch = -newpitch;
}
m_humdrum_text << newpitch;
}
if (j < (int)notes.size()-1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
}
if (rhythmQ) {
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "*-";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
} else if (base12Q) {
partcount = (int)notes.size();
if (rhythmQ) {
m_humdrum_text << "**absq\t";
m_humdrum_text << "**bar\t";
m_humdrum_text << "**beat\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "**b12";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
for (i=0; i<(int)notes[0].size(); i++) {
if (rhythmQ) {
line = notes[0][i].line;
beat = infile[line].getDurationFromBarline().getFloat() * notes[0][i].beatsize + 1;
if (notes[j][i].notemarker) {
m_humdrum_text << (char)notes[j][i].notemarker;
}
m_humdrum_text << infile[line].getDurationFromStart() << "\t";
m_humdrum_text << notes[0][i].measure << "\t";
m_humdrum_text << beat << "\t";
}
for (j=0; j<(int)notes.size(); j++) {
if (notes[j][i].notemarker) {
m_humdrum_text << (char)notes[j][i].notemarker;
}
pitch = notes[j][i].b40;
if (pitch == 0) {
// print rest
m_humdrum_text << 0;
} else {
abspitch = abs(pitch);
newpitch = Convert::base40ToMidiNoteNumber(abspitch);
if (pitch < 0) {
newpitch = -newpitch;
}
m_humdrum_text << newpitch;
}
if (j < (int)notes.size()-1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
}
if (rhythmQ) {
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "*-";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
} else {
// print as Humdrum **kern data
partcount = (int)notes.size();
if (rhythmQ) {
m_humdrum_text << "**absq\t";
m_humdrum_text << "**bar\t";
m_humdrum_text << "**beat\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "**kern";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
for (i=0; i<(int)notes[0].size(); i++) {
if (rhythmQ) {
line = notes[0][i].line;
beat = infile[line].getDurationFromBarline().getFloat() * notes[0][i].beatsize + 1;
if (notes[j][i].notemarker) {
m_humdrum_text << (char)notes[j][i].notemarker;
}
m_humdrum_text << infile[line].getDurationFromStart() << "\t";
m_humdrum_text << notes[0][i].measure << "\t";
m_humdrum_text << beat << "\t";
}
for (j=0; j<(int)notes.size(); j++) {
if (notes[j][i].notemarker) {
m_humdrum_text << (char)notes[j][i].notemarker;
}
pitch = notes[j][i].b40;
abspitch = abs(pitch);
if (pitch == 0) {
m_humdrum_text << "r";
} else {
if ((pitch > 0) && (i<(int)notes[j].size()-1) &&
(notes[j][i+1].b40 == -abspitch)) {
// start of a note which continues into next
// sonority.
m_humdrum_text << "[";
}
m_humdrum_text << Convert::base40ToKern(abspitch);
// print tie continue/termination as necessary.
if (pitch < 0) {
if ((i < (int)notes[j].size() - 1) &&
(notes[j][i+1].b40 == notes[j][i].b40)) {
// note sustains further
m_humdrum_text << "_";
} else {
// note does not sustain any further.
m_humdrum_text << "]";
}
}
}
if (j < (int)notes.size()-1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
}
if (rhythmQ) {
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
m_humdrum_text << "*-\t";
}
for (i=0; i<partcount; i++) {
m_humdrum_text << "*-";
if (i < partcount - 1) {
m_humdrum_text << "\t";
}
}
m_humdrum_text << endl;
}
}
//////////////////////////////
//
// Tool_cint::extractNoteArray --
//
void Tool_cint::extractNoteArray(vector<vector<NoteNode> >& notes, HumdrumFile& infile,
vector<int>& ktracks, vector<int>& reverselookup) {
HumRegex hre;
Ids.resize(infile.getTrackCount()+1);
int i, j, ii, jj;
for (i=0; i<(int)Ids.size(); i++) {
Ids[i] = EMPTY_ID;
}
vector<NoteNode> current(ktracks.size());
vector<double> beatsizes(infile.getTrackCount()+1, 1);
int sign;
int track = 0;
int index;
int snum = 0;
int measurenumber = 0;
int tempmeasurenum = 0;
double beatsize = 1.0;
int topnum, botnum;
for (i=0; i<infile.getLineCount(); i++) {
if (debugQ) {
m_humdrum_text << "PROCESSING LINE: " << i << "\t" << infile[i] << endl;
}
if (infile[i].isBarline()) {
tempmeasurenum = infile.getMeasureNumber(i);
if (tempmeasurenum >= 0) {
measurenumber = tempmeasurenum;
}
}
for (j=0; j<(int)current.size(); j++) {
current[j].clear();
current[j].measure = measurenumber;
current[j].line = i;
}
if (infile[i].isBarline() && (infile.token(i, 0)->find("||") != string::npos)) {
// double barline (terminal for Josquin project), so add a row
// of rests to prevent cint melodic interval identification between
// adjacent notes in different sections.
for (j=0; j<(int)notes.size(); j++) {
notes[j].push_back(current[j]);
}
} else if (infile[i].isInterpretation()) {
// search for time signatures from which to extract beat information.
for (j=0; j<infile[i].getFieldCount(); j++) {
track = infile.token(i, j)->getTrack();
if (hre.search(*infile.token(i, j), "^\\*M(\\d+)/(\\d+)")) {
// deal with 3%2 in denominator later...
topnum = hre.getMatchInt(1);
botnum = hre.getMatchInt(2);
beatsize = botnum;
if (((topnum % 3) == 0) && (topnum > 3) && (botnum > 1)) {
// compound meter
// fix later
beatsize = botnum / 3;
}
beatsizes[track] = beatsize / 4.0;
} else if (*infile.token(i, j) == "*met(C|)") {
// MenCutC, use 2 as the "beat"
beatsizes[track] = 2.0 / 4.0;
}
}
} else if (idQ && infile[i].isLocalComment()) {
for (j=0; j<infile[i].getFieldCount(); j++) {
if (hre.search(*infile.token(i, j), "^!ID:\\s*([^\\s]*)")) {
int track = infile.token(i, j)->getTrack();
Ids[track] = hre.getMatch(1);
}
}
}
if (!infile[i].isData()) {
continue;
}
for (j=0; j<infile[i].getFieldCount(); j++) {
sign = 1;
if (!infile.token(i, j)->isKern()) {
continue;
}
track = infile.token(i, j)->getTrack();
index = reverselookup[track];
if (index < 0) {
continue;
}
if (idQ) {
current[index].getId() = Ids[track];
Ids[track] = ""; // don't assign to next item;
}
current[index].line = i;
current[index].spine = j;
current[index].beatsize = beatsizes[track];
if (infile.token(i, j)->isNull()) {
sign = -1;
HTp nullx = infile.token(i, j)->resolveNull();
if (nullx == NULL) {
ii = jj = -1;
} else {
ii = nullx->getLineIndex();
jj = nullx->getFieldIndex();
}
} else {
ii = i;
jj = j;
}
if (infile.token(ii, jj)->find(NoteMarker) != string::npos) {
current[index].notemarker = NoteMarker;
}
if (infile.token(ii, jj)->find('r') != string::npos) {
current[index].b40 = 0;
current[index].serial = ++snum;
continue;
}
if (*infile.token(ii, jj) == ".") {
current[index].b40 = 0;
current[index].serial = snum;
}
current[index].b40 = Convert::kernToBase40(*infile.token(ii, jj));
if (infile.token(ii, jj)->find('_') != string::npos) {
sign = -1;
current[index].serial = snum;
}
if (infile.token(ii, jj)->find(']') != string::npos) {
sign = -1;
current[index].serial = snum;
}
current[index].b40 *= sign;
if (sign > 0) {
current[index].serial = ++snum;
if (durationQ) {
current[index].duration = infile.token(ii, jj)->getTiedDuration();
}
}
}
if (onlyRests(current) && onlyRests(notes.back())) {
// don't store more than one row of rests in the data array.
continue;
}
if (allSustained(current)) {
// don't store sonorities which are purely sutained
// (may need to be updated with a --sustain option implementation)
continue;
}
for (j=0; j<(int)notes.size(); j++) {
notes[j].push_back(current[j]);
}
}
// attach ID tag to all sustain sections of notes
if (idQ) {
for (j=0; j<(int)notes.size(); j++) {
for (i=1; i<(int)notes[j].size(); i++) {
if (notes[j][i].isAttack()) {
continue;
}
if ((int)notes[j][i].getId().size() > 0) {
// allow for Ids on sustained notes which probably means
// that there is a written tied note in the music.
continue;
}
if (notes[j][i].getB40() == notes[j][i-1].getB40()) {
notes[j][i].getId() = notes[j][i-1].getId();
}
}
}
}
}
//////////////////////////////
//
// Tool_cint::onlyRests -- returns true if all NoteNodes are for rests
//
int Tool_cint::onlyRests(vector<NoteNode>& data) {
int i;
for (i=0; i<(int)data.size(); i++) {
if (!data[i].isRest()) {
return 0;
}
}
return 1;
}
//////////////////////////////
//
// Tool_cint::hasAttack -- returns true if at least one NoteNode has
// has an attack.
//
int Tool_cint::hasAttack(vector<NoteNode>& data) {
int i;
for (i=0; i<(int)data.size(); i++) {
if (data[i].isAttack()) {
return 1;
}
}
return 0;
}
//////////////////////////////
//
// Tool_cint::allSustained -- returns true if all NoteNodes are sustains
// or rests (but not all rests).
//
int Tool_cint::allSustained(vector<NoteNode>& data) {
int i;
int hasnote = 0;
for (i=0; i<(int)data.size(); i++) {
if (data[i].b40 != 0) {
hasnote = 1;
}
if (data[i].isAttack()) {
return 0;
}
}
if (hasnote == 0) {
return 0;
}
return 1;
}
//////////////////////////////
//
// Tool_cint::getAbbreviations --
//
void Tool_cint::getAbbreviations(vector<string>& abbreviations,
vector<string>& names) {
abbreviations.resize(names.size());
for (int i=0; i<(int)names.size(); i++) {
getAbbreviation(abbreviations[i], names[i]);
}
}
//////////////////////////////
//
// Tool_cint::getAbbreviation --
//
void Tool_cint::getAbbreviation(string& abbr, string& name) {
HumRegex hre;
hre.replaceDestructive(abbr, "(?<=[a-zA-Z])[a-zA-Z]*", "");
hre.tr(abbr, "123456789", "abcdefghi");
}
//////////////////////////////
//
// Tool_cint::getKernTracks -- return a list of track number for **kern spines.
//
void Tool_cint::getKernTracks(vector<int>& ktracks, HumdrumFile& infile) {
int i, j;
ktracks.reserve(infile.getTrackCount()+1);
ktracks.resize(0);
int track;
for (i=0; i<infile.getLineCount(); i++) {
if (!infile[i].isInterpretation()) {
continue;
}
for (j=0; j<infile[i].getFieldCount(); j++) {
if (infile.token(i, j)->isKern()) {
track = infile.token(i, j)->getTrack();
ktracks.push_back(track);
}
}
break;
}
}
//////////////////////////////
//
// Tool_cint::getNames -- get the names of each column if they have one.
//
void Tool_cint::getNames(vector<string>& names, vector<int>& reverselookup,
HumdrumFile& infile) {
names.resize((int)reverselookup.size()-1);
char buffer[1024] = {0};
int value;
HumRegex pre;
int i;
int j;
int track;
for (i=0; i<(int)names.size(); i++) {
value = (int)reverselookup.size() - i;
sprintf(buffer, "%d", value);
names[i] = buffer;
}
for (i=0; i<infile.getLineCount(); i++) {
if (infile[i].isData()) {
// stop looking for instrument name after the first data line
break;
}
if (!infile[i].isInterpretation()) {
continue;
}
for (j=0; j<infile[i].getFieldCount(); j++) {
if (reverselookup[infile.token(i, j)->getTrack()] < 0) {
continue;
}
if (!infile.token(i, j)->isKern()) {
continue;
}
if (pre.search(*infile.token(i, j), "^\\*I\"(.*)")) {
track = infile.token(i, j)->getTrack();
names[reverselookup[track]] = pre.getMatch(1);
}
}
}
if (debugQ) {
for (i=0; i<(int)names.size(); i++) {
m_humdrum_text << i << ":\t" << names[i] << endl;
}
}
}
//////////////////////////////
//
// Tool_cint::initialize -- validate and process command-line options.
//
void Tool_cint::initialize(void) {
// handle basic options:
if (getBoolean("author")) {
m_humdrum_text << "Written by Craig Stuart Sapp, "
<< "craig@ccrma.stanford.edu, September 2013" << endl;
exit(0);
} else if (getBoolean("version")) {
m_humdrum_text << getCommand() << ", version: 31 May 2017" << endl;
m_humdrum_text << "compiled: " << __DATE__ << endl;
exit(0);
} else if (getBoolean("help")) {
usage(getCommand());
exit(0);
} else if (getBoolean("example")) {
example();
exit(0);
}
koptionQ = getBoolean("koption");
if (getBoolean("comma")) {
Spacer = ",";
} else {
Spacer = " ";
}
// dispay as base-7 by default
base7Q = 1;
base40Q = getBoolean("base-40");
base12Q = getBoolean("base-12");
chromaticQ = getBoolean("chromatic");
zeroQ = getBoolean("zero");
if (base40Q) {
base12Q = 0;
base7Q = 0;
zeroQ = 0;
}
if (base12Q) {
base40Q = 0;
base7Q = 0;
zeroQ = 0;
}
pitchesQ = getBoolean("pitches");
debugQ = getBoolean("debug");
rhythmQ = getBoolean("rhythm");
durationQ = getBoolean("duration");
latticeQ = getBoolean("lattice");
sustainQ = getBoolean("sustain");
topQ = getBoolean("top");
toponlyQ = getBoolean("top-only");
hparenQ = getBoolean("harmonic-parentheses");
mparenQ = getBoolean("melodic-parentheses");
parenQ = getBoolean("parentheses");
rowsQ = getBoolean("rows");
hmarkerQ = getBoolean("harmonic-marker");
interleavedQ = getBoolean("interleaved-lattice");
mmarkerQ = getBoolean("melodic-marker");
attackQ = getBoolean("attacks");
rawQ = getBoolean("raw");
raw2Q = getBoolean("raw2");
xoptionQ = getBoolean("x");
octaveallQ = getBoolean("octave-all");
octaveQ = getBoolean("octave");
noharmonicQ = getBoolean("no-harmonic");
nomelodicQ = getBoolean("no-melodic");
norestsQ = getBoolean("no-rests");
nounisonsQ = getBoolean("no-melodic-unisons");
Chaincount = getInteger("n");
searchQ = getBoolean("search");
markQ = getBoolean("mark");
idQ = getBoolean("id");
countQ = getBoolean("count");
filenameQ = getBoolean("filename");
suspensionsQ = getBoolean("suspensions");
uncrossQ = getBoolean("uncross");
locationQ = getBoolean("location");
retroQ = getBoolean("retrospective");
NoteMarker = 0;
if (getBoolean("note-marker")) {
NoteMarker = getString("note-marker").c_str()[0];
}
if (Chaincount < 0) {
Chaincount = 0;
}
if (searchQ) {
// Automatically assume marking of --search is used
// (may change in the future).
markQ = 1;
}
if (countQ) {
searchQ = 1;
markQ = 0;
}
if (raw2Q) {
norestsQ = 1;
}
if (searchQ) {
SearchString = getString("search");
}
}
//////////////////////////////
//
// Tool_cint::example -- example usage of the quality program
//
void Tool_cint::example(void) {
m_humdrum_text <<
" \n"
<< endl;
}
//////////////////////////////
//
// Tool_cint::usage -- gives the usage statement for the meter program
//
void Tool_cint::usage(const string& command) {
m_humdrum_text <<
" \n"
<< endl;
}
// END_MERGE
} // end namespace hum
| 24.253737 | 93 | 0.583965 | [
"vector"
] |
333598349f3833cb52074edcecccc9323c212756 | 6,512 | cpp | C++ | SOURCE/ArchitectMineBaron.cpp | OnionBurger/DungeonsOfPain | cb56c138a12bdc08376a2ba04f02d24527344202 | [
"MIT"
] | null | null | null | SOURCE/ArchitectMineBaron.cpp | OnionBurger/DungeonsOfPain | cb56c138a12bdc08376a2ba04f02d24527344202 | [
"MIT"
] | null | null | null | SOURCE/ArchitectMineBaron.cpp | OnionBurger/DungeonsOfPain | cb56c138a12bdc08376a2ba04f02d24527344202 | [
"MIT"
] | null | null | null | #include "ArchitectMineBaron.h"
#include "getRand.h"
#include "MinerRect.h"
ArchitectMineBaron::ArchitectMineBaron(bool lastLevel) {
lastLvl = lastLevel;
occup = 0;
}
void ArchitectMineBaron::generate() {
sizeX = 20;
sizeY = 20;
allocate();
allocateOccup();
fillWith(T_WALL);
placeStartHall();
++lastOccupToken;
unsigned roomCnt = 0;
unsigned consecutiveFails = 0;
while (roomCnt < 8 && consecutiveFails < 5 && !gateQueue.empty()) {
Miner *miner = pickMiner();
t_point gate = pickGate();
if (miner->doMining(gate)) {
putDoor(gate);
planGatesFromMiner(miner);
++lastOccupToken;
consecutiveFails = 0;
++roomCnt;
} else {
++consecutiveFails;
}
}
if (!lastLvl) placeStairs();
removeWaitingDoors();
}
bool ArchitectMineBaron::digOut(unsigned x, unsigned y) {
if (!isFree(x, y)) return false;
lvl[x][y] = T_EMPTY;
occup[x][y] = lastOccupToken;
return true;
}
bool ArchitectMineBaron::isUnoccupied(unsigned x, unsigned y) const {
return occup[x][y] < 0;
}
bool ArchitectMineBaron::isFree(unsigned x, unsigned y) const {
if (x < 1 || y < 1 || x + 1 >= sizeX || y + 1 >= sizeY) return false;
return isUnoccupied(x, y) || occup[x][y] == lastOccupToken;
}
bool ArchitectMineBaron::ownWall(unsigned x, unsigned y) {
if (!isFree(x, y)) return false;
if (lvl[x][y] != T_WALL) return false;
occup[x][y] = lastOccupToken;
return true;
}
bool ArchitectMineBaron::placeEnemy(unsigned x, unsigned y) {
if (x < 1 || y < 1 || x + 1 >= sizeX || y + 1 >= sizeY) return false;
if (occup[x][y] != lastOccupToken) return false;
if (lvl[x][y] != T_EMPTY) return false;
locsEnemy.push_back(t_point(x, y));
return true;
}
bool ArchitectMineBaron::placeItem(unsigned x, unsigned y) {
if (x < 1 || y < 1 || x + 1 >= sizeX || y + 1 >= sizeY) return false;
if (occup[x][y] != lastOccupToken) return false;
if (lvl[x][y] != T_EMPTY) return false;
locsItem.push_back(t_point(x, y));
return true;
}
bool ArchitectMineBaron::planGate(unsigned x, unsigned y) {
if (x < 2 || y < 2 || x + 2 >= sizeX || y + 2 >= sizeY) return false;
if (!isFree(x, y)) return false;
if (lvl[x][y] != T_WALL) return false;
gateQueue.push_back(t_point(x, y));
occup[x][y] = lastOccupToken;
return true;
}
void ArchitectMineBaron::placeStartHall() {
t_point startHallPos;
startHallPos.first = 1 + getRandUnsigned(sizeX - 2 - 5);
startHallPos.second = 1 + getRandUnsigned(sizeY - 2 - 5);
for (unsigned i = 1; i <= 3; ++i)
for (unsigned j = 1; j <= 3; ++j)
digOut(startHallPos.first + i, startHallPos.second + j);
ownWall(startHallPos.first + 0, startHallPos.second + 0);
ownWall(startHallPos.first + 0, startHallPos.second + 4);
ownWall(startHallPos.first + 4, startHallPos.second + 0);
ownWall(startHallPos.first + 4, startHallPos.second + 4);
for (unsigned i = 1; i <= 3; ++i) {
planGate(startHallPos.first + i, startHallPos.second + 0);
planGate(startHallPos.first + i, startHallPos.second + 4);
planGate(startHallPos.first + 0, startHallPos.second + i);
planGate(startHallPos.first + 4, startHallPos.second + i);
}
locPlayer = t_point(startHallPos.first + 2, startHallPos.second + 2);
}
Miner* ArchitectMineBaron::pickMiner() {
return new MinerRect(this);
}
Architect::t_point ArchitectMineBaron::pickGate() {
unsigned ind = getRandUnsigned(gateQueue.size());
t_point ret = gateQueue[ind];
if (ind + 1 < gateQueue.size()) gateQueue[ind] = gateQueue[gateQueue.size() - 1];
gateQueue.pop_back();
return ret;
}
void ArchitectMineBaron::planGatesFromMiner(Miner *miner) {
for (unsigned i = 0; i < miner->getGates().size(); ++i)
planGate(miner->getGates()[i]);
}
void ArchitectMineBaron::putDoor(const t_point &gate) {
lvl[gate.first][gate.second] = T_DOOR;
}
void ArchitectMineBaron::placeStairs() {
if (locsItem.empty()) {
locStairs = locPlayer;
} else {
unsigned index = getRandUnsigned(locsItem.size());
locStairs = locsItem[index];
if (index + 1 < locsItem.size()) locsItem[index] = locsItem[locsItem.size() - 1];
locsItem.pop_back();
}
}
/*void ArchitectMineBaron::placeStuff() {
gatherSpawnPlaces();
shuffleSpawnPlaces();
if (spawnPlaces.empty()) {
if (!lastLvl) locStairs = locPlayer;
return;
}
if (!lastLvl) locStairs = spawnPlaces[0];
unsigned enemies = 5, items = 3;
for (unsigned i = 0; i < enemies; ++i)
locsEnemy.push_back(spawnPlaces[1 + i]);
for (unsigned i = 0; i < items; ++i)
locsItem.push_back(spawnPlaces[1 + enemies + i]);
}
void ArchitectMineBaron::gatherSpawnPlaces() {
// allocate an array of booleans
bool **spawn;
spawn = new bool*[sizeX];
for (unsigned i = 0; i < sizeX; ++i) {
spawn[i] = new bool[sizeY];
// everything is good for spawning at first
for (unsigned j = 0; j < sizeY; ++j) {
spawn[i][j] = true;
}
}
// uncheck walls, doors, everything outside of rooms and inside starting hall
// also, we don't want anything to spawn adjacent to a door
for (unsigned i = 0; i < sizeX; ++i) {
for (unsigned j = 0; j < sizeY; ++j) {
if (lvl[i][j] == T_DOOR) {
spawn[i][j] = false;
if (i > 0) spawn[i - 1][j] = false;
if (i + 1 < sizeX) spawn[i + 1][j] = false;
if (j > 0) spawn[i][j - 1] = false;
if (j + 1 < sizeY) spawn[i][j + 1] = false;
} else if (lvl[i][j] != T_EMPTY || occup[i][j] <= 0) {
spawn[i][j] = false;
}
}
}
// now add those places to the vector
for (unsigned i = 0; i < sizeX; ++i) {
for (unsigned j = 0; j < sizeY; ++j) {
if (spawn[i][j]) spawnPlaces.push_back(Architect::t_point(i, j));
}
}
// delete the array of booleans
for (unsigned i = 0; i < sizeX; ++i) delete [] spawn[i];
delete [] spawn;
}
void ArchitectMineBaron::shuffleSpawnPlaces() {
for (unsigned i = 1; i < spawnPlaces.size(); ++i) {
unsigned index = getRandUnsigned(i + 1);
if (index != i) {
t_point tmp = spawnPlaces[index];
spawnPlaces[index] = spawnPlaces[i];
spawnPlaces[i] = tmp;
}
}
}*/
void ArchitectMineBaron::removeWaitingDoors() {
for (unsigned i = 0; i < gateQueue.size(); ++i)
lvl[gateQueue[i].first][gateQueue[i].second] = T_WALL;
}
void ArchitectMineBaron::allocateOccup() {
occup = new int*[sizeX];
lastOccupToken = 0;
for (unsigned i = 0; i < sizeX; ++i) {
occup[i] = new int[sizeY];
for (unsigned j = 0; j < sizeY; ++j) {
occup[i][j] = -1;
}
}
}
void ArchitectMineBaron::clearOccup() {
if (occup) {
for (unsigned i = 0; i < sizeX; ++i)
delete [] occup[i];
delete [] occup;
lvl = 0;
}
}
ArchitectMineBaron::~ArchitectMineBaron() {
clearOccup();
} | 25.142857 | 83 | 0.646652 | [
"vector"
] |
3337997811ee99783c795922eb369255a40e1724 | 14,472 | cpp | C++ | Code/Editor/Controls/ConsoleSCBMFC.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 1 | 2022-03-12T14:13:45.000Z | 2022-03-12T14:13:45.000Z | Code/Editor/Controls/ConsoleSCBMFC.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | 2 | 2022-01-13T04:29:38.000Z | 2022-03-12T01:05:31.000Z | Code/Editor/Controls/ConsoleSCBMFC.cpp | sandeel31/o3de | db88812d61eef77c6f4451b7f8c7605d6db07412 | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "EditorDefs.h"
#include "ConsoleSCBMFC.h"
#include "PropertiesDialog.h"
#include "QtViewPaneManager.h"
#include "Core/QtEditorApplication.h"
#include <Controls/ui_ConsoleSCBMFC.h>
#include <QtUtil.h>
#include <QtUtilWin.h>
#include <QtCore/QStringList>
#include <QtCore/QScopedPointer>
#include <QtCore/QPoint>
#include <QtGui/QCursor>
#include <QtGui/QMouseEvent>
#include <QtWidgets/QStyle>
#include <QtWidgets/QStyleFactory>
#include <QtWidgets/QMenu>
#include <QtWidgets/QScrollBar>
#include <QtWidgets/QVBoxLayout>
#include <vector>
#include <iostream>
namespace MFC
{
static CPropertiesDialog* gPropertiesDlg = nullptr;
static CString mfc_popup_helper(HWND hwnd, int x, int y);
static CConsoleSCB* s_consoleSCB = nullptr;
static QString RemoveColorCode(const QString& text, int& iColorCode)
{
QString cleanString;
cleanString.reserve(text.size());
const int textSize = text.size();
for (int i = 0; i < textSize; ++i)
{
QChar c = text.at(i);
bool isLast = i == textSize - 1;
if (c == '$' && !isLast && text.at(i + 1).isDigit())
{
if (iColorCode == 0)
{
iColorCode = text.at(i + 1).digitValue();
}
++i;
continue;
}
if (c == '\r' || c == '\n')
{
++i;
continue;
}
cleanString.append(c);
}
return cleanString;
}
ConsoleLineEdit::ConsoleLineEdit(QWidget* parent)
: QLineEdit(parent)
, m_historyIndex(0)
, m_bReusedHistory(false)
{
}
void ConsoleLineEdit::mousePressEvent(QMouseEvent* ev)
{
if (ev->type() == QEvent::MouseButtonPress && ev->button() & Qt::RightButton)
{
Q_EMIT variableEditorRequested();
}
QLineEdit::mousePressEvent(ev);
}
void ConsoleLineEdit::mouseDoubleClickEvent(QMouseEvent* ev)
{
Q_EMIT variableEditorRequested();
}
bool ConsoleLineEdit::event(QEvent* ev)
{
// Tab key doesn't go to keyPressEvent(), must be processed here
if (ev->type() != QEvent::KeyPress)
{
return QLineEdit::event(ev);
}
QKeyEvent* ke = static_cast<QKeyEvent*>(ev);
if (ke->key() != Qt::Key_Tab)
{
return QLineEdit::event(ev);
}
QString inputStr = text();
QString newStr;
QStringList tokens = inputStr.split(" ");
inputStr = tokens.isEmpty() ? QString() : tokens.first();
IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
const bool ctrlPressed = ke->modifiers() & Qt::ControlModifier;
CString cstring = QtUtil::ToCString(inputStr); // TODO: Use QString once the backend stops using QString
if (ctrlPressed)
{
newStr = QtUtil::ToString(console->AutoCompletePrev(cstring));
}
else
{
newStr = QtUtil::ToString(console->ProcessCompletion(cstring));
newStr = QtUtil::ToString(console->AutoComplete(cstring));
if (newStr.isEmpty())
{
newStr = QtUtil::ToQString(GetIEditor()->GetCommandManager()->AutoComplete(QtUtil::ToString(newStr)));
}
}
if (!newStr.isEmpty())
{
newStr += " ";
setText(newStr);
}
deselect();
return true;
}
void ConsoleLineEdit::keyPressEvent(QKeyEvent* ev)
{
IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
auto commandManager = GetIEditor()->GetCommandManager();
console->ResetAutoCompletion();
switch (ev->key())
{
case Qt::Key_Enter:
case Qt::Key_Return:
{
QString str = text().trimmed();
if (!str.isEmpty())
{
if (commandManager->IsRegistered(QtUtil::ToCString(str)))
{
commandManager->Execute(QtUtil::ToString(str));
}
else
{
CLogFile::WriteLine(QtUtil::ToCString(str));
GetIEditor()->GetSystem()->GetIConsole()->ExecuteString(QtUtil::ToCString(str));
}
// If a history command was reused directly via up arrow enter, do not reset history index
if (m_history.size() > 0 && m_historyIndex < m_history.size() && m_history[m_historyIndex] == str)
{
m_bReusedHistory = true;
}
else
{
m_historyIndex = m_history.size();
}
// Do not add the same string if it is the top of the stack, but allow duplicate entries otherwise
if (m_history.isEmpty() || m_history.back() != str)
{
m_history.push_back(str);
if (!m_bReusedHistory)
{
m_historyIndex = m_history.size();
}
}
}
else
{
m_historyIndex = m_history.size();
}
setText(QString());
break;
}
case Qt::Key_AsciiTilde: // ~
case Qt::Key_Agrave: // `
// disable log.
GetIEditor()->ShowConsole(false);
setText(QString());
m_historyIndex = m_history.size();
break;
case Qt::Key_Escape:
setText(QString());
m_historyIndex = m_history.size();
break;
case Qt::Key_Up:
DisplayHistory(false /*bForward*/);
break;
case Qt::Key_Down:
DisplayHistory(true /*bForward*/);
break;
default:
QLineEdit::keyPressEvent(ev);
}
}
void ConsoleLineEdit::DisplayHistory(bool bForward)
{
if (m_history.isEmpty())
{
return;
}
// Immediately after reusing a history entry, ensure up arrow re-displays command just used
if (!m_bReusedHistory || bForward)
{
m_historyIndex = static_cast<unsigned int>(clamp_tpl(static_cast<int>(m_historyIndex) + (bForward ? 1 : -1), 0, m_history.size() - 1));
}
m_bReusedHistory = false;
setText(m_history[m_historyIndex]);
}
ConsoleTextEdit::ConsoleTextEdit(QWidget* parent)
: QTextEdit(parent)
{
}
Lines CConsoleSCB::s_pendingLines;
CConsoleSCB::CConsoleSCB(QWidget* parent)
: QWidget(parent)
, ui(new Ui::ConsoleMFC())
, m_richEditTextLength(0)
, m_backgroundTheme(gSettings.consoleBackgroundColorTheme)
{
m_lines = s_pendingLines;
s_pendingLines.clear();
s_consoleSCB = this;
ui->setupUi(this);
setMinimumHeight(120);
// Setup the color table for the default (light) theme
m_colorTable << QColor(0, 0, 0)
<< QColor(0, 0, 0)
<< QColor(0, 0, 200) // blue
<< QColor(0, 200, 0) // green
<< QColor(200, 0, 0) // red
<< QColor(0, 200, 200) // cyan
<< QColor(128, 112, 0) // yellow
<< QColor(200, 0, 200) // red+blue
<< QColor(0x000080ff)
<< QColor(0x008f8f8f);
OnStyleSettingsChanged();
connect(ui->button, &QPushButton::clicked, this, &CConsoleSCB::showVariableEditor);
connect(ui->lineEdit, &MFC::ConsoleLineEdit::variableEditorRequested, this, &MFC::CConsoleSCB::showVariableEditor);
connect(Editor::EditorQtApplication::instance(), &Editor::EditorQtApplication::skinChanged, this, &MFC::CConsoleSCB::OnStyleSettingsChanged);
if (GetIEditor()->IsInConsolewMode())
{
// Attach / register edit box
//CLogFile::AttachEditBox(m_edit.GetSafeHwnd()); // FIXME
}
}
CConsoleSCB::~CConsoleSCB()
{
s_consoleSCB = nullptr;
delete gPropertiesDlg;
gPropertiesDlg = nullptr;
CLogFile::AttachEditBox(nullptr);
}
void CConsoleSCB::RegisterViewClass()
{
QtViewOptions opts;
opts.preferedDockingArea = Qt::BottomDockWidgetArea;
opts.isDeletable = false;
opts.isStandard = true;
opts.showInMenu = true;
opts.builtInActionId = ID_VIEW_CONSOLEWINDOW;
opts.sendViewPaneNameBackToAmazonAnalyticsServers = true;
RegisterQtViewPane<CConsoleSCB>(GetIEditor(), LyViewPane::Console, LyViewPane::CategoryTools, opts);
}
void CConsoleSCB::OnStyleSettingsChanged()
{
ui->button->setIcon(QIcon(QString(":/controls/img/cvar_dark.bmp")));
// Set the debug/warning text colors appropriately for the background theme
// (e.g. not have black text on black background)
QColor textColor = Qt::black;
m_backgroundTheme = gSettings.consoleBackgroundColorTheme;
if (m_backgroundTheme == SEditorSettings::ConsoleColorTheme::Dark)
{
textColor = Qt::white;
}
m_colorTable[0] = textColor;
m_colorTable[1] = textColor;
QColor bgColor;
if (!GetIEditor()->IsInConsolewMode() && CConsoleSCB::GetCreatedInstance() && m_backgroundTheme == SEditorSettings::ConsoleColorTheme::Dark)
{
bgColor = Qt::black;
}
else
{
bgColor = Qt::white;
}
ui->textEdit->setStyleSheet(QString("QTextEdit{ background: %1 }").arg(bgColor.name(QColor::HexRgb)));
// Clear out the console text when we change our background color since
// some of the previous text colors may not be appropriate for the
// new background color
ui->textEdit->clear();
}
void CConsoleSCB::showVariableEditor()
{
const QPoint cursorPos = QCursor::pos();
CString str = mfc_popup_helper(0, cursorPos.x(), cursorPos.y());
if (!str.IsEmpty())
{
ui->lineEdit->setText(QtUtil::ToQString(str));
}
}
void CConsoleSCB::SetInputFocus()
{
ui->lineEdit->setFocus();
ui->lineEdit->setText(QString());
}
void CConsoleSCB::AddToConsole(const QString& text, bool bNewLine)
{
m_lines.push_back({ text, bNewLine });
FlushText();
}
void CConsoleSCB::FlushText()
{
if (m_lines.empty())
{
return;
}
// Store our current cursor in case we need to restore it, and check if
// the user has scrolled the text edit away from the bottom
const QTextCursor oldCursor = ui->textEdit->textCursor();
QScrollBar* scrollBar = ui->textEdit->verticalScrollBar();
const int oldScrollValue = scrollBar->value();
bool scrolledOffBottom = oldScrollValue != scrollBar->maximum();
ui->textEdit->moveCursor(QTextCursor::End);
QTextCursor textCursor = ui->textEdit->textCursor();
while (!m_lines.empty())
{
ConsoleLine line = m_lines.front();
m_lines.pop_front();
int iColor = 0;
QString text = MFC::RemoveColorCode(line.text, iColor);
if (iColor < 0 || iColor >= m_colorTable.size())
{
iColor = 0;
}
if (line.newLine)
{
text = QtUtil::trimRight(text);
text = "\r\n" + text;
}
QTextCharFormat format;
const QColor color(m_colorTable[iColor]);
format.setForeground(color);
if (iColor != 0)
{
format.setFontWeight(QFont::Bold);
}
textCursor.setCharFormat(format);
textCursor.insertText(text);
}
// If the user has selected some text in the text edit area or has scrolled
// away from the bottom, then restore the previous cursor and keep the scroll
// bar in the same location
if (oldCursor.hasSelection() || scrolledOffBottom)
{
ui->textEdit->setTextCursor(oldCursor);
scrollBar->setValue(oldScrollValue);
}
// Otherwise scroll to the bottom so the latest text can be seen
else
{
scrollBar->setValue(scrollBar->maximum());
}
}
QSize CConsoleSCB::minimumSizeHint() const
{
return QSize(-1, -1);
}
QSize CConsoleSCB::sizeHint() const
{
return QSize(100, 100);
}
/** static */
void CConsoleSCB::AddToPendingLines(const QString& text, bool bNewLine)
{
s_pendingLines.push_back({ text, bNewLine });
}
static CVarBlock* VarBlockFromConsoleVars()
{
IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
std::vector<const char*> cmds;
cmds.resize(console->GetNumVars());
size_t cmdCount = console->GetSortedVars(&cmds[0], cmds.size());
CVarBlock* vb = new CVarBlock;
IVariable* pVariable = 0;
for (int i = 0; i < cmdCount; i++)
{
ICVar* pCVar = console->GetCVar(cmds[i]);
if (!pCVar)
{
continue;
}
int varType = pCVar->GetType();
switch (varType)
{
case CVAR_INT:
pVariable = new CVariable<int>();
pVariable->Set(pCVar->GetIVal());
break;
case CVAR_FLOAT:
pVariable = new CVariable<float>();
pVariable->Set(pCVar->GetFVal());
break;
case CVAR_STRING:
pVariable = new CVariable<CString>();
pVariable->Set(pCVar->GetString());
break;
default:
assert(0);
}
pVariable->SetDescription(pCVar->GetHelp());
pVariable->SetName(cmds[i]);
if (pVariable)
{
vb->AddVariable(pVariable);
}
}
return vb;
}
static void OnConsoleVariableUpdated(IVariable* pVar)
{
if (!pVar)
{
return;
}
CString varName = pVar->GetName();
ICVar* pCVar = GetIEditor()->GetSystem()->GetIConsole()->GetCVar(varName);
if (!pCVar)
{
return;
}
if (pVar->GetType() == IVariable::INT)
{
int val;
pVar->Get(val);
pCVar->Set(val);
}
else if (pVar->GetType() == IVariable::FLOAT)
{
float val;
pVar->Get(val);
pCVar->Set(val);
}
else if (pVar->GetType() == IVariable::STRING)
{
CString val;
pVar->Get(val);
pCVar->Set(val);
}
}
static CString mfc_popup_helper(HWND hwnd, int x, int y)
{
IConsole* console = GetIEditor()->GetSystem()->GetIConsole();
TSmartPtr<CVarBlock> vb = VarBlockFromConsoleVars();
XmlNodeRef node;
if (!gPropertiesDlg)
{
gPropertiesDlg = new CPropertiesDialog("Console Variables", node, AfxGetMainWnd(), true);
}
if (!gPropertiesDlg->m_hWnd)
{
gPropertiesDlg->Create(CPropertiesDialog::IDD, AfxGetMainWnd());
gPropertiesDlg->SetUpdateCallback(AZStd::bind(OnConsoleVariableUpdated, AZStd::placeholders::_1));
}
gPropertiesDlg->ShowWindow(SW_SHOW);
gPropertiesDlg->BringWindowToTop();
gPropertiesDlg->GetPropertyCtrl()->AddVarBlock(vb);
return "";
}
CConsoleSCB* CConsoleSCB::GetCreatedInstance()
{
return s_consoleSCB;
}
} // namespace MFC
#include <Controls/moc_ConsoleSCBMFC.cpp>
| 26.602941 | 145 | 0.613322 | [
"vector",
"3d"
] |
333820cf51bab14c20af3966ba5fdb77aaab0bca | 9,363 | cpp | C++ | Source/AllProjects/Installer/CQCInst/CQCInst_CheckMSPanel.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Installer/CQCInst/CQCInst_CheckMSPanel.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/Installer/CQCInst/CQCInst_CheckMSPanel.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCInst_CheckMSPanel.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 11/02/2004
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the info panel that does the master server check
// if it's not being installed here. We have to contact it and we have to
// get the system id from it and store it as the system id for this system.
//
// If we are installing any background services, we need to get an admin
// login so that we can get some required info.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQCInst.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TInstCheckMSPanel,TInstInfoPanel)
// ---------------------------------------------------------------------------
// CLASS: TInstCheckMSPanel
// PREFIX: pan
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TInstCheckMSPanel: Constructors and Destructor
// ---------------------------------------------------------------------------
TInstCheckMSPanel::TInstCheckMSPanel(TCQCInstallInfo* const pinfoCur
, TMainFrameWnd* const pwndParent) :
TInstInfoPanel(L"Master Server Test", pinfoCur, pwndParent)
, m_pwndImage(nullptr)
, m_pwndStatus(nullptr)
, m_pwndTest(nullptr)
, m_strLastTest()
{
}
TInstCheckMSPanel::~TInstCheckMSPanel()
{
}
// ---------------------------------------------------------------------------
// TInstCheckMSPanel: Public, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TInstCheckMSPanel::bPanelIsVisible() const
{
//
// We only want to be seen if the master server is not being installed. If not, then
// we have to verify that we can contact the Master Server at the location indicated
// by the user.
//
return !infoCur().viiNewInfo().bMasterServer();
}
tCIDLib::TBoolean
TInstCheckMSPanel::bValidate(tCIDCtrls::TWndId& widFailed, TString& strErrText)
{
//
// If not installing the master server and they've not passed the connect
// test yet, then reject it.
//
if (!infoCur().viiNewInfo().bMasterServer() && !m_bPassed)
{
strErrText.LoadFromMsg(kCQCInstErrs::errcVal_NoMSTest, facCQCInst);
return kCIDLib::False;
}
return kCIDLib::True;
}
tCIDLib::TVoid TInstCheckMSPanel::ReactToChanges()
{
//
// If we had previously passed, but the address has changed, clear the status
// stuff. We also tell the facility object to clear any stored creds.
//
if (m_bPassed && (m_strLastTest != infoCur().viiNewInfo().strMSAddr()))
{
m_pwndImage->SetBitmap(m_bmpBad);
m_pwndStatus->ClearText();
m_bPassed = kCIDLib::False;
}
}
// ---------------------------------------------------------------------------
// TInstCheckMSPanel: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TInstCheckMSPanel::bCreated()
{
TParent::bCreated();
// Set our text for use by any popups
strWndText(facCQCInst.strMsg(kCQCInstMsgs::midPan_MSTest_Title));
// Load our child controls
LoadDlgItems(kCQCInst::ridPan_MSTest);
// Get some pointers to the ones we want to interact with
CastChildWnd(*this, kCQCInst::ridPan_MSTest_Image, m_pwndImage);
CastChildWnd(*this, kCQCInst::ridPan_MSTest_Status, m_pwndStatus);
CastChildWnd(*this, kCQCInst::ridPan_MSTest_Test, m_pwndTest);
// Register a click handler on the main frame for our test button
m_pwndTest->pnothRegisterHandler(this, &TInstCheckMSPanel::eClickHandler);
// Load our app images
m_bmpBad = facCQCInst.bmpLoadLargeAppImg(L"CQCAppGray");
m_bmpGood = facCQCInst.bmpLoadLargeAppImg(L"CQCApp");
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// TInstCheckMSPanel: Private, non-virtual methods
// ---------------------------------------------------------------------------
tCIDCtrls::EEvResponses TInstCheckMSPanel::eClickHandler(TButtClickInfo& wnotEvent)
{
if (wnotEvent.widSource() == kCQCInst::ridPan_MSTest_Test)
{
try
{
// Assume failure
m_bPassed = kCIDLib::False;
m_pwndImage->SetBitmap(m_bmpBad);
m_pwndStatus->strWndText(L"Contacting Master Server");
// Resolve the master server address and log it for later use
{
TIPAddress ipaLog
(
infoCur().viiNewInfo().strMSAddr(), tCIDSock::EAddrTypes::Unspec
);
facCQCInst.LogInstallMsg(L"Master server address resolves to: %(1)", ipaLog);
}
//
// The user has to log in as an admin on the target MS, to prove he has the right
// to install a new client, and so that we can get some info we need. We use a
// helper which will do the login if needed or just return the credentials if we
// already got them in a previous step.
//
TString strMsg;
facCQCInst.bLoadCIDMsg(kCQCInstMsgs::midTitle_AdminLogin, strMsg);
TCQCUserCtx cuctxTmp;
if (facCQCInst.wndMain().bLogin(*this, strMsg, cuctxTmp))
{
// Put up a wait pointer while we are doing this part
TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait);
//
// Get a security server proxy, and get the secondary server credentials,
// we have to provide our admin security token we just got. We have to store
// this away in the install info.
//
tCQCKit::TSecuritySrvProxy orbcSec = facCQCKit().orbcSecuritySrvProxy(5000);
TString strSrvUser;
TString strSrvPassword;
if (orbcSec->bQuerySrvCreds(strSrvUser, strSrvPassword, cuctxTmp.sectUser()))
{
//
// Store a success and the address we tested against, and update it to use the
// system id we got.
//
m_pwndImage->SetBitmap(m_bmpGood);
facCQCInst.bLoadCIDMsg(kCQCInstMsgs::midStatus_MSFound, strMsg);
m_pwndStatus->strWndText(strMsg);
m_strLastTest = infoCur().viiNewInfo().strMSAddr();
// Just to be sure, make sure the reported account exists
if (orbcSec->bLoginExists(strSrvUser, cuctxTmp.sectUser()))
{
//
// Store away the server credentials stuff on the install info. The install
// thread will get it from there.
//
infoCur().SetSrvCreds(strSrvUser, strSrvPassword);
m_bPassed = kCIDLib::True;
}
else
{
TErrBox msgbFail(facCQCInst.strMsg(kCQCInstErrs::errcVal_MSCheckFailed));
msgbFail.ShowIt(*this);
m_pwndStatus->strWndText(facCQCInst.strMsg(kCQCInstErrs::errcVal_SrvCreds));
}
}
else
{
facCQCInst.bLoadCIDMsg(kCQCInstErrs::errcFail_NoSrvCreds, strMsg);
m_pwndStatus->strWndText(strMsg);
m_bPassed = kCIDLib::False;
}
if (m_bPassed)
{
// Get an installation server proxy and ping it to insure connectivity
tCQCKit::TInstSrvProxy orbcInst = facCQCKit().orbcInstSrvProxy(10000);
orbcInst->Ping();
}
}
else
{
facCQCInst.bLoadCIDMsg(kCQCInstErrs::errcFail_AdminReq, strMsg);
m_pwndStatus->strWndText(strMsg);
m_bPassed = kCIDLib::False;
}
}
catch(TError& errToCatch)
{
m_bPassed = kCIDLib::False;
if (!errToCatch.bLogged())
{
errToCatch.AddStackLevel(CID_FILE, CID_LINE);
TModule::LogEventObj(errToCatch);
}
const TString strErr = facCQCInst.strMsg(kCQCInstErrs::errcVal_MSCheckFailed);
TErrBox msgbFail(strErr);
msgbFail.ShowIt(*this);
m_pwndStatus->strWndText(errToCatch.strErrText());
return tCIDCtrls::EEvResponses::Handled;
}
}
return tCIDCtrls::EEvResponses::Handled;
}
| 36.431907 | 100 | 0.524939 | [
"object"
] |
33390d03594f556465a0ea2fdd164e1dcc198876 | 2,263 | cpp | C++ | blockhash/blockhash.cpp | conr2d/forbidden-spells | f98927bcbda7d81499c08869bcf6c984f310447a | [
"MIT"
] | null | null | null | blockhash/blockhash.cpp | conr2d/forbidden-spells | f98927bcbda7d81499c08869bcf6c984f310447a | [
"MIT"
] | null | null | null | blockhash/blockhash.cpp | conr2d/forbidden-spells | f98927bcbda7d81499c08869bcf6c984f310447a | [
"MIT"
] | null | null | null | #include <eosio/eosio.hpp>
#include <eosio/crypto.hpp>
#include <eosio/system.hpp>
#include <eosio/producer_schedule.hpp>
#include <eosio/transaction.hpp>
using namespace eosio;
#ifdef __cplusplus
namespace eosio {
using capi_checksum256 = std::array<uint8_t,32> __attribute__ ((aligned(16)));
}
#endif
struct block_header {
block_timestamp timestamp;
name producer;
uint16_t confirmed = 0;
capi_checksum256 previous;
capi_checksum256 transaction_mroot;
capi_checksum256 action_mroot;
uint32_t schedule_version = 0;
std::optional<eosio::producer_schedule> new_producers;
std::vector<std::pair<uint16_t,std::vector<char>>> header_extensions;
EOSLIB_SERIALIZE(block_header, (timestamp)(producer)(confirmed)(previous)(transaction_mroot)(action_mroot)
(schedule_version)(new_producers)(header_extensions))
};
class [[eosio::contract]] blockhash : public contract {
public:
using contract::contract;
struct [[eosio::table("blockid")]] block_id {
checksum256 value;
uint64_t primary_key() const {
return static_cast<uint64_t>(value.data()[0] >> (sizeof(uint32_t) * 8 * 3));
}
};
using block_ids = eosio::multi_index<"blockid"_n, block_id>;
[[eosio::action]]
void onblock(ignore<block_header>) {
require_auth(get_self());
block_ids ids(get_self(), get_self().value);
auto begin = ids.begin();
auto end = ids.end();
// Keep the latest 256 block ids
if ((begin != end) && (--end != begin)) {
while (end->primary_key() > begin->primary_key() + 256) {
begin = ids.erase(begin);
}
}
ids.emplace(get_self(), [&](auto& id) {
id.value = eosio::sha256(get_datastream().pos(), action_data_size());
uint32_t block_num = tapos_block_num();
auto dst = reinterpret_cast<char*>(id.value.data()) + (sizeof(uint32_t) * 3);
auto src = reinterpret_cast<char*>(&block_num);
std::copy(src, src + sizeof(uint32_t), dst);
});
}
};
| 31.873239 | 109 | 0.590809 | [
"vector"
] |
333eedd4caeccd14f07d1d0dcd08340eb17e0b00 | 1,315 | cc | C++ | src/41_find-missing-positive.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | 2 | 2018-07-28T06:11:30.000Z | 2019-01-15T15:16:54.000Z | src/41_find-missing-positive.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | src/41_find-missing-positive.cc | q191201771/yoko_leetcode | a29b163169f409856e9c9808890bcb25ca976f78 | [
"MIT"
] | null | null | null | // Given an unsorted integer array, find the smallest missing positive integer.
//
// Example 1:
//
// Input: [1,2,0]
// Output: 3
// Example 2:
//
// Input: [3,4,-1,1]
// Output: 2
// Example 3:
//
// Input: [7,8,9,11,12]
// Output: 1
//
// Note:
//
// Your algorithm should run in O(n) time and uses constant extra space.
#ifdef YOKO_DEBUG
#include "util/helper.hpp"
#endif
// [3,4,-1,1]
// [1,2,0]
class Solution {
private:
void help(vector<int> &nums, int i) {
if (nums[i] <= 0 || nums[i] > nums.size() || nums[i]-1 == i || nums[nums[i]-1] == nums[i]) { return; }
int tmp = nums[nums[i]-1];
nums[nums[i]-1] = nums[i];
nums[i] = tmp;
//std::cout << " " << chef::stringify_stl(nums) << std::endl;
help(nums, i);
}
public:
int firstMissingPositive(vector<int>& nums) {
if (nums.empty()) { return 1; }
for (std::size_t i = 0; i < nums.size(); i++) {
//std::cout << chef::stringify_stl(nums) << std::endl;
help(nums, i);
}
for (std::size_t i = 0; i < nums.size(); i++) {
if (nums[i]-1 != i) {
return i+1;
}
}
return nums.size()+1;
}
};
#ifdef YOKO_DEBUG
int main() {
Solution s;
vector<int> nums({3, 4, -1, 1});
std::cout << s.firstMissingPositive(nums) << std::endl;
return 0;
}
#endif
| 20.873016 | 106 | 0.535361 | [
"vector"
] |
333ef2994488aa23cb3b02b0d5ab0df2cd3cb6f5 | 3,562 | cpp | C++ | utils/addr2name.cpp | egor-tensin/winapi-debug | 2dee4e95e629d315e8d68bf275c900ffbb7317c0 | [
"MIT"
] | null | null | null | utils/addr2name.cpp | egor-tensin/winapi-debug | 2dee4e95e629d315e8d68bf275c900ffbb7317c0 | [
"MIT"
] | null | null | null | utils/addr2name.cpp | egor-tensin/winapi-debug | 2dee4e95e629d315e8d68bf275c900ffbb7317c0 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 Egor Tensin <Egor.Tensin@gmail.com>
// This file is part of the "winapi-debug" project.
// For details, see https://github.com/egor-tensin/winapi-debug.
// Distributed under the MIT License.
#include "command_line.hpp"
#include "pdb_descr.hpp"
#include <winapi/debug.hpp>
#include <boost/program_options.hpp>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace {
class Addr2Name : public SettingsParser {
public:
explicit Addr2Name(int argc, char** argv) : SettingsParser{argc, argv} {
namespace po = boost::program_options;
visible.add_options()(
"pdb", po::value<std::vector<PDB>>(&pdbs)->value_name("ADDR,PATH"), "load a PDB file");
visible.add_options()(
"lines,l", po::bool_switch(&lines), "try to resolve source files & line numbers");
hidden.add_options()(
"address",
po::value<std::vector<winapi::Address>>(&addresses)->value_name("ADDR"),
"add an address to resolve");
positional.add("address", -1);
}
const char* get_short_description() const override {
return "[-h|--help] [--pdb ADDR,PATH]... [-l|--lines] [--] [ADDR]...";
}
std::vector<PDB> pdbs;
std::vector<winapi::Address> addresses;
bool lines = false;
};
std::string format_symbol(const winapi::Module& module, const winapi::Symbol& symbol) {
std::ostringstream oss;
oss << module.get_name() << '!' << symbol.get_name();
const auto displacement = symbol.get_displacement();
if (displacement)
oss << '+' << winapi::address::format(displacement);
return oss.str();
}
std::string format_line_info(const winapi::LineInfo& line_info) {
std::ostringstream oss;
oss << '[' << line_info.file_path << " @ " << line_info.line_number << ']';
return oss.str();
}
void dump_error(const std::exception& e) {
std::cerr << "error: " << e.what() << '\n';
}
void resolve_symbol(const winapi::PostMortem& analysis,
winapi::Address address,
bool lines = false) {
try {
const auto symbol = analysis.resolve_symbol(address);
const auto& module = analysis.module_with_offline_base(symbol.get_offline_base());
std::ostringstream msg;
msg << format_symbol(module, symbol);
if (lines) {
try {
const auto line_info = analysis.resolve_line(address);
msg << ' ' << format_line_info(line_info);
} catch (const std::exception& e) {
dump_error(e);
}
}
std::cout << msg.str() << '\n';
} catch (const std::exception& e) {
dump_error(e);
std::cout << winapi::address::format(address) << '\n';
}
}
} // namespace
int main(int argc, char* argv[]) {
try {
Addr2Name settings{argc, argv};
try {
settings.parse(argc, argv);
} catch (const boost::program_options::error& e) {
settings.usage_error(e);
return 1;
}
if (settings.exit_with_usage) {
settings.usage();
return 0;
}
winapi::PostMortem analysis;
for (const auto& pdb : settings.pdbs)
analysis.add_pdb(pdb.online_base, pdb.path);
for (const auto& address : settings.addresses)
resolve_symbol(analysis, address, settings.lines);
} catch (const std::exception& e) {
dump_error(e);
return 1;
}
return 0;
}
| 29.196721 | 99 | 0.589556 | [
"vector"
] |
33445e11cc2ef6c4a2131b040628c72278c8bea8 | 2,347 | cpp | C++ | fileutils.cpp | SvetaMorkva/Unexpected-Journey | e9a005a2d5b1bf6ef3bcba9218db61e886ebc37f | [
"MIT"
] | 1 | 2020-12-06T23:59:08.000Z | 2020-12-06T23:59:08.000Z | fileutils.cpp | SvetaMorkva/Unexpected-Journey | e9a005a2d5b1bf6ef3bcba9218db61e886ebc37f | [
"MIT"
] | null | null | null | fileutils.cpp | SvetaMorkva/Unexpected-Journey | e9a005a2d5b1bf6ef3bcba9218db61e886ebc37f | [
"MIT"
] | null | null | null | //
// Created by Sveta Morkva on 11/28/20.
//
#include "fileutils.h"
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
std::vector<std::string> fileutils::get_file_list(const std::string &path) {
std::vector<std::string> m_file_list;
if (fs::is_directory(path)) {
fs::path apk_path(path);
fs::directory_iterator end;
for (fs::directory_iterator i(apk_path); i != end; ++i) {
const fs::path cp = (*i);
if (cp.extension() == ".jpg" || cp.extension() == ".jpeg") {
m_file_list.push_back(cp.string());
}
}
}
return m_file_list;
}
void fileutils::preprocessData() {
const auto &trainFolder = "../images/train/";
if (fs::exists(trainFolder)) {
fs::path path_to_remove(trainFolder);
for (fs::directory_iterator end_dir_it, it(path_to_remove); it!=end_dir_it; ++it) {
fs::remove_all(it->path());
}
} else {
fs::create_directory(trainFolder);
}
if (!fs::exists("../metrics")) {
fs::create_directory("../metrics");
}
std::ofstream fileLabels;
fileLabels.open("../metrics/train_data.csv", std::ofstream::out | std::ofstream::trunc);
fileLabels << "Image_name, Correct label\n";
const auto &book1Data = get_file_list("../images/Book1");
const auto &book2Data = get_file_list("../images/Book2");
const auto &noneData = get_file_list("../images/None");
int num = 0;
for (size_t i = 0; i < book1Data.size(); i++) {
auto newfilename = trainFolder + std::to_string(num++) + ".jpg";
fs::copy_file(book1Data[i], newfilename);
fileLabels << newfilename << "," << 1 << "\n";
}
for (size_t i = 0; i < book2Data.size(); i++) {
auto newfilename = trainFolder + std::to_string(num++) + ".jpg";
fs::copy_file(book2Data[i], newfilename);
fileLabels << newfilename << "," << 2 << "\n";
}
for (size_t i = 0; i < noneData.size(); i++) {
auto newfilename = trainFolder + std::to_string(num++) + ".jpg";
fs::copy_file(noneData[i], newfilename);
fileLabels << newfilename << "," << 0 << "\n";
}
fileLabels.close();
}
std::string fileutils::getFilenameFromPath(const std::string &path) {
auto it = path.rfind('/');
return path.substr(it + 1);
}
| 33.528571 | 92 | 0.580741 | [
"vector"
] |
3345ba06a265cc48b9faed030426fce663fa000f | 14,163 | hpp | C++ | cpp/src/cylon/table.hpp | chathurawidanage/cylon | ac61b7a50880138fe67de21adee208016a94979a | [
"Apache-2.0"
] | null | null | null | cpp/src/cylon/table.hpp | chathurawidanage/cylon | ac61b7a50880138fe67de21adee208016a94979a | [
"Apache-2.0"
] | null | null | null | cpp/src/cylon/table.hpp | chathurawidanage/cylon | ac61b7a50880138fe67de21adee208016a94979a | [
"Apache-2.0"
] | null | null | null | /*
* 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 CYLON_SRC_IO_TABLE_H_
#define CYLON_SRC_IO_TABLE_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <cylon/indexing/index.hpp>
#include <cylon/io/csv_read_config.hpp>
#ifdef BUILD_CYLON_PARQUET
#include <cylon/io/parquet_config.hpp>
#endif
#include <cylon/column.hpp>
#include <cylon/ctx/cylon_context.hpp>
#include <cylon/io/csv_write_config.hpp>
#include <cylon/join/join.hpp>
#include <cylon/join/join_config.hpp>
#include <cylon/row.hpp>
#include <cylon/status.hpp>
#include <cylon/util/uuid.hpp>
namespace cylon {
/**
* Table provides the main API for using cylon for data processing.
*/
class Table {
public:
/**
* Table created from an arrow::Table
* @param ctx
* @param tab (shared_ptr is passed by value and the copy is moved as a class member)
*/
Table(const std::shared_ptr<CylonContext> &ctx, std::shared_ptr<arrow::Table> tab);
/**
* Table created from cylon::Column
* @param ctx
* @param cols (vector is passed by value and the copy is moved as a class member)
*/
Table(const std::shared_ptr<CylonContext> &ctx, std::vector<std::shared_ptr<Column>> cols);
virtual ~Table();
/**
* Create a table from an arrow table,
* @param table arrow::Table
* @return
*/
static Status FromArrowTable(const std::shared_ptr<CylonContext> &ctx,
const std::shared_ptr<arrow::Table> &table,
std::shared_ptr<Table> &tableOut);
/**
* Create a table from cylon columns
* @param ctx
* @param columns
* @param tableOut
* @return
*/
static Status FromColumns(const std::shared_ptr<CylonContext> &ctx,
const std::vector<std::shared_ptr<Column>> &columns,
std::shared_ptr<Table> &tableOut);
/**
* Create a arrow table from this data structure
* @param output arrow table
* @return the status of the operation
*/
Status ToArrowTable(std::shared_ptr<arrow::Table> &output);
/**
* Print the col range and row range
* @param col1 start col
* @param col2 end col
* @param row1 start row
* @param row2 end row
* @param out the stream
* @param delimiter delimiter between values
* @param use_custom_header custom header
* @param headers the names of custom header
* @return true if print is successful
*/
Status PrintToOStream(int col1, int col2, int row1, int row2, std::ostream &out,
char delimiter = ',', bool use_custom_header = false,
const std::vector<std::string> &headers = {});
/*END OF TRANSFORMATION FUNCTIONS*/
/**
* Get the number of columns in the table
* @return number of columns
*/
int32_t Columns();
/**
* Get the number of rows in this table
* @return number of rows in the table
*/
int64_t Rows();
/**
* Print the complete table
*/
void Print();
/**
* Print the table from row1 to row2 and col1 to col2
* @param row1 first row to start printing (including)
* @param row2 end row to stop printing (including)
* @param col1 first column to start printing (including)
* @param col2 end column to stop printing (including)
*/
void Print(int row1, int row2, int col1, int col2);
/**
* Get the underlying arrow table
* @return the arrow table
*/
std::shared_ptr<arrow::Table> get_table();
/**
* Clears the table
*/
void Clear();
/**
* Returns the cylon Context
* @return
*/
const std::shared_ptr<cylon::CylonContext> &GetContext() const;
/**
* Get column names of the table
* @return vector<string>
*/
std::vector<std::string> ColumnNames();
/**
* Set to true to free the memory of this table when it is not needed
*/
void retainMemory(bool retain) { retain_ = retain; }
/**
* Returns if this table retains data after any operation performed on it
* @return
*/
bool IsRetain() const;
/**
* Get a cylon::Column from the table
* @param index
* @return
*/
std::shared_ptr<Column> GetColumn(int32_t index) const;
/**
* Get the column vector of the table
* @return
*/
const std::vector<std::shared_ptr<cylon::Column>> &GetColumns() const;
Status SetArrowIndex(std::shared_ptr<cylon::BaseArrowIndex> &index, bool drop_index);
std::shared_ptr<BaseArrowIndex> GetArrowIndex();
Status ResetArrowIndex(bool drop = false);
Status AddColumn(int64_t position, const std::string& column_name, std::shared_ptr<arrow::Array> &input_column);
private:
/**
* Every table should have an unique id
*/
const std::shared_ptr<cylon::CylonContext> ctx;
std::shared_ptr<arrow::Table> table_;
bool retain_ = true;
std::vector<std::shared_ptr<cylon::Column>> columns_;
std::shared_ptr<cylon::BaseArrowIndex> base_arrow_index_ = nullptr;
};
/**
* Create a table by reading a csv file
* @param path file path
* @return a pointer to the table
*/
Status FromCSV(const std::shared_ptr<CylonContext> &ctx, const std::string &path,
std::shared_ptr<Table> &tableOut,
const cylon::io::config::CSVReadOptions &options = cylon::io::config::CSVReadOptions());
/**
* Read multiple CSV files into multiple tables. If threading is enabled, the tables will be read
* in parallel
* @param ctx
* @param paths
* @param tableOuts
* @param options
* @return
*/
Status FromCSV(const std::shared_ptr<CylonContext> &ctx, const std::vector<std::string> &paths,
const std::vector<std::shared_ptr<Table> *> &tableOuts,
const io::config::CSVReadOptions &options = cylon::io::config::CSVReadOptions());
/**
* Write the table as a CSV
* @param table shared pointer to the cylon table
* @param path file path
* @return the status of the operation
*/
Status WriteCSV(const std::shared_ptr<Table> &table, const std::string &path,
const cylon::io::config::CSVWriteOptions &options = cylon::io::config::CSVWriteOptions());
/**
* Merge the set of tables to create a single table
* @param tables
* @return new merged table
*/
Status Merge(const std::vector<std::shared_ptr<cylon::Table>> &tables, std::shared_ptr<Table> &tableOut);
/**
* Do the join with the right table
* @param left the left table
* @param right the right table
* @param joinConfig the join configurations
* @param output the final table
* @return success
*/
Status Join(std::shared_ptr<Table> &left, std::shared_ptr<Table> &right,
const join::config::JoinConfig &join_config, std::shared_ptr<Table> &output);
/**
* Similar to local join, but performs the join in a distributed fashion
* @param left
* @param right
* @param join_config
* @param output
* @return <cylon::Status>
*/
Status DistributedJoin(std::shared_ptr<Table> &left, std::shared_ptr<Table> &right,
const join::config::JoinConfig &join_config, std::shared_ptr<Table> &output);
/**
* Performs union with the passed table
* @param first
* @param second
* @param output
* @return <cylon::Status>
*/
Status Union(const std::shared_ptr<Table> &first, const std::shared_ptr<Table> &second,
std::shared_ptr<Table> &output);
/**
* Similar to local union, but performs the union in a distributed fashion
* @param first
* @param second
* @param output
* @return <cylon::Status>
*/
Status DistributedUnion(std::shared_ptr<Table> &first, std::shared_ptr<Table> &second,
std::shared_ptr<Table> &out);
/**
* Performs subtract/difference with the passed table
* @param first
* @param second
* @param output
* @return <cylon::Status>
*/
Status Subtract(const std::shared_ptr<Table> &first, const std::shared_ptr<Table> &second,
std::shared_ptr<Table> &out);
/**
* Similar to local subtract/difference, but performs in a distributed fashion
* @param first
* @param second
* @param output
* @return <cylon::Status>
*/
Status DistributedSubtract(std::shared_ptr<Table> &left, std::shared_ptr<Table> &right,
std::shared_ptr<Table> &out);
/**
* Performs intersection with the passed table
* @param first
* @param second
* @param output
* @return <cylon::Status>
*/
Status Intersect(const std::shared_ptr<Table> &first, const std::shared_ptr<Table> &second,
std::shared_ptr<Table> &output);
/**
* Similar to local intersection, but performs in a distributed fashion
* @param first
* @param second
* @param output
* @return <cylon::Status>
*/
Status DistributedIntersect(std::shared_ptr<Table> &left, std::shared_ptr<Table> &right,
std::shared_ptr<Table> &out);
/**
* Shuffles a table based on hashes
* @param table
* @param hash_col_idx vector of column indices that needs to be hashed
* @param output
* @return
*/
Status Shuffle(std::shared_ptr<cylon::Table> &table, const std::vector<int> &hash_col_idx,
std::shared_ptr<cylon::Table> &output);
/**
* Partition the table based on the hash
* @param hash_columns the columns use for has
* @param no_of_partitions number partitions
* @return new set of tables each with the new partition
*/
Status HashPartition(std::shared_ptr<cylon::Table> &table, const std::vector<int> &hash_columns,
int no_of_partitions,
std::unordered_map<int, std::shared_ptr<cylon::Table>> *output);
/**
* Sort the table according to the given column, this is a local sort (if the table has chunked
* columns, they will be merged in the output table)
* @param sort_column
* @return new table sorted according to the sort column
*/
Status Sort(std::shared_ptr<cylon::Table> &table, int sort_column, std::shared_ptr<Table> &output,
bool ascending = true);
/**
* Sort the table according to the given set of columns, this is a local sort (if the table has
* chunked columns, they will be merged in the output table)
* @param sort_column
* @return new table sorted according to the sort columns
*/
Status Sort(std::shared_ptr<cylon::Table> &table, const std::vector<int32_t> &sort_columns,
std::shared_ptr<cylon::Table> &out, bool ascending);
/**
* Sort the table according to the given set of columns and respective ordering direction, this is a
* local sort (if the table has chunked columns, they will be merged in the output table).
*
* Sort direction 'true' indicates ascending ordering and false indicate descending ordering.
* @param sort_column
* @return new table sorted according to the sort columns
*/
Status Sort(std::shared_ptr<cylon::Table> &table, const std::vector<int32_t> &sort_columns,
std::shared_ptr<cylon::Table> &out, const std::vector<bool> &sort_direction);
/**
* Sort the table according to the given column, this is a local sort (if the table has chunked
* columns, they will be merged in the output table)
* @param sort_column
* @return new table sorted according to the sort column
*/
struct SortOptions {
uint32_t num_bins;
uint64_t num_samples;
static SortOptions Defaults() { return {0, 0}; }
};
Status DistributedSort(std::shared_ptr<cylon::Table> &table,
int sort_column,
std::shared_ptr<Table> &output,
bool ascending = true,
SortOptions sort_options = SortOptions::Defaults());
Status DistributedSort(std::shared_ptr<cylon::Table> &table,
const std::vector<int> &sort_columns,
std::shared_ptr<Table> &output,
const std::vector<bool> &sort_direction,
SortOptions sort_options = SortOptions::Defaults());
/**
* Filters out rows based on the selector function
* @param table
* @param selector lambda function returning a bool
* @param output
* @return
*/
Status Select(std::shared_ptr<cylon::Table> &table, const std::function<bool(cylon::Row)> &selector,
std::shared_ptr<Table> &output);
/**
* Creates a View of an existing table by dropping one or more columns
* @param table
* @param project_columns
* @param output
* @return
*/
Status Project(std::shared_ptr<cylon::Table> &table, const std::vector<int32_t> &project_columns,
std::shared_ptr<Table> &output);
/**
* Creates a new table by dropping the duplicated elements column-wise
* @param table
* @param cols
* @param out
* @return Status
*/
Status Unique(std::shared_ptr<cylon::Table> &in, const std::vector<int> &cols,
std::shared_ptr<cylon::Table> &out, bool first = true);
Status DistributedUnique(std::shared_ptr<cylon::Table> &in, const std::vector<int> &cols,
std::shared_ptr<cylon::Table> &out);
#ifdef BUILD_CYLON_PARQUET
/**
* Create a table by reading a parquet file
* @param path file path
* @return a pointer to the table
*/
Status FromParquet(const std::shared_ptr<CylonContext> &ctx, const std::string &path,
std::shared_ptr<Table> &tableOut);
/**
* Read multiple parquet files into multiple tables. If threading is enabled, the tables will be
* read in parallel
* @param ctx
* @param paths
* @param tableOuts
* @param options
* @return
*/
Status FromParquet(const std::shared_ptr<CylonContext> &ctx, const std::vector<std::string> &paths,
const std::vector<std::shared_ptr<Table> *> &tableOuts,
const io::config::ParquetOptions &options = cylon::io::config::ParquetOptions());
/**
* Write the table as a parquet file
* @param path file path
* @return the status of the operation
*/
Status WriteParquet(const std::shared_ptr<cylon::CylonContext> &ctx,
std::shared_ptr<cylon::Table> &table,
const std::string &path,
const io::config::ParquetOptions &options = cylon::io::config::ParquetOptions());
#endif // BUILD_CYLON_PARQUET
} // namespace cylon
#endif // CYLON_SRC_IO_TABLE_H_
| 30.523707 | 114 | 0.687707 | [
"vector"
] |
33467cc4be4c6333b708520b8eaeecfeaa5a925e | 2,704 | cpp | C++ | ShaderGLLib/Frame.cpp | EPAC-Saxon/advance-obj-JuliePreperier | 5adc1a308c8ad6bed9555dc507f83437a5b5208c | [
"MIT"
] | null | null | null | ShaderGLLib/Frame.cpp | EPAC-Saxon/advance-obj-JuliePreperier | 5adc1a308c8ad6bed9555dc507f83437a5b5208c | [
"MIT"
] | null | null | null | ShaderGLLib/Frame.cpp | EPAC-Saxon/advance-obj-JuliePreperier | 5adc1a308c8ad6bed9555dc507f83437a5b5208c | [
"MIT"
] | null | null | null | #include "Frame.h"
#include <stdexcept>
#include <GL/glew.h>
#include <cassert>
namespace sgl {
Frame::Frame()
{
glGenFramebuffers(1, &frame_id_);
error_.Display(__FILE__, __LINE__ - 1);
}
Frame::~Frame()
{
glDeleteFramebuffers(1, &frame_id_);
}
void Frame::Bind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, frame_id_);
error_.Display(__FILE__, __LINE__ - 1);
}
void Frame::UnBind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
error_.Display(__FILE__, __LINE__ - 1);
}
void Frame::BindAttach(const Render& render) const
{
Bind();
render.Bind();
glFramebufferRenderbuffer(
GL_FRAMEBUFFER,
GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER,
render.GetId());
error_.Display(__FILE__, __LINE__ - 5);
}
void Frame::BindTexture(
const Texture& texture,
const FrameColorAttachment frame_color_attachment /*=
FrameColorAttachment::COLOR_ATTACHMENT0*/,
const int mipmap /*= 0*/,
const FrameTextureType frame_texture_type /*=
FrameTextureType::TEXTURE_2D*/) const
{
Bind();
glFramebufferTexture2D(
GL_FRAMEBUFFER,
static_cast<GLenum>(frame_color_attachment),
GetFrameTextureType(frame_texture_type),
texture.GetId(),
mipmap);
error_.Display(__FILE__, __LINE__ - 6);
}
FrameColorAttachment Frame::GetFrameColorAttachment(const int i)
{
switch (i)
{
case 0:
return FrameColorAttachment::COLOR_ATTACHMENT0;
case 1:
return FrameColorAttachment::COLOR_ATTACHMENT1;
case 2:
return FrameColorAttachment::COLOR_ATTACHMENT2;
case 3:
return FrameColorAttachment::COLOR_ATTACHMENT3;
case 4:
return FrameColorAttachment::COLOR_ATTACHMENT4;
case 5:
return FrameColorAttachment::COLOR_ATTACHMENT5;
case 6:
return FrameColorAttachment::COLOR_ATTACHMENT6;
case 7:
return FrameColorAttachment::COLOR_ATTACHMENT7;
default :
throw std::runtime_error("Only [0-7] level allowed.");
}
}
const int Frame::GetFrameTextureType(
const FrameTextureType frame_texture_type) const
{
int value = static_cast<int>(frame_texture_type);
if (value >= 0)
{
return GL_TEXTURE_CUBE_MAP_POSITIVE_X + value;
}
return GL_TEXTURE_2D;
}
FrameTextureType Frame::GetFrameTextureType(const int i)
{
return static_cast<FrameTextureType>(i);
}
void Frame::DrawBuffers(const std::uint32_t size /*= 1*/)
{
assert(size < 9);
std::vector<unsigned int> draw_buffer = {};
for (std::uint32_t i = 0; i < size; ++i)
{
draw_buffer.emplace_back(
static_cast<unsigned int>(Frame::GetFrameColorAttachment(i)));
}
glDrawBuffers(
static_cast<GLsizei>(draw_buffer.size()),
draw_buffer.data());
error_.Display(__FILE__, __LINE__ - 3);
}
} // End namespace sgl.
| 22.915254 | 66 | 0.714867 | [
"render",
"vector"
] |
334edf234f8fb5f3bed6d9c655ec57b3f9b77df9 | 19,647 | cc | C++ | test/common/http/conn_manager_impl_fuzz_test.cc | boazjohn/envoy | aab05453ff2e354093f70d0b1160e25e6cd79a66 | [
"Apache-2.0"
] | 1 | 2019-04-01T22:49:29.000Z | 2019-04-01T22:49:29.000Z | test/common/http/conn_manager_impl_fuzz_test.cc | boazjohn/envoy | aab05453ff2e354093f70d0b1160e25e6cd79a66 | [
"Apache-2.0"
] | 2 | 2021-03-20T05:31:48.000Z | 2021-03-20T05:32:33.000Z | test/common/http/conn_manager_impl_fuzz_test.cc | boazjohn/envoy | aab05453ff2e354093f70d0b1160e25e6cd79a66 | [
"Apache-2.0"
] | null | null | null | // This fuzzer explores the behavior of HCM with replay of trace actions that describe the behavior
// of a mocked codec and decoder/encoder filters. It is only partially complete (~60% test coverage
// with supplied corpus), since HCM has a lot of behavior to model, requiring investment in building
// out modeling actions and a corpus, which is time consuming and may not have significant security
// of functional correctness payoff beyond existing tests. Places where we could increase fuzz
// coverage include:
// * Watermarks
// * WebSocket upgrades
// * Tracing and stats.
// * Encode filter actions (e.g. modeling stop/continue, only done for decoder today).
// * SSL
// * Idle/drain timeouts.
// * HTTP 1.0 special cases
// * Fuzz config settings
#include "common/common/empty_string.h"
#include "common/http/conn_manager_impl.h"
#include "common/http/context_impl.h"
#include "common/http/date_provider_impl.h"
#include "common/http/exception.h"
#include "common/network/address_impl.h"
#include "common/network/utility.h"
#include "test/common/http/conn_manager_impl_fuzz.pb.h"
#include "test/fuzz/fuzz_runner.h"
#include "test/fuzz/utility.h"
#include "test/mocks/access_log/mocks.h"
#include "test/mocks/common.h"
#include "test/mocks/http/mocks.h"
#include "test/mocks/local_info/mocks.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/runtime/mocks.h"
#include "test/mocks/ssl/mocks.h"
#include "test/mocks/tracing/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/simulated_time_system.h"
#include "gmock/gmock.h"
using testing::InvokeWithoutArgs;
using testing::Return;
namespace Envoy {
namespace Http {
class FuzzConfig : public ConnectionManagerConfig {
public:
struct RouteConfigProvider : public Router::RouteConfigProvider {
RouteConfigProvider(TimeSource& time_source) : time_source_(time_source) {}
// Router::RouteConfigProvider
Router::ConfigConstSharedPtr config() override { return route_config_; }
absl::optional<ConfigInfo> configInfo() const override { return {}; }
SystemTime lastUpdated() const override { return time_source_.systemTime(); }
TimeSource& time_source_;
std::shared_ptr<Router::MockConfig> route_config_{new NiceMock<Router::MockConfig>()};
};
FuzzConfig()
: route_config_provider_(time_system_),
stats_{{ALL_HTTP_CONN_MAN_STATS(POOL_COUNTER(fake_stats_), POOL_GAUGE(fake_stats_),
POOL_HISTOGRAM(fake_stats_))},
"",
fake_stats_},
tracing_stats_{CONN_MAN_TRACING_STATS(POOL_COUNTER(fake_stats_))},
listener_stats_{CONN_MAN_LISTENER_STATS(POOL_COUNTER(fake_stats_))} {
access_logs_.emplace_back(std::make_shared<NiceMock<AccessLog::MockInstance>>());
}
void newStream() {
codec_ = new NiceMock<MockServerConnection>();
decoder_filter_ = new NiceMock<MockStreamDecoderFilter>();
encoder_filter_ = new NiceMock<MockStreamEncoderFilter>();
EXPECT_CALL(filter_factory_, createFilterChain(_))
.WillOnce(Invoke([this](FilterChainFactoryCallbacks& callbacks) -> void {
callbacks.addStreamDecoderFilter(StreamDecoderFilterSharedPtr{decoder_filter_});
callbacks.addStreamEncoderFilter(StreamEncoderFilterSharedPtr{encoder_filter_});
}));
EXPECT_CALL(*decoder_filter_, setDecoderFilterCallbacks(_));
EXPECT_CALL(*encoder_filter_, setEncoderFilterCallbacks(_));
}
// Http::ConnectionManagerConfig
const std::list<AccessLog::InstanceSharedPtr>& accessLogs() override { return access_logs_; }
ServerConnectionPtr createCodec(Network::Connection&, const Buffer::Instance&,
ServerConnectionCallbacks&) override {
return ServerConnectionPtr{codec_};
}
DateProvider& dateProvider() override { return date_provider_; }
std::chrono::milliseconds drainTimeout() override { return std::chrono::milliseconds(100); }
FilterChainFactory& filterFactory() override { return filter_factory_; }
bool generateRequestId() override { return true; }
uint32_t maxRequestHeadersKb() const override { return max_request_headers_kb_; }
absl::optional<std::chrono::milliseconds> idleTimeout() const override { return idle_timeout_; }
std::chrono::milliseconds streamIdleTimeout() const override { return stream_idle_timeout_; }
std::chrono::milliseconds requestTimeout() const override { return request_timeout_; }
std::chrono::milliseconds delayedCloseTimeout() const override { return delayed_close_timeout_; }
Router::RouteConfigProvider& routeConfigProvider() override { return route_config_provider_; }
const std::string& serverName() override { return server_name_; }
ConnectionManagerStats& stats() override { return stats_; }
ConnectionManagerTracingStats& tracingStats() override { return tracing_stats_; }
bool useRemoteAddress() override { return use_remote_address_; }
const Http::InternalAddressConfig& internalAddressConfig() const override {
return internal_address_config_;
}
uint32_t xffNumTrustedHops() const override { return 0; }
bool skipXffAppend() const override { return false; }
const std::string& via() const override { return EMPTY_STRING; }
Http::ForwardClientCertType forwardClientCert() override { return forward_client_cert_; }
const std::vector<Http::ClientCertDetailsType>& setCurrentClientCertDetails() const override {
return set_current_client_cert_details_;
}
const Network::Address::Instance& localAddress() override { return local_address_; }
const absl::optional<std::string>& userAgent() override { return user_agent_; }
const TracingConnectionManagerConfig* tracingConfig() override { return tracing_config_.get(); }
ConnectionManagerListenerStats& listenerStats() override { return listener_stats_; }
bool proxy100Continue() const override { return proxy_100_continue_; }
const Http::Http1Settings& http1Settings() const override { return http1_settings_; }
const envoy::config::filter::network::http_connection_manager::v2::HttpConnectionManager config_;
std::list<AccessLog::InstanceSharedPtr> access_logs_;
MockServerConnection* codec_{};
MockStreamDecoderFilter* decoder_filter_{};
MockStreamEncoderFilter* encoder_filter_{};
NiceMock<MockFilterChainFactory> filter_factory_;
Event::SimulatedTimeSystem time_system_;
SlowDateProviderImpl date_provider_{time_system_};
RouteConfigProvider route_config_provider_;
std::string server_name_;
Stats::IsolatedStoreImpl fake_stats_;
ConnectionManagerStats stats_;
ConnectionManagerTracingStats tracing_stats_;
ConnectionManagerListenerStats listener_stats_;
uint32_t max_request_headers_kb_{Http::DEFAULT_MAX_REQUEST_HEADERS_KB};
absl::optional<std::chrono::milliseconds> idle_timeout_;
std::chrono::milliseconds stream_idle_timeout_{};
std::chrono::milliseconds request_timeout_{};
std::chrono::milliseconds delayed_close_timeout_{};
bool use_remote_address_{true};
Http::ForwardClientCertType forward_client_cert_{Http::ForwardClientCertType::Sanitize};
std::vector<Http::ClientCertDetailsType> set_current_client_cert_details_;
Network::Address::Ipv4Instance local_address_{"127.0.0.1"};
absl::optional<std::string> user_agent_;
TracingConnectionManagerConfigPtr tracing_config_;
bool proxy_100_continue_ = true;
Http::Http1Settings http1_settings_;
Http::DefaultInternalAddressConfig internal_address_config_;
};
// Internal representation of stream state. Encapsulates the stream state, mocks
// and encoders for both the request/response.
class FuzzStream {
public:
// We track stream state here to prevent illegal operations, e.g. applying an
// encodeData() to the codec after encodeTrailers(). This is necessary to
// maintain the preconditions for operations on the codec at the API level. Of
// course, it's the codecs must be robust to wire-level violations. We
// explore these violations via MutateAction and SwapAction at the connection
// buffer level.
enum class StreamState { PendingHeaders, PendingDataOrTrailers, Closed };
FuzzStream(ConnectionManagerImpl& conn_manager, FuzzConfig& config,
const HeaderMap& request_headers, bool end_stream)
: conn_manager_(conn_manager), config_(config) {
config_.newStream();
EXPECT_CALL(*config_.codec_, dispatch(_))
.WillOnce(InvokeWithoutArgs([this, &request_headers, end_stream] {
decoder_ = &conn_manager_.newStream(encoder_);
auto headers = std::make_unique<TestHeaderMapImpl>(request_headers);
if (headers->Method() == nullptr) {
headers->setReferenceKey(Headers::get().Method, "GET");
}
decoder_->decodeHeaders(std::move(headers), end_stream);
}));
fakeOnData();
decoder_filter_ = config.decoder_filter_;
encoder_filter_ = config.encoder_filter_;
request_state_ = end_stream ? StreamState::Closed : StreamState::PendingDataOrTrailers;
response_state_ = StreamState::PendingHeaders;
}
void fakeOnData() {
Buffer::OwnedImpl fake_input;
conn_manager_.onData(fake_input, false);
}
Http::FilterHeadersStatus fromHeaderStatus(test::common::http::HeaderStatus status) {
switch (status) {
case test::common::http::HeaderStatus::HEADER_CONTINUE:
return Http::FilterHeadersStatus::Continue;
case test::common::http::HeaderStatus::HEADER_STOP_ITERATION:
return Http::FilterHeadersStatus::StopIteration;
default:
return Http::FilterHeadersStatus::Continue;
}
}
Http::FilterDataStatus fromDataStatus(test::common::http::DataStatus status) {
switch (status) {
case test::common::http::DataStatus::DATA_CONTINUE:
return Http::FilterDataStatus::Continue;
case test::common::http::DataStatus::DATA_STOP_ITERATION_AND_BUFFER:
return Http::FilterDataStatus::StopIterationAndBuffer;
case test::common::http::DataStatus::DATA_STOP_ITERATION_AND_WATERMARK:
return Http::FilterDataStatus::StopIterationAndWatermark;
case test::common::http::DataStatus::DATA_STOP_ITERATION_NO_BUFFER:
return Http::FilterDataStatus::StopIterationNoBuffer;
default:
return Http::FilterDataStatus::Continue;
}
}
Http::FilterTrailersStatus fromTrailerStatus(test::common::http::TrailerStatus status) {
switch (status) {
case test::common::http::TrailerStatus::TRAILER_CONTINUE:
return Http::FilterTrailersStatus::Continue;
case test::common::http::TrailerStatus::TRAILER_STOP_ITERATION:
return Http::FilterTrailersStatus::StopIteration;
default:
return Http::FilterTrailersStatus::Continue;
}
}
void decoderFilterCallbackAction(
const test::common::http::DecoderFilterCallbackAction& decoder_filter_callback_action) {
switch (decoder_filter_callback_action.decoder_filter_callback_action_selector_case()) {
case test::common::http::DecoderFilterCallbackAction::kAddDecodedData: {
if (request_state_ == StreamState::PendingDataOrTrailers) {
Buffer::OwnedImpl buf(std::string(
decoder_filter_callback_action.add_decoded_data().size() % (1024 * 1024), 'a'));
decoder_filter_->callbacks_->addDecodedData(
buf, decoder_filter_callback_action.add_decoded_data().streaming());
}
break;
}
default:
// Maybe nothing is set?
break;
}
}
void requestAction(StreamState& state, const test::common::http::RequestAction& request_action) {
switch (request_action.request_action_selector_case()) {
case test::common::http::RequestAction::kData: {
if (state == StreamState::PendingDataOrTrailers) {
const auto& data_action = request_action.data();
ON_CALL(*decoder_filter_, decodeData(_, _))
.WillByDefault(InvokeWithoutArgs([this, &data_action]() -> Http::FilterDataStatus {
if (data_action.has_decoder_filter_callback_action()) {
decoderFilterCallbackAction(data_action.decoder_filter_callback_action());
}
return fromDataStatus(data_action.status());
}));
EXPECT_CALL(*config_.codec_, dispatch(_)).WillOnce(InvokeWithoutArgs([this, &data_action] {
Buffer::OwnedImpl buf(std::string(data_action.size() % (1024 * 1024), 'a'));
decoder_->decodeData(buf, data_action.end_stream());
}));
fakeOnData();
state = data_action.end_stream() ? StreamState::Closed : StreamState::PendingDataOrTrailers;
}
break;
}
case test::common::http::RequestAction::kTrailers: {
if (state == StreamState::PendingDataOrTrailers) {
const auto& trailers_action = request_action.trailers();
ON_CALL(*decoder_filter_, decodeTrailers(_))
.WillByDefault(
InvokeWithoutArgs([this, &trailers_action]() -> Http::FilterTrailersStatus {
if (trailers_action.has_decoder_filter_callback_action()) {
decoderFilterCallbackAction(trailers_action.decoder_filter_callback_action());
}
return fromTrailerStatus(trailers_action.status());
}));
EXPECT_CALL(*config_.codec_, dispatch(_))
.WillOnce(InvokeWithoutArgs([this, &trailers_action] {
decoder_->decodeTrailers(std::make_unique<TestHeaderMapImpl>(
Fuzz::fromHeaders(trailers_action.headers())));
}));
fakeOnData();
state = StreamState::Closed;
}
break;
}
case test::common::http::RequestAction::kContinueDecoding: {
decoder_filter_->callbacks_->continueDecoding();
break;
}
case test::common::http::RequestAction::kThrowDecoderException: {
if (state == StreamState::PendingDataOrTrailers) {
EXPECT_CALL(*config_.codec_, dispatch(_)).WillOnce(InvokeWithoutArgs([] {
throw CodecProtocolException("blah");
}));
fakeOnData();
state = StreamState::Closed;
}
break;
}
default:
// Maybe nothing is set or not a request action?
break;
}
}
void responseAction(StreamState& state,
const test::common::http::ResponseAction& response_action) {
const bool end_stream = response_action.end_stream();
switch (response_action.response_action_selector_case()) {
case test::common::http::ResponseAction::kContinueHeaders: {
if (state == StreamState::PendingHeaders) {
auto headers = std::make_unique<TestHeaderMapImpl>(
Fuzz::fromHeaders(response_action.continue_headers()));
headers->setReferenceKey(Headers::get().Status, "100");
decoder_filter_->callbacks_->encode100ContinueHeaders(std::move(headers));
}
break;
}
case test::common::http::ResponseAction::kHeaders: {
if (state == StreamState::PendingHeaders) {
auto headers =
std::make_unique<TestHeaderMapImpl>(Fuzz::fromHeaders(response_action.headers()));
// The client codec will ensure we always have a valid :status.
// Similarly, local replies should always contain this.
try {
Utility::getResponseStatus(*headers);
} catch (const CodecClientException&) {
headers->setReferenceKey(Headers::get().Status, "200");
}
decoder_filter_->callbacks_->encodeHeaders(std::move(headers), end_stream);
state = end_stream ? StreamState::Closed : StreamState::PendingDataOrTrailers;
}
break;
}
case test::common::http::ResponseAction::kData: {
if (state == StreamState::PendingDataOrTrailers) {
Buffer::OwnedImpl buf(std::string(response_action.data() % (1024 * 1024), 'a'));
decoder_filter_->callbacks_->encodeData(buf, end_stream);
state = end_stream ? StreamState::Closed : StreamState::PendingDataOrTrailers;
}
break;
}
case test::common::http::ResponseAction::kTrailers: {
if (state == StreamState::PendingDataOrTrailers) {
decoder_filter_->callbacks_->encodeTrailers(
std::make_unique<TestHeaderMapImpl>(Fuzz::fromHeaders(response_action.trailers())));
state = StreamState::Closed;
}
break;
}
default:
// Maybe nothing is set?
break;
}
}
void streamAction(const test::common::http::StreamAction& stream_action) {
switch (stream_action.stream_action_selector_case()) {
case test::common::http::StreamAction::kRequest: {
requestAction(request_state_, stream_action.request());
break;
}
case test::common::http::StreamAction::kResponse: {
responseAction(response_state_, stream_action.response());
break;
}
default:
// Maybe nothing is set?
break;
}
}
ConnectionManagerImpl& conn_manager_;
FuzzConfig& config_;
StreamDecoder* decoder_{};
NiceMock<MockStreamEncoder> encoder_;
MockStreamDecoderFilter* decoder_filter_{};
MockStreamEncoderFilter* encoder_filter_{};
StreamState request_state_;
StreamState response_state_;
};
typedef std::unique_ptr<FuzzStream> FuzzStreamPtr;
DEFINE_PROTO_FUZZER(const test::common::http::ConnManagerImplTestCase& input) {
FuzzConfig config;
NiceMock<Network::MockDrainDecision> drain_close;
NiceMock<Runtime::MockRandomGenerator> random;
Stats::FakeSymbolTableImpl symbol_table;
Http::ContextImpl http_context;
NiceMock<Runtime::MockLoader> runtime;
NiceMock<LocalInfo::MockLocalInfo> local_info;
NiceMock<Upstream::MockClusterManager> cluster_manager;
NiceMock<Network::MockReadFilterCallbacks> filter_callbacks;
std::unique_ptr<Ssl::MockConnectionInfo> ssl_connection;
bool connection_alive = true;
ON_CALL(filter_callbacks.connection_, ssl()).WillByDefault(Return(ssl_connection.get()));
ON_CALL(Const(filter_callbacks.connection_), ssl()).WillByDefault(Return(ssl_connection.get()));
ON_CALL(filter_callbacks.connection_, close(_))
.WillByDefault(InvokeWithoutArgs([&connection_alive] { connection_alive = false; }));
filter_callbacks.connection_.local_address_ =
std::make_shared<Network::Address::Ipv4Instance>("127.0.0.1");
filter_callbacks.connection_.remote_address_ =
std::make_shared<Network::Address::Ipv4Instance>("0.0.0.0");
ConnectionManagerImpl conn_manager(config, drain_close, random, http_context, runtime, local_info,
cluster_manager, nullptr, config.time_system_);
conn_manager.initializeReadFilterCallbacks(filter_callbacks);
std::vector<FuzzStreamPtr> streams;
for (const auto& action : input.actions()) {
ENVOY_LOG_MISC(trace, "action {} with {} streams", action.DebugString(), streams.size());
if (!connection_alive) {
ENVOY_LOG_MISC(trace, "skipping due to dead connection");
break;
}
switch (action.action_selector_case()) {
case test::common::http::Action::kNewStream: {
streams.emplace_back(new FuzzStream(conn_manager, config,
Fuzz::fromHeaders(action.new_stream().request_headers()),
action.new_stream().end_stream()));
break;
}
case test::common::http::Action::kStreamAction: {
const auto& stream_action = action.stream_action();
if (streams.empty()) {
break;
}
(*std::next(streams.begin(), stream_action.stream_id() % streams.size()))
->streamAction(stream_action);
break;
}
default:
// Maybe nothing is set?
break;
}
}
filter_callbacks.connection_.dispatcher_.clearDeferredDeleteList();
}
} // namespace Http
} // namespace Envoy
| 44.150562 | 100 | 0.717005 | [
"vector",
"model"
] |
334fb29accd0b8a44d25f975cd298a1e88fd351c | 24,859 | cpp | C++ | GameName/Game/Source/Map.cpp | AlCh440/Project2_CITM | 99de28553f5e0a11d8551a13d23c0ea44de58ef4 | [
"MIT"
] | 1 | 2022-03-13T11:50:14.000Z | 2022-03-13T11:50:14.000Z | GameName/Game/Source/Map.cpp | AlCh440/Project2_CITM | 99de28553f5e0a11d8551a13d23c0ea44de58ef4 | [
"MIT"
] | null | null | null | GameName/Game/Source/Map.cpp | AlCh440/Project2_CITM | 99de28553f5e0a11d8551a13d23c0ea44de58ef4 | [
"MIT"
] | null | null | null |
#include "App.h"
#include "Render.h"
#include "Textures.h"
#include "Map.h"
#include "Physics.h"
#include "LevelManagement.h"
#include "Entities.h"
#include "Entity.h"
#include "Player.h"
#include<iostream>
#include "GreenPath.h"
#include "Defs.h"
#include "Log.h"
#include <math.h>
#include "Chest.h"
#include "Consumable.h"
#include "HPPotion.h"
#include "ManaPotion.h"
#include "Key.h"
using namespace std;
Map::Map(bool isActive) : Module(isActive), mapLoaded(false)
{
name.Create("map");
toSave = false;
saveConfigs = true;
}
// Destructor
Map::~Map()
{}
int Properties::GetProperty(const char* value, int defaultValue) const
{
p2ListItem<Property*>* item = list.start;
while (item)
{
if (item->data->name == value)
return item->data->value;
item = item->next;
}
return defaultValue;
}
bool Properties::SetProperty(const char* name, int set_value)
{
p2ListItem<Property*>* item = list.start;
while (item)
{
if (item->data->name == name)
{
item->data->value = set_value;
return true;
}
item = item->next;
}
return false;
}
void Properties::CreateProperty(const char* name, int createValue)
{
Property aux;
aux.name = name;
aux.value = createValue;
list.add(&aux);
}
int Properties::GetProperty_(const char* name)
{
for (p2ListItem<Properties::Property*>* propList = list.getFirst(); propList != nullptr; propList = propList->next)
{
if (propList->data->name == name)
{
return propList->data->value;
}
}
return 0;
}
// Called before render is available
bool Map::Awake(pugi::xml_node& config)
{
LOG("Loading Map Parser");
bool ret = true;
//folder.Create(config.child("folder").child_value());
folder.Create("Assets/maps/");
tx_tileInfo = app->tex->Load("Assets/Sprites/UI/screen_logo.jpg");
return ret;
}
// Draw the map (all requried layers)
void Map::Draw()
{
if (mapLoaded == false) return;
p2ListItem<MapLayer*>* mapLayerItem;
mapLayerItem = mapData.layers.start;
while (mapLayerItem != NULL) {
if (mapLayerItem->data->properties.GetProperty("Draw") == 1) {
for (int x = 0; x < mapLayerItem->data->width; x++)
{
for (int y = 0; y < mapLayerItem->data->height; y++)
{
int gid = mapLayerItem->data->Get(x, y);
if (gid > 0) {
TileSet* tileset = GetTilesetFromTileId(gid);
SDL_Rect r = tileset->GetTileRect(gid);
iPoint pos = MapToWorld(x, y);
app->render->DrawTexture(tileset->texture, pos.x, pos.y, &r);
}
}
}
}
mapLayerItem = mapLayerItem->next;
}
if (DEBUG)
app->physics->DrawColliders();
}
//A method that translates x,y coordinates from map positions to world positions
iPoint Map::MapToWorld(int x, int y) const
{
iPoint ret;
//Isometric map to world coordinates
if (mapData.type == MAPTYPE_ORTHOGONAL)
{
ret.x = x * mapData.tileWidth;
ret.y = y * mapData.tileHeight;
}
else if (mapData.type == MAPTYPE_ISOMETRIC)
{
ret.x = (x - y) * (mapData.tileWidth / 2);
ret.y = (x + y) * (mapData.tileHeight / 2);
}
else
{
LOG("Unknown map type");
ret.x = x; ret.y = y;
}
return ret;
}
//Orthographic world to map coordinates
iPoint Map::WorldToMap(int x, int y) const
{
iPoint ret(0, 0);
//The case for isometric maps to WorldToMap
if (mapData.type == MAPTYPE_ORTHOGONAL)
{
ret.x = x / mapData.tileWidth;
ret.y = y / mapData.tileHeight;
}
else if (mapData.type == MAPTYPE_ISOMETRIC)
{
float half_width = mapData.tileWidth * 0.5f;
float half_height = mapData.tileHeight * 0.5f;
ret.x = int((x / half_width + y / half_height) / 2);
ret.y = int((y / half_height - (x / half_width)) / 2);
}
else
{
LOG("Unknown map type");
ret.x = x; ret.y = y;
}
return ret;
}
bool Map::CreateWalkabilityMap(int& width, int& height, uchar** buffer, int layerValue) const
{
bool ret = false;
p2ListItem<MapLayer*>* item;
item = mapData.layers.start;
for (item = mapData.layers.start; item != NULL; item = item->next)
{
MapLayer* layer = item->data;
if (layer->properties.GetProperty("Navigation", 0) != layerValue)
continue;
uchar* map = new uchar[layer->width * layer->height];
memset(map, 1, layer->width * layer->height);
for (int y = 0; y < mapData.height; ++y)
{
for (int x = 0; x < mapData.width; ++x)
{
int i = (y * layer->width) + x;
int tileId = layer->Get(x, y);
TileSet* tileset = (tileId > 0) ? GetTilesetFromTileId(tileId) : NULL;
if (tileset != NULL)
{
map[i] = (tileId - tileset->firstgid) > 0 ? 0 : 1;
}
}
}
*buffer = map;
width = mapData.width;
height = mapData.height;
ret = true;
break;
}
return ret;
}
Object* Map::GetObjectById(int _id)
{
p2ListItem<ObjectLayer*>* objectLayer;
objectLayer = mapData.objectLayers.start;
while (objectLayer != NULL)
{
p2ListItem<Object*>* object;
object = objectLayer->data->objects.start;
while (object != NULL)
{
if (object->data->id == _id)
{
return object->data;
}
object = object->next;
}
objectLayer = objectLayer->next;
}
return nullptr;
}
//Pick the right Tileset based on a tile id
TileSet* Map::GetTilesetFromTileId(int id) const
{
p2ListItem<TileSet*>* item = mapData.tilesets.start;
TileSet* set = item->data;
while (item)
{
if (id < item->data->firstgid)
{
set = item->prev->data;
break;
}
set = item->data;
item = item->next;
}
return set;
}
// Get relative Tile rectangle
SDL_Rect TileSet::GetTileRect(int id) const
{
SDL_Rect rect = { 0 };
//Get relative Tile rectangle
int relativeId = id - firstgid;
rect.w = tileWidth;
rect.h = tileHeight;
rect.x = margin + ((rect.w + spacing) * (relativeId % columns));
rect.y = margin + ((rect.h + spacing) * (relativeId / columns));
return rect;
}
// Called before quitting
bool Map::CleanUp()
{
LOG("Unloading map");
// clean up any memory allocated from tilesets/map
// Remove all tilesets
p2ListItem<TileSet*>* item;
item = mapData.tilesets.start;
while (item != NULL)
{
RELEASE(item->data);
item = item->next;
}
mapData.tilesets.clear();
// clean up all layer data
// Remove all layers
p2ListItem<MapLayer*>* item2;
item2 = mapData.layers.start;
while (item2 != NULL)
{
RELEASE(item2->data);
item2 = item2->next;
}
mapData.layers.clear();
// Remove all objects
p2ListItem<ObjectLayer*>* item3;
item3 = mapData.objectLayers.start;
while (item3 != NULL)
{
RELEASE(item3->data);
item3 = item3->next;
}
mapData.objectLayers.clear();
p2ListItem <PhysBody*>* item5 = nullptr;
for (p2ListItem <PhysBody*>* item4 = Colliders.getFirst(); item4 != nullptr; item4 = item4->next)
{
item4->data->pendingToDelete = true;
if (item5 != nullptr) Colliders.del(item5);
item5 = item4;
}
return true;
}
// Load new map
bool Map::Load(const char* filename)
{
bool ret = true;
SString tmp("%s%s", folder.GetString(), filename);
pugi::xml_document mapFile;
pugi::xml_parse_result result = mapFile.load_file(tmp.GetString());
if (result == NULL)
{
LOG("Could not load map xml file %s. pugi error: %s", filename, result.description());
ret = false;
}
// Load general info
if (ret == true)
{
// Create and call a private function to load and fill all your map data
ret = LoadMap(mapFile);
}
// Create and call a private function to load a tileset
// remember to support more any number of tilesets!
if (ret == true)
{
ret = LoadTileSets(mapFile.child("map"));
if (ret)
LOG("TileSets Loaded...");
else
LOG("TileSets Not Loaded...");
}
// Iterate all layers and load each of them
// Load layer info
if (ret == true)
{
ret = LoadAllLayers(mapFile.child("map"));
if (ret)
LOG("Layers Loaded...");
else
LOG("Layers Not Loaded...");
}
if (ret == true)
{
ret = LoadAllObjectLayers(mapFile.child("map"));
if (ret)
LOG("Objects Loaded...");
else
LOG("Objects Not Loaded...");
}
if (ret == true)
{
//LOG all the data loaded iterate all tilesets and LOG everything
//LOG the info for each loaded layer
}
//once the maps and layers are loaded, we set the physics properties
if (ret == true)
{
//here we will set ground and death colliders and spawn entities
SetMapColliders();
}
mapLoaded = ret;
return ret;
}
//Load map general properties
bool Map::LoadMap(pugi::xml_node mapFile)
{
bool ret = true;
pugi::xml_node map = mapFile.child("map");
if (map == NULL)
{
LOG("Error parsing map xml file: Cannot find 'map' tag.");
ret = false;
}
else
{
// Load map general properties
mapData.height = map.attribute("height").as_int();
mapData.width = map.attribute("width").as_int();
mapData.tileHeight = map.attribute("tileheight").as_int();
mapData.tileWidth = map.attribute("tilewidth").as_int();
// Add formula to go from isometric map to world coordinates
mapData.type = MAPTYPE_UNKNOWN;
if (strcmp(map.attribute("orientation").as_string(), "isometric") == 0)
{
mapData.type = MAPTYPE_ISOMETRIC;
}
if (strcmp(map.attribute("orientation").as_string(), "orthogonal") == 0)
{
mapData.type = MAPTYPE_ORTHOGONAL;
}
}
return ret;
}
// Implement the LoadTileSet function to load the tileset properties
bool Map::LoadTileSets(pugi::xml_node mapFile) {
bool ret = true;
pugi::xml_node tileset;
for (tileset = mapFile.child("tileset"); tileset && ret; tileset = tileset.next_sibling("tileset"))
{
TileSet* set = new TileSet();
if (ret == true) ret = LoadTilesetDetails(tileset, set);
if (ret == true) ret = LoadTilesetImage(tileset, set);
mapData.tilesets.add(set);
}
return ret;
}
// Load Tileset attributes
bool Map::LoadTilesetDetails(pugi::xml_node& tileset_node, TileSet* set)
{
bool ret = true;
// L03: DONE 4: Load Tileset attributes
set->name.Create(tileset_node.attribute("name").as_string());
set->firstgid = tileset_node.attribute("firstgid").as_int();
set->tileWidth = tileset_node.attribute("tilewidth").as_int();
set->tileHeight = tileset_node.attribute("tileheight").as_int();
set->margin = tileset_node.attribute("margin").as_int();
set->spacing = tileset_node.attribute("spacing").as_int();
set->tilecount = tileset_node.attribute("tilecount").as_int();
set->columns = tileset_node.attribute("columns").as_int();
return ret;
}
// Load Tileset image
bool Map::LoadTilesetImage(pugi::xml_node& tileset_node, TileSet* set)
{
bool ret = true;
pugi::xml_node image = tileset_node.child("image");
set->source = tileset_node.child("image").attribute("source").as_string();
set->texHeight = tileset_node.child("image").attribute("tex_height").as_int();
set->texWidth = tileset_node.child("image").attribute("text_width").as_int();
if (image == NULL)
{
LOG("Error parsing tileset xml file: Cannot find 'image' tag.");
ret = false;
}
else
{
// Load Tileset image
SString tmp("%s%s", folder.GetString(), image.attribute("source").as_string());
set->texture = app->tex->Load(tmp.GetString());
}
return ret;
}
// Iterate all layers and load each of them
bool Map::LoadAllLayers(pugi::xml_node mapNode) {
bool ret = true;
for (pugi::xml_node layerNode = mapNode.child("layer"); layerNode && ret; layerNode = layerNode.next_sibling("layer"))
{
//Load the layer
MapLayer* mapLayer = new MapLayer();
ret = LoadLayer(layerNode, mapLayer);
//add the layer to the map
mapData.layers.add(mapLayer);
}
return ret;
}
// Implement a function that loads a single layer layer
bool Map::LoadLayer(pugi::xml_node& node, MapLayer* layer)
{
bool ret = true;
//Load the attributes
layer->name = node.attribute("name").as_string();
layer->width = node.attribute("width").as_int();
layer->height = node.attribute("height").as_int();
//Call Load Propoerties
LoadProperties(node, layer->properties);
//Reserve the memory for the tile array
layer->data = new uint[layer->width * layer->height];
memset(layer->data, 0, layer->width * layer->height);
//Iterate over all the tiles and assign the values
pugi::xml_node tile;
int i = 0;
for (tile = node.child("data").child("tile"); tile && ret; tile = tile.next_sibling("tile"))
{
layer->data[i] = tile.attribute("gid").as_int();
i++;
}
return ret;
}
//Load a group of properties from a node and fill a list with it
bool Map::LoadProperties(pugi::xml_node& node, Properties& properties)
{
bool ret = true;
for (pugi::xml_node propertieNode = node.child("properties").child("property"); propertieNode; propertieNode = propertieNode.next_sibling("property"))
{
Properties::Property* p = new Properties::Property();
p->name = propertieNode.attribute("name").as_string();
p->value = propertieNode.attribute("value").as_int();
properties.list.add(p);
}
return ret;
}
bool Map::LoadAllObjectLayers(pugi::xml_node mapNode)
{
bool ret = true;
LOG("LOADING OBJECT LAYERS....");
for (pugi::xml_node layerNode = mapNode.child("objectgroup"); layerNode && ret; layerNode = layerNode.next_sibling("objectgroup"))
{
//Load the layer
ObjectLayer* objectLayer = new ObjectLayer();
ret = LoadObjectLayer(layerNode, objectLayer);
//add the layer to the map
mapData.objectLayers.add(objectLayer);
}
return ret;
}
bool Map::LoadObjectLayer(pugi::xml_node& node, ObjectLayer* layer)
{
bool ret = true;
//Load object group attributes
layer->name = node.attribute("name").as_string();
//Check what type of object is
if (strcmp(layer->name.GetString(), "Gems") == 0)
{
layer->texture = app->tex->Load("../Output/Assets/Spritesx16/gems.png");
if (layer->texture == NULL)
LOG("Gems texture not loaded...");
}
else if (strcmp(layer->name.GetString(), "checkpoints") == 0)
{
layer->texture = NULL;
}
else if (strcmp(layer->name.GetString(), "Potions") == 0)
{
layer->texture = layer->texture = app->tex->Load("../Output/Assets/Spritesx16/props.png");;
}
LOG("LOADING OBJECT LAYER: %s",layer->name.GetString());
//Create and load each object property
pugi::xml_node object;
//LOG("node: %s", node.name());
for (object = node.child("object"); object && ret; object = object.next_sibling("object"))
{
//LOG("node: %s", object.name());
Object* obj = new Object();
//store object attributes
obj->name = object.attribute("name").as_string();
obj->id = object.attribute("id").as_int();
obj->x = object.attribute("x").as_int();
obj->y = object.attribute("y").as_int();
obj->width = object.attribute("width").as_int();
obj->height = object.attribute("height").as_int();
//LOG("OBJECT ID: %i", obj->id);
//Check what type of object is
if (strcmp(object.attribute("type").as_string(), "player") == 0) {
obj->type = Collider_Type::PLAYEROPENWORLD;
}
else if (strcmp(object.attribute("type").as_string(), "knight") == 0) {
obj->type = Collider_Type::PLAYERKNIGHT;
}
else if (strcmp(object.attribute("type").as_string(), "ranger") == 0) {
obj->type = Collider_Type::PLAYERRANGER;
}
else if (strcmp(object.attribute("type").as_string(), "dummy") == 0) {
obj->type = Collider_Type::DUMMY;
}
else if (strcmp(object.attribute("type").as_string(), "goblin") == 0) {
obj->type = Collider_Type::GOBLIN;
}
else if (strcmp(object.attribute("type").as_string(), "kingGoblin") == 0) {
obj->type = Collider_Type::KINGGOBLIN;
}
else if (strcmp(object.attribute("type").as_string(), "dummyNPC") == 0) {
obj->type = Collider_Type::NPCDUMMY;
}
else if (strcmp(object.attribute("type").as_string(), "guardNPC") == 0) {
obj->type = Collider_Type::NPCGUARD;
}
else if (strcmp(object.attribute("type").as_string(), "villagerWoNPC") == 0) {
obj->type = Collider_Type::NPCWOVILLAGER;
}
else if (strcmp(object.attribute("type").as_string(), "Checkpoint") == 0) {
obj->type = Collider_Type::CHECK_POINT;
}
else if (strcmp(object.attribute("type").as_string(), "wall") == 0)
{
obj->type = Collider_Type::WALL;
}
else if (strcmp(object.attribute("type").as_string(), "entrance") == 0)
{
obj->type = Collider_Type::ENTRANCE;
}
else if (strcmp(object.attribute("type").as_string(), "exit") == 0)
{
obj->type = Collider_Type::EXIT;
}
else if (strcmp(object.attribute("type").as_string(), "combattrigger") == 0)
{
obj->type = Collider_Type::COMBATTRIGGER;
}
else if (strcmp(object.attribute("type").as_string(), "GeneralRoom") == 0)
{
obj->type = Collider_Type::GENERAL_ENTRANCE;
}
else if (strcmp(object.attribute("type").as_string(), "ArchmageRoom") == 0)
{
obj->type = Collider_Type::MAGE_ENTRANCE;
}
else if (strcmp(object.attribute("type").as_string(), "Shop") == 0)
{
obj->type = Collider_Type::SHOP_ENTRANCE;
}
else if (strcmp(object.attribute("type").as_string(), "combattrigger") == 0)
{
obj->type = Collider_Type::COMBATTRIGGER;
}
else if (strcmp(object.attribute("type").as_string(), "chest") == 0)
{
obj->type = Collider_Type::CHEST;
/*if (object.first_child().name() == "properties");
{
pugi::xml_node prop;
prop = object.first_child().first_child();
while (prop != nullptr)
{
pugi::xml_attribute att = prop.attribute("name");
if (att.value() == string("hpPotion"))
{
obj->properties.CreateProperty("hp_potion", 1);
}
prop = prop.next_sibling();
}
}*/
}
layer->objects.add(obj);
//send current object node and obj to store the properties
LoadObject(object, obj);
}
return ret;
}
bool Map::LoadObject(pugi::xml_node& node, Object* object)
{
bool ret = true;
//Iterate over all the object properties and set values, store the object to the list
LOG("Loading object: %s", object->name.GetString());
pugi::xml_node objProperty;
int i = 0;
for (objProperty = node.child("properties").child("property"); objProperty && ret; objProperty = objProperty.next_sibling("property"))
{
Properties::Property* p = new Properties::Property();
//if any other attribute
//p->name = objProperty.attribute("name").as_string();
//p->value = objProperty.attribute("value").as_int();
object->properties.list.add(p);
}
return ret;
}
bool Map::SetMapColliders()
{
bool ret = true;
p2ListItem<ObjectLayer*>* objectLayer;
objectLayer = mapData.objectLayers.start;
LOG("--------!!!SETTING ENTITIES!!!---------");
while (objectLayer != NULL)
{
LOG("SETTING %s LAYER COLLIDER...", objectLayer->data->name.GetString());
p2ListItem<Object*>* object;
object = objectLayer->data->objects.start;
while (object != NULL)
{
//Box 2d has the pivot on the center so add the half of the tile
iPoint spawnPos;
spawnPos.x = object->data->x + object->data->width * 0.5;
spawnPos.y = object->data->y + object->data->height * 0.5;
switch (object->data->type)
{
case PLAYEROPENWORLD:
if (app->entities->openWorld == nullptr)
{
app->entities->AddEntity(object->data->type, spawnPos);
}
else
{
if (app->entities->openWorld->mapPlayerUpdate == true)
{
//if (app->entities->openWorld->physBody == NULL)
//{
// app->entities->openWorld->RestartPhysBody(spawnPos, object->data->type);
//}
//else
//app->entities->openWorld->SetPositionFromPixels(spawnPos);
//app->entities->openWorld->SetPosition(spawnPos);
}
else
{
app->entities->openWorld->mapPlayerUpdate = true;
}
}
LOG("spawn world player...");
break;
case CHEST:
chestIns = app->entities->AddEntity(object->data->type, spawnPos);
if (object->data->properties.GetProperty_("hp_potion") == 1)
{
HPPotion* hp = new HPPotion(HP_POTION);
}
if (object->data->properties.GetProperty("mana_potion", 1))
{
ManaPotion* mp = new ManaPotion(MANA_POTION);
chestIns->AddItem(mp);
}
if (object->data->properties.GetProperty("key", 1))
{
Key* k = new Key(1);
chestIns->AddItem(k);
}
if (object->data->properties.GetProperty("key", 2))
{
Key* k = new Key(2);
chestIns->AddItem(k);
}
if (object->data->properties.GetProperty("key", 3))
{
Key* k = new Key(3);
chestIns->AddItem(k);
}
if (object->data->properties.GetProperty("key", 4))
{
Key* k = new Key(4);
chestIns->AddItem(k);
}
LOG("spawn chest...");
break;
case PLAYERKNIGHT:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("spawn knight...");
break;
case PLAYERRANGER:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("spawn ranger...");
break;
case DUMMY:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("spawn dummy...");
break;
case GOBLIN:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("spawn goblin...");
case KINGGOBLIN:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("spawn King goblin");
case NPCDUMMY:
app->entities->AddEntity(object->data->type, spawnPos);
break;
case NPCGUARD:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("spawn Guard NPC...");
break;
case NPCWOVILLAGER:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("spawn Women villager NPC...");
break;
case PORTAL:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("SETTING PORTAL COLLIDER...");
break;
case CHECK_POINT:
app->entities->AddEntity(object->data->type, spawnPos);
LOG("SETTING CHECKPOINT COLLIDER...");
break;
case WALL:
{
PhysBody* pb;
pb = app->physics->CreateRectangle(spawnPos.x, spawnPos.y, object->data->width, object->data->height, b2_staticBody);
pb->color = { 200,0,0,255 };
pb->type = object->data->type;
Colliders.add(pb);
}
break;
case EXIT:
{
Trigger* t = new Trigger();
t->physBody = app->physics->CreateRectangleSensor(spawnPos.x, spawnPos.y, object->data->width, object->data->height, b2BodyType::b2_staticBody, { 154,38,154,155 });
t->type = object->data->type;
t->physBody->listener = app->entities;
t->physBody->type = object->data->type;
app->entities->exitIntance = t;
app->entities->entities.add(t);
}
break;
case ENTRANCE:
{
Trigger* t = new Trigger();
t->physBody = app->physics->CreateRectangleSensor(spawnPos.x, spawnPos.y, object->data->width, object->data->height, b2BodyType::b2_staticBody, { 154,38,154,155 });
t->type = object->data->type;
t->physBody->listener = app->entities;
t->physBody->type = object->data->type;
app->entities->entranceIntance = t;
app->entities->entities.add(t);
}
break;
case GENERAL_ENTRANCE:
{
Trigger* t = new Trigger();
t->physBody = app->physics->CreateRectangleSensor(spawnPos.x, spawnPos.y, object->data->width, object->data->height, b2BodyType::b2_staticBody, { 154,38,154,155 });
t->type = object->data->type;
t->physBody->listener = app->entities;
t->physBody->type = object->data->type;
app->entities->generalEntrance = t;
app->entities->entities.add(t);
}
break;
case MAGE_ENTRANCE:
{
Trigger* t = new Trigger();
t->physBody = app->physics->CreateRectangleSensor(spawnPos.x, spawnPos.y, object->data->width, object->data->height, b2BodyType::b2_staticBody, { 154,38,154,155 });
t->type = object->data->type;
t->physBody->listener = app->entities;
t->physBody->type = object->data->type;
app->entities->mageEntrance = t;
app->entities->entities.add(t);
}
break;
case SHOP_ENTRANCE:
{
Trigger* t = new Trigger();
t->physBody = app->physics->CreateRectangleSensor(spawnPos.x, spawnPos.y, object->data->width, object->data->height, b2BodyType::b2_staticBody, { 154,38,154,155 });
t->type = object->data->type;
t->physBody->listener = app->entities;
t->physBody->type = object->data->type;
app->entities->shopEntrance = t;
app->entities->entities.add(t);
}
break;
case COMBATTRIGGER:
{
Trigger* t = new Trigger();
t->physBody = app->physics->CreateRectangleSensor(spawnPos.x, spawnPos.y, object->data->width, object->data->height, b2BodyType::b2_staticBody, { 154,38,154,155 });
t->type = object->data->type;
t->physBody->listener = app->entities;
t->physBody->type = object->data->type;
t->id = 0; // Use when there is multiple battle scenes
app->entities->listOfCombatTriggers.add(t);
app->entities->entities.add(t);
t->Start();
}break;
default:
break;
}
object = object->next;
}
objectLayer = objectLayer->next;
}
return ret;
}
void Map::ClearColliders()
{
app->physics->allPhysicBodies.clear();
}
bool Map::LoadState(pugi::xml_node& data)
{
bool ret = true;
return ret;
}
bool Map::SaveState(pugi::xml_node& data) const
{
bool ret = true;
return ret;
}
bool Map::SaveConfig(pugi::xml_node& data) const
{
pugi::xml_node aux = data.append_child("folder");
aux.set_value(folder.GetString());
return true;
}
| 24.637265 | 169 | 0.651997 | [
"render",
"object"
] |
3353bd7eb9bce9f70627044689eff1165446f39a | 7,590 | cc | C++ | test/realm/compqueue.cc | stkaplan/legion | ad82a1c1f39ed20a16df29aa331428d42c0ecfb6 | [
"Apache-2.0"
] | null | null | null | test/realm/compqueue.cc | stkaplan/legion | ad82a1c1f39ed20a16df29aa331428d42c0ecfb6 | [
"Apache-2.0"
] | null | null | null | test/realm/compqueue.cc | stkaplan/legion | ad82a1c1f39ed20a16df29aa331428d42c0ecfb6 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Realm test for completion queues
#include <realm.h>
#include <realm/cmdline.h>
#include "philox.h"
#include "osdep.h"
using namespace Realm;
Logger log_app("app");
typedef Philox_2x32<> PRNG;
enum {
// PRNG keys
PKEY_PROCS,
PKEY_DELAY,
};
enum {
TOP_LEVEL_TASK = Processor::TASK_ID_FIRST_AVAILABLE+0,
SPAWNER_TASK,
WORK_TASK,
};
struct TestConfig {
size_t tasks_per_proc;
size_t max_in_flight;
size_t max_to_pop;
long long min_exec_time, max_exec_time;
int watchdog_timeout;
};
struct SpawnerArgs {
TestConfig config;
CompletionQueue cq;
int index;
};
struct WorkTaskArgs {
long long exec_time;
};
void worker_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
const WorkTaskArgs& w_args = *reinterpret_cast<const WorkTaskArgs *>(args);
// we model doing work by just sleeping for the requested amount of time
usleep(w_args.exec_time);
}
void reap_events(CompletionQueue cq, size_t& in_flight,
size_t max_in_flight, size_t max_to_pop)
{
while(in_flight > max_in_flight) {
// try to pop an event
size_t to_pop = std::min(max_to_pop, in_flight);
std::vector<Event> popped(to_pop, Event::NO_EVENT);
size_t count = cq.pop_events(&popped[0], to_pop);
assert(count <= to_pop);
if(count > 0) {
popped.resize(count);
log_app.info() << "popped " << count << " events: " << PrettyVector<Event>(popped);
in_flight -= count;
} else {
// instead of hammering cq, ask for a nonempty event and wait on it
// before trying again
Event nonempty = cq.get_nonempty_event();
nonempty.wait();
}
}
}
void spawner_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
const SpawnerArgs& s_args = *reinterpret_cast<const SpawnerArgs *>(args);
CompletionQueue cq = s_args.cq;
// get the list of processors we'll spawn work tasks on
Machine::ProcessorQuery pq(Machine::get_machine());
pq.only_kind(p.kind());
std::vector<Processor> procs(pq.begin(), pq.end());
size_t in_flight = 0;
for(size_t i = 0; i < s_args.config.tasks_per_proc; i++) {
// choose a random processor
Processor target = procs[PRNG::rand_int(PKEY_PROCS, s_args.index, i, procs.size())];
// and choose a random delay
WorkTaskArgs w_args;
w_args.exec_time = s_args.config.min_exec_time;
if(s_args.config.max_exec_time > s_args.config.min_exec_time)
w_args.exec_time += PRNG::rand_int(PKEY_DELAY, s_args.index, i,
(s_args.config.max_exec_time -
s_args.config.min_exec_time));
// work tasks get a higher priority to get ahead of the reaping task
Event e = target.spawn(WORK_TASK, &w_args, sizeof(w_args),
ProfilingRequestSet(), Event::NO_EVENT, 1);
log_app.info() << "added event: " << e;
cq.add_event(e);
in_flight++;
// make sure we limit the number in flight
reap_events(s_args.cq, in_flight,
s_args.config.max_in_flight - 1,
s_args.config.max_to_pop);
}
// reap events until we have none in flight
reap_events(s_args.cq, in_flight,
0 /*max_in_flight*/,
s_args.config.max_to_pop);
}
void test_cq(const TestConfig& config,
const std::vector<Processor>& procs, size_t cq_size)
{
CompletionQueue cq = CompletionQueue::create_completion_queue(cq_size);
// set a timeout to catch hangs
if(config.watchdog_timeout > 0)
alarm(config.watchdog_timeout);
// launch a spawner on each processor
std::vector<Event> events;
for(size_t i = 0; i < procs.size(); i++) {
SpawnerArgs s_args;
s_args.config = config;
s_args.cq = cq;
s_args.index = i;
Event e = procs[i].spawn(SPAWNER_TASK, &s_args, sizeof(s_args));
events.push_back(e);
}
// wait on all spawners to finish
Event::merge_events(events).wait();
// all tasks done - turn off alarm
if(config.watchdog_timeout > 0)
alarm(0);
cq.destroy();
}
void top_level_task(const void *args, size_t arglen,
const void *userdata, size_t userlen, Processor p)
{
const TestConfig& config = *reinterpret_cast<const TestConfig *>(args);
Machine::ProcessorQuery pq(Machine::get_machine());
pq.only_kind(p.kind());
std::vector<Processor> procs(pq.begin(), pq.end());
log_app.print() << "compqueue test: " << procs.size() << " procs, "
<< config.tasks_per_proc << " tasks/proc, "
<< config.max_in_flight << " in flight, "
<< config.max_to_pop << " max pop";
// create a completion queue - it should not ever have to hold more
// than #procs * max_in_flight events
size_t cq_size = procs.size() * config.max_in_flight;
test_cq(config, procs, cq_size);
// also test the dynamic completion queue case
test_cq(config, procs, 0);
log_app.info() << "completed successfully";
Runtime::get_runtime().shutdown(Event::NO_EVENT, 0 /*success*/);
}
// we're going to use alarm() as a watchdog to detect deadlocks
void sigalrm_handler(int sig)
{
log_app.fatal() << "HELP! Alarm triggered - likely deadlock!";
abort();
}
int main(int argc, const char **argv)
{
Runtime rt;
rt.init(&argc, (char ***)&argv);
TestConfig config;
config.tasks_per_proc = 1000;
config.max_in_flight = 20;
config.max_to_pop = 10;
config.min_exec_time = 10; // 10us
config.max_exec_time = 10000; // 10ms
// above parameters results in ~1000 * 10ms = 10s of work per processor
// if we take more than ~5x that, something's wrong
config.watchdog_timeout = 60; // 60 seconds
CommandLineParser clp;
clp.add_option_int("-t", config.tasks_per_proc);
clp.add_option_int("-m", config.max_in_flight);
clp.add_option_int("-p", config.max_to_pop);
clp.add_option_int("-min", config.min_exec_time);
clp.add_option_int("-max", config.max_exec_time);
clp.add_option_int("-timeout", config.watchdog_timeout);
bool ok = clp.parse_command_line(argc, argv);
assert(ok);
// try to use a cpu proc, but if that doesn't exist, take whatever we can get
Processor p = Machine::ProcessorQuery(Machine::get_machine())
.only_kind(Processor::LOC_PROC)
.first();
if(!p.exists())
p = Machine::ProcessorQuery(Machine::get_machine()).first();
assert(p.exists());
Processor::register_task_by_kind(p.kind(), false /*!global*/,
TOP_LEVEL_TASK,
CodeDescriptor(top_level_task),
ProfilingRequestSet()).external_wait();
Processor::register_task_by_kind(p.kind(), false /*!global*/,
SPAWNER_TASK,
CodeDescriptor(spawner_task),
ProfilingRequestSet()).external_wait();
Processor::register_task_by_kind(p.kind(), false /*!global*/,
WORK_TASK,
CodeDescriptor(worker_task),
ProfilingRequestSet()).external_wait();
signal(SIGALRM, sigalrm_handler);
// collective launch of a single top level task
rt.collective_spawn(p, TOP_LEVEL_TASK, &config, sizeof(config));
// now sleep this thread until that shutdown actually happens
int ret = rt.wait_for_shutdown();
return ret;
}
| 29.648438 | 89 | 0.695125 | [
"vector",
"model"
] |
3354282cf3b2a4ee7c0c62df39c4dd612b0aee32 | 2,115 | cpp | C++ | oneEngine/oneGame/source/after/entities/item/props/ItemElectricSource.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/after/entities/item/props/ItemElectricSource.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/after/entities/item/props/ItemElectricSource.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z |
#include "ItemElectricSource.h"
#include "after/entities/props/props/ElectricSourceComponent.h"
//#include "CVoxelTerrain.h"
#include "core/time/time.h"
#include "engine/physics/raycast/Raycaster.h"
#include "renderer/material/glMaterial.h"
#include "renderer/logic/model/CModel.h"
#include "after/types/terrain/BlockTracker.h"
#include "after/terrain/edit/CTerrainAccessor.h"
// Constructor (on ground)
ItemElectricSource::ItemElectricSource ( void )
: CWeaponItem( ItemData() )
{
InitializeCommon();
}
// Common code
void ItemElectricSource::InitializeCommon ( void )
{
transform.scale = Vector3d( 0.2f, 0.2f, 0.2f );
glMaterial* newMat = new glMaterial();
newMat->m_diffuse = Color( 0.6f,0.3f,0.3f );
newMat->removeReference();
pModel = new CModel( string("models\\geosphere.FBX") );
}
// Destructor
ItemElectricSource::~ItemElectricSource ( void )
{
}
// Update
void ItemElectricSource::Update ( void )
{
}
// Use places the object on a terrain bit
bool ItemElectricSource::Use ( int x )
{
if ( x == Item::USecondary )
{
if ( !CanUse( x ) )
{
SetCooldown( x, Time::deltaTime*3.0f );
return true;
}
SetCooldown( x, Time::deltaTime*3.0f );
bool placed = false;
// Remove cube that player is looking at.
Ray viewRay = pOwner->GetEyeRay();
RaycastHit result;
BlockTrackInfo block;
if ( Raycaster.Raycast( viewRay, 8.0f, &result, Physics::GetCollisionFilter(Layers::PHYS_BULLET_TRACE,0,31), pOwner ) )
{
TerrainAccess.GetBlockAtPosition( result, block );
if ( block.valid )
{
ElectricSourceComponent* newComponent = new ElectricSourceComponent( block );
newComponent->transform.position = result.hitPos + result.hitNormal*0.5f;
//AddToTerrain();
placed = true;
}
}
if ( placed )
{
weaponItemState.iCurrentStack -= 1;
if ( weaponItemState.iCurrentStack == 0 )
{
//CGameState::pActive->DeleteObject( this );
// Delete this object in the inventory
}
}
/*if ( placed )
{
holdState = None;
pOwner = NULL;
if ( pBody == NULL )
CreatePhysics();
}*/
return true;
}
else
{
return false;
}
} | 22.263158 | 121 | 0.683215 | [
"object",
"model",
"transform"
] |
33589aad4f81b64132e93c7519230d9885ece765 | 1,990 | hpp | C++ | src/rti/reflection/specular.hpp | XaverKlemenschits/rti | 0672079da94fd726c597041a6b23ee24d9906e82 | [
"BSD-3-Clause"
] | 3 | 2019-05-16T07:44:36.000Z | 2020-05-08T13:55:12.000Z | src/rti/reflection/specular.hpp | XaverKlemenschits/rti | 0672079da94fd726c597041a6b23ee24d9906e82 | [
"BSD-3-Clause"
] | null | null | null | src/rti/reflection/specular.hpp | XaverKlemenschits/rti | 0672079da94fd726c597041a6b23ee24d9906e82 | [
"BSD-3-Clause"
] | 4 | 2020-06-24T08:18:41.000Z | 2021-05-28T10:22:13.000Z | #pragma once
#include "i_reflection.hpp"
namespace rti { namespace reflection {
template<typename Ty>
class specular : public rti::reflection::i_reflection<Ty> {
public:
rti::util::pair<rti::util::triple<Ty> >
use(RTCRay& pRayIn, RTCHit& pHitIn, rti::geo::meta_geometry<Ty>& pGeometry,
rti::rng::i_rng& pRng, rti::rng::i_rng::i_state& pRngState) override final {
return use(pRayIn, pHitIn, pGeometry);
}
static
rti::util::pair<rti::util::triple<Ty> >
use(RTCRay& pRayIn, RTCHit& pHitIn, rti::geo::meta_geometry<Ty>& pGeometry) {
auto primID = pHitIn.primID;
auto normal = pGeometry.get_normal(primID);
// Instead of querying the geometry object for the surface normal one could used
// the (unnormalized) surface normal provided by the rayhit.hit struct.
auto dirOldInv = rti::util::inv ( rti::util::triple<Ty> {pRayIn.dir_x, pRayIn.dir_y, pRayIn.dir_z} );
// For computing the specular refelction direction we need the vectors to be normalized.
assert(rti::util::is_normalized(normal) && "surface normal vector is supposed to be normalized");
assert(rti::util::is_normalized(dirOldInv) && "direction vector is supposed to be normalized");
// Compute new direction
auto direction =
rti::util::diff(rti::util::scale(2 * rti::util::dot_product(normal, dirOldInv), normal), dirOldInv);
// // instead of using this epsilon one could set tnear to a value other than zero
// auto epsilon = 1e-6;
// auto ox = pRayIn.org_x + pRayIn.dir_x * pRayIn.tfar + normal[0] * epsilon;
// auto oy = pRayIn.org_y + pRayIn.dir_y * pRayIn.tfar + normal[1] * epsilon;
// auto oz = pRayIn.org_z + pRayIn.dir_z * pRayIn.tfar + normal[2] * epsilon;
// auto newOrigin = rti::util::triple<Ty> {(Ty) ox, (Ty) oy, (Ty) oz};
auto newOrigin = pGeometry.get_new_origin(pRayIn, primID);
return {newOrigin, direction};
}
private:
};
}} // namespace
| 44.222222 | 108 | 0.665327 | [
"geometry",
"object",
"vector"
] |
3359968fec4965107fddaa67a44b79d7a3342825 | 4,779 | cpp | C++ | amr-wind/physics/ChannelFlowLES.cpp | ndevelder/amr-wind-channel-les | 51b048ba30a5ed3ac1bd055e807f4d59a64a45ea | [
"BSD-3-Clause"
] | null | null | null | amr-wind/physics/ChannelFlowLES.cpp | ndevelder/amr-wind-channel-les | 51b048ba30a5ed3ac1bd055e807f4d59a64a45ea | [
"BSD-3-Clause"
] | null | null | null | amr-wind/physics/ChannelFlowLES.cpp | ndevelder/amr-wind-channel-les | 51b048ba30a5ed3ac1bd055e807f4d59a64a45ea | [
"BSD-3-Clause"
] | null | null | null | #include "amr-wind/physics/ChannelFlowLES.H"
#include "amr-wind/CFDSim.H"
#include "AMReX_iMultiFab.H"
#include "AMReX_MultiFabUtil.H"
#include "AMReX_ParmParse.H"
#include "amr-wind/utilities/trig_ops.H"
#include "amr-wind/utilities/DirectionSelector.H"
namespace amr_wind {
namespace channel_flow_les {
ChannelFlowLES::ChannelFlowLES(CFDSim& sim)
: m_time(sim.time()), m_repo(sim.repo()), m_mesh(sim.mesh())
{
{
amrex::ParmParse pp("ChannelFlowLES");
pp.query("normal_direction", m_norm_dir);
pp.query("density", m_rho);
pp.query("re_tau", m_re_tau);
pp.query("perturb_velocity", m_perturb_vel);
pp.query("Uperiods", m_Uperiods);
pp.query("Vperiods", m_Vperiods);
pp.query("Wperiods", m_Wperiods);
pp.query("perturb_scale", m_perturb_scale);
}
{
amrex::Real mu;
amrex::ParmParse pp("transport");
pp.query("viscosity", mu);
// Assumes a boundary layer height of 1.0
m_utau = mu * m_re_tau / (m_rho * 1.0);
m_ytau = mu / (m_utau * m_rho);
}
{
std::string statistics_mode = "precursor";
int dir = 2;
amrex::ParmParse pp("ChannelFlowLES");
pp.query("normal_direction", dir);
pp.query("statistics_mode", statistics_mode);
m_stats =
ChannelStatsBase::create(statistics_mode, sim, dir);
}
}
/** Initialize the velocity, density fields at the beginning of the
* simulation.
*/
void ChannelFlowLES::initialize_fields(int level, const amrex::Geometry& geom)
{
switch (m_norm_dir) {
case 1:
initialize_fields(level, geom, YDir(), 1);
break;
case 2:
initialize_fields(level, geom, ZDir(), 2);
break;
default:
amrex::Abort("axis must be equal to 1 or 2");
break;
}
}
template <typename IndexSelector>
void ChannelFlowLES::initialize_fields(
int level,
const amrex::Geometry& geom,
const IndexSelector& idxOp,
const int n_idx)
{
const amrex::Real kappa = m_kappa;
const amrex::Real y_tau = m_ytau;
const amrex::Real utau = m_utau;
auto& velocity = m_repo.get_field("velocity")(level);
auto& density = m_repo.get_field("density")(level);
density.setVal(m_rho);
for (amrex::MFIter mfi(velocity); mfi.isValid(); ++mfi) {
const auto& vbx = mfi.validbox();
const auto& dx = geom.CellSizeArray();
const auto& problo = geom.ProbLoArray();
const auto& probhi = geom.ProbHiArray();
auto vel = velocity.array(mfi);
const bool perturb_vel = m_perturb_vel;
const amrex::Real pi = M_PI;
const amrex::Real per_scale = m_perturb_scale;
const amrex::Real aval = m_Uperiods * 2.0 * pi / (probhi[0] - problo[0]);
const amrex::Real bval = m_Vperiods * 2.0 * pi / (probhi[1] - problo[1]);
const amrex::Real cval = m_Wperiods * 2.0 * pi / (probhi[2] - problo[2]);
// Currently assumes a channel half height of 1.0m
amrex::ParallelFor(
vbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
const amrex::Real x = problo[0] + (i + 0.5) * dx[0];
const amrex::Real y = problo[1] + (j + 0.5) * dx[1];
const amrex::Real z = problo[2] + (k + 0.5) * dx[2];
const int n_ind = idxOp(i, j, k);
amrex::Real h = problo[n_idx] + (n_ind + 0.5) * dx[n_idx];
if (h > 1.0) h = 2.0 - h;
const amrex::Real hp = h / y_tau;
vel(i, j, k, 0) =
utau * (1. / kappa * std::log1p(kappa * hp) +
7.8 * (1.0 - std::exp(-hp / 11.0) -
(hp / 11.0) * std::exp(-hp / 3.0)));
vel(i, j, k, 1) = 0.0;
vel(i, j, k, 2) = 0.0;
if (perturb_vel) {
const amrex::Real xl = x - problo[0];
const amrex::Real yl = y - problo[1];
const amrex::Real zl = z - problo[2];
const amrex::Real damp = 1.0 - std::exp(-6.0 * h * h);
vel(i, j, k, 0) += per_scale * damp * std::cos(aval * yl);
vel(i, j, k, 1) += per_scale * damp * std::cos(bval * xl);
vel(i, j, k, 2) += per_scale * damp * std::cos(cval * zl);
}
});
}
}
void ChannelFlowLES::post_init_actions()
{
m_stats->post_init_actions();
}
void ChannelFlowLES::pre_advance_work()
{
const auto& vel_pa = m_stats->vel_profile();
}
void ChannelFlowLES::post_advance_work()
{
m_stats->post_advance_work();
}
} // namespace channel_flow
} // namespace amr_wind
| 31.86 | 81 | 0.550115 | [
"mesh",
"geometry"
] |
335ec77cea5660347e64c30cb3f45e886e0205ce | 6,172 | cpp | C++ | Modules/Classification/DataCollection/Utilities/mitkCostingStatistic.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | 1 | 2021-11-20T08:19:27.000Z | 2021-11-20T08:19:27.000Z | Modules/Classification/DataCollection/Utilities/mitkCostingStatistic.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | Modules/Classification/DataCollection/Utilities/mitkCostingStatistic.cpp | wyyrepo/MITK | d0837f3d0d44f477b888ec498e9a2ed407e79f20 | [
"BSD-3-Clause"
] | null | null | null | #include <mitkCostingStatistic.h>
#include <mitkDataCollection.h>
#include <mitkCollectionStatistic.h>
#include <sstream>
// DataCollection Stuff
#include <mitkDataCollectionImageIterator.h>
//stl stuff
#include <sstream>
static void EnsureDataImageInCollection(mitk::DataCollection::Pointer collection, std::string origin, std::string target)
{
typedef itk::Image<double, 3> FeatureImage;
typedef itk::Image<unsigned char, 3> LabelImage;
if (collection->HasElement(origin))
{
LabelImage::Pointer originImage = dynamic_cast<LabelImage*>(collection->GetData(origin).GetPointer());
MITK_INFO << "Creating new Element";
if (!collection->HasElement(target) && originImage.IsNotNull())
{
MITK_INFO << "New image necessary";
FeatureImage::Pointer image = FeatureImage::New();
image->SetRegions(originImage->GetLargestPossibleRegion());
image->SetSpacing(originImage->GetSpacing());
image->SetOrigin(originImage->GetOrigin());
image->SetDirection(originImage->GetDirection());
image->Allocate();
collection->AddData(dynamic_cast<itk::DataObject*>(image.GetPointer()),target,"");
}
}
for (std::size_t i = 0; i < collection->Size();++i)
{
mitk::DataCollection* newCol = dynamic_cast<mitk::DataCollection*>(collection->GetData(i).GetPointer());
if (newCol != nullptr)
{
EnsureDataImageInCollection(newCol, origin, target);
}
}
}
static void EnsureLabelImageInCollection(mitk::DataCollection::Pointer collection, std::string origin, std::string target)
{
typedef itk::Image<unsigned char, 3> FeatureImage;
typedef itk::Image<unsigned char, 3> LabelImage;
if (collection->HasElement(origin))
{
LabelImage::Pointer originImage = dynamic_cast<LabelImage*>(collection->GetData(origin).GetPointer());
MITK_INFO << "Creating new Element";
if (!collection->HasElement(target) && originImage.IsNotNull())
{
MITK_INFO << "New image necessary";
FeatureImage::Pointer image = FeatureImage::New();
image->SetRegions(originImage->GetLargestPossibleRegion());
image->SetSpacing(originImage->GetSpacing());
image->SetOrigin(originImage->GetOrigin());
image->SetDirection(originImage->GetDirection());
image->Allocate();
collection->AddData(dynamic_cast<itk::DataObject*>(image.GetPointer()),target,"");
}
}
for (std::size_t i = 0; i < collection->Size();++i)
{
mitk::DataCollection* newCol = dynamic_cast<mitk::DataCollection*>(collection->GetData(i).GetPointer());
if (newCol != nullptr)
{
EnsureLabelImageInCollection(newCol, origin, target);
}
}
}
void mitk::CostingStatistic::SetCollection(mitk::DataCollection::Pointer collection)
{
m_Collection = collection;
}
mitk::DataCollection::Pointer mitk::CostingStatistic::GetCollection()
{
return m_Collection;
}
bool mitk::CostingStatistic::UpdateCollection()
{
EnsureDataImageInCollection(m_Collection, m_MaskName, m_CombinedProbabilityA);
EnsureDataImageInCollection(m_Collection, m_MaskName, m_CombinedProbabilityB);
EnsureLabelImageInCollection(m_Collection, m_MaskName, m_CombinedLabelName);
std::vector<DataCollectionImageIterator<double, 3> > iterProbA;
std::vector<DataCollectionImageIterator<double, 3> > iterProbB;
for (std::size_t i = 0; i < m_ProbabilityClassA.size(); ++i)
{
DataCollectionImageIterator<double, 3> iter(m_Collection, m_ProbabilityClassA[i]);
iterProbA.push_back(iter);
}
for (std::size_t i = 0; i < m_ProbabilityClassB.size(); ++i)
{
DataCollectionImageIterator<double, 3> iter(m_Collection, m_ProbabilityClassB[i]);
iterProbB.push_back(iter);
}
DataCollectionImageIterator<double, 3> iterCombineA(m_Collection, m_CombinedProbabilityA);
DataCollectionImageIterator<double, 3> iterCombineB(m_Collection, m_CombinedProbabilityB);
DataCollectionImageIterator<unsigned char, 3> iterMask(m_Collection, m_MaskName);
while (!iterMask.IsAtEnd())
{
if (iterMask.GetVoxel() > 0)
{
double probA = 0;
double probB = 0;
for (std::size_t i = 0; i < iterProbA.size(); ++i)
{
probA += iterProbA[i].GetVoxel();
}
for (std::size_t i = 0; i < iterProbB.size(); ++i)
{
probB += iterProbB[i].GetVoxel();
}
iterCombineA.SetVoxel(probA * 100);
iterCombineB.SetVoxel(probB * 100);
}
else
{
iterCombineA.SetVoxel(0.0);
iterCombineB.SetVoxel(0.0);
}
++iterCombineA;
++iterCombineB;
++iterMask;
for (std::size_t i = 0; i < iterProbA.size(); ++i)
{
++(iterProbA[i]);
}
for (std::size_t i = 0; i < iterProbB.size(); ++i)
{
++(iterProbB[i]);
}
}
return false;
}
bool mitk::CostingStatistic::CalculateClass(double threshold)
{
DataCollectionImageIterator<unsigned char, 3> iterMask(m_Collection, m_MaskName);
DataCollectionImageIterator<unsigned char, 3> iterLabel(m_Collection, m_CombinedLabelName);
DataCollectionImageIterator<double, 3> iterCombineA(m_Collection, m_CombinedProbabilityA);
DataCollectionImageIterator<double, 3> iterCombineB(m_Collection, m_CombinedProbabilityB);
while (!iterMask.IsAtEnd())
{
if (iterMask.GetVoxel() > 0)
{
double probA = iterCombineA.GetVoxel() / (iterCombineA.GetVoxel() + iterCombineB.GetVoxel());
probA *= 100;
iterLabel.SetVoxel(probA >= threshold ? 1 : 2);
}
else
{
iterLabel.SetVoxel(0);
}
++iterMask;
++iterLabel;
++iterCombineA;
++iterCombineB;
}
return true;
}
bool mitk::CostingStatistic::WriteStatistic(std::ostream &out,std::ostream &sout, double stepSize, std::string shortLabel)
{
UpdateCollection();
for (double threshold = 0 ; threshold <= 100; threshold += stepSize)
{
CalculateClass(threshold);
std::stringstream ss;
ss << shortLabel << ";" << threshold;
mitk::CollectionStatistic stat;
stat.SetCollection(m_Collection);
stat.SetClassCount(2);
stat.SetGoldName("GTV");
stat.SetTestName(m_CombinedLabelName);
stat.SetMaskName(m_MaskName);
stat.Update();
stat.Print(out, sout,false, ss.str());
}
return true;
}
| 31.329949 | 122 | 0.691672 | [
"vector"
] |
3365beeeec5efff38c807ac28309f6a08f882876 | 32,859 | cc | C++ | src/modular/bin/sessionmgr/story_runner/story_provider_impl.cc | wwjiang007/fuchsia-1 | 0db66b52b5bcd3e27c8b8c2163925309e8522f94 | [
"BSD-2-Clause"
] | 210 | 2019-02-05T12:45:09.000Z | 2022-03-28T07:59:06.000Z | src/modular/bin/sessionmgr/story_runner/story_provider_impl.cc | wwjiang007/fuchsia-1 | 0db66b52b5bcd3e27c8b8c2163925309e8522f94 | [
"BSD-2-Clause"
] | 5 | 2019-12-04T15:13:37.000Z | 2020-02-19T08:11:38.000Z | src/modular/bin/sessionmgr/story_runner/story_provider_impl.cc | wwjiang007/fuchsia-1 | 0db66b52b5bcd3e27c8b8c2163925309e8522f94 | [
"BSD-2-Clause"
] | 73 | 2019-03-06T18:55:23.000Z | 2022-03-26T12:04:51.000Z | // Copyright 2016 The Fuchsia 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/modular/bin/sessionmgr/story_runner/story_provider_impl.h"
#include <fuchsia/ui/app/cpp/fidl.h>
#include <lib/async/cpp/task.h>
#include <lib/async/default.h>
#include <lib/fidl/cpp/interface_handle.h>
#include <lib/fidl/cpp/interface_request.h>
#include <lib/fit/function.h>
#include <lib/syslog/cpp/macros.h>
#include <lib/zx/time.h>
#include <memory>
#include <utility>
#include <vector>
#include "src/lib/fsl/handles/object_info.h"
#include "src/lib/fsl/vmo/strings.h"
#include "src/lib/uuid/uuid.h"
#include "src/modular/bin/basemgr/cobalt/cobalt.h"
#include "src/modular/bin/sessionmgr/annotations.h"
#include "src/modular/bin/sessionmgr/storage/story_storage.h"
#include "src/modular/bin/sessionmgr/story_runner/story_controller_impl.h"
#include "src/modular/lib/common/teardown.h"
#include "src/modular/lib/fidl/array_to_string.h"
#include "src/modular/lib/fidl/clone.h"
#include "src/modular/lib/fidl/proxy.h"
namespace modular {
class StoryProviderImpl::StopStoryCall : public Operation<> {
public:
using StoryRuntimesMap = std::map<std::string, struct StoryRuntimeContainer>;
StopStoryCall(std::string story_id, const bool skip_notifying_sessionshell,
StoryRuntimesMap* const story_runtime_containers, ResultCall result_call)
: Operation("StoryProviderImpl::StopStoryCall", std::move(result_call)),
story_id_(std::move(story_id)),
skip_notifying_sessionshell_(skip_notifying_sessionshell),
story_runtime_containers_(story_runtime_containers) {}
private:
void Run() override {
FlowToken flow{this};
auto i = story_runtime_containers_->find(story_id_);
if (i == story_runtime_containers_->end()) {
FX_LOGS(WARNING) << "I was told to stop story " << story_id_ << ", but I can't find it.";
return;
}
FX_DCHECK(i->second.controller_impl != nullptr);
i->second.controller_impl->Teardown(skip_notifying_sessionshell_,
[weak_ptr = GetWeakPtr(), this, flow] {
// Ensure |story_runtime_containers_| has not been
// destroyed.
//
// This operation and its parent |StoryProviderImpl| may
// be destroyed before this callback executes, for example
// when |StoryProviderImpl.Teardown| times out. When this
// happens, `operation_queue_` and this operation are
// destroyed before |story_runtime_containers_|,
// invalidating |weak_ptr|.
if (!weak_ptr)
return;
story_runtime_containers_->erase(story_id_);
});
}
private:
const std::string story_id_;
const bool skip_notifying_sessionshell_;
StoryRuntimesMap* const story_runtime_containers_;
};
// Loads a StoryRuntimeContainer object and stores it in
// |story_provider_impl.story_runtime_containers_| so that the story is ready to be run.
class StoryProviderImpl::LoadStoryRuntimeCall : public Operation<StoryRuntimeContainer*> {
public:
LoadStoryRuntimeCall(StoryProviderImpl* const story_provider_impl,
SessionStorage* const session_storage, std::string story_id,
inspect::Node* root_node, ResultCall result_call)
: Operation("StoryProviderImpl::LoadStoryRuntimeCall", std::move(result_call)),
story_provider_impl_(story_provider_impl),
session_storage_(session_storage),
story_id_(std::move(story_id)),
session_inspect_node_(root_node) {}
private:
void Run() override {
FlowToken flow{this, &story_runtime_container_};
// Use the existing controller, if possible.
// This won't race against itself because it's managed by an operation
// queue.
auto i = story_provider_impl_->story_runtime_containers_.find(story_id_);
if (i != story_provider_impl_->story_runtime_containers_.end()) {
story_runtime_container_ = &i->second;
return;
}
auto story_data = session_storage_->GetStoryData(story_id_);
if (!story_data) {
return;
// Operation finishes since |flow| goes out of scope.
}
Cont(std::move(story_data), flow);
}
void Cont(fuchsia::modular::internal::StoryDataPtr story_data, FlowToken flow) {
auto story_storage = session_storage_->GetStoryStorage(story_id_);
struct StoryRuntimeContainer container {
.executor = std::make_unique<async::Executor>(async_get_default_dispatcher()),
.storage = std::move(story_storage), .current_data = std::move(story_data),
};
container.InitializeInspect(story_id_, session_inspect_node_);
container.controller_impl =
std::make_unique<StoryControllerImpl>(story_id_, session_storage_, container.storage.get(),
story_provider_impl_, container.story_node.get());
auto it =
story_provider_impl_->story_runtime_containers_.emplace(story_id_, std::move(container));
story_runtime_container_ = &it.first->second;
}
StoryProviderImpl* const story_provider_impl_; // not owned
SessionStorage* const session_storage_; // not owned
const std::string story_id_;
inspect::Node* session_inspect_node_;
// Return value.
StoryRuntimeContainer* story_runtime_container_ = nullptr;
// Sub operations run in this queue.
OperationQueue operation_queue_;
};
class StoryProviderImpl::StopAllStoriesCall : public Operation<> {
public:
StopAllStoriesCall(StoryProviderImpl* const story_provider_impl, ResultCall result_call)
: Operation("StoryProviderImpl::StopAllStoriesCall", std::move(result_call)),
story_provider_impl_(story_provider_impl) {}
private:
void Run() override {
FlowToken flow{this};
for (auto& it : story_provider_impl_->story_runtime_containers_) {
// Each callback has a copy of |flow| which only goes out-of-scope
// once the story corresponding to |it| stops.
//
// TODO(thatguy): If the StoryControllerImpl is deleted before it can
// complete StopWithoutNotifying(), we will never be called back and the
// OperationQueue on which we're running will block. Moving over to
// fpromise::promise will allow us to observe cancellation.
operations_.Add(std::make_unique<StopStoryCall>(
it.first, true /* skip_notifying_sessionshell */,
&story_provider_impl_->story_runtime_containers_, [flow] {}));
}
}
OperationCollection operations_;
StoryProviderImpl* const story_provider_impl_; // not owned
};
class StoryProviderImpl::StopStoryShellCall : public Operation<> {
public:
StopStoryShellCall(StoryProviderImpl* const story_provider_impl, ResultCall result_call)
: Operation("StoryProviderImpl::StopStoryShellCall", std::move(result_call)),
story_provider_impl_(story_provider_impl) {}
private:
void Run() override {
FlowToken flow{this};
if (story_provider_impl_->preloaded_story_shell_app_) {
// Calling Teardown() below will branch |flow| into normal and timeout
// paths. |flow| must go out of scope when either of the paths
// finishes.
FlowTokenHolder branch{flow};
story_provider_impl_->preloaded_story_shell_app_->Teardown(
kBasicTimeout, [branch] { std::unique_ptr<FlowToken> flow = branch.Continue(); });
}
}
StoryProviderImpl* const story_provider_impl_; // not owned
};
StoryProviderImpl::StoryProviderImpl(Environment* const session_environment,
SessionStorage* const session_storage,
fuchsia::modular::session::AppConfig story_shell_config,
fuchsia::modular::StoryShellFactoryPtr story_shell_factory,
ComponentContextInfo component_context_info,
AgentServicesFactory* const agent_services_factory,
inspect::Node* root_node)
: session_environment_(session_environment),
session_storage_(session_storage),
story_shell_config_(std::move(story_shell_config)),
story_shell_factory_(std::move(story_shell_factory)),
component_context_info_(std::move(component_context_info)),
agent_services_factory_(agent_services_factory),
session_inspect_node_(root_node),
weak_factory_(this) {
session_storage_->SubscribeStoryDeleted(
[weak_this = weak_factory_.GetWeakPtr()](std::string story_id) {
if (!weak_this) {
return WatchInterest::kStop;
}
weak_this->OnStoryStorageDeleted(std::move(story_id));
return WatchInterest::kContinue;
});
session_storage_->SubscribeStoryUpdated(
[weak_this = weak_factory_.GetWeakPtr()](
std::string story_id, const fuchsia::modular::internal::StoryData& story_data) {
if (!weak_this) {
return WatchInterest::kStop;
}
weak_this->OnStoryStorageUpdated(std::move(story_id), story_data);
return WatchInterest::kContinue;
});
}
StoryProviderImpl::~StoryProviderImpl() = default;
void StoryProviderImpl::Connect(fidl::InterfaceRequest<fuchsia::modular::StoryProvider> request) {
bindings_.AddBinding(this, std::move(request));
}
void StoryProviderImpl::StopAllStories(fit::function<void()> callback) {
operation_queue_.Add(std::make_unique<StopAllStoriesCall>(this, std::move(callback)));
}
void StoryProviderImpl::SetPresentationProtocol(PresentationProtocolPtr presentation_protocol) {
FX_DCHECK(!std::holds_alternative<std::monostate>(presentation_protocol))
<< "Presentation protocol cannot be set to the PresentationProtocolPtr default value. "
"It must be either a SessionShellPtr or a GraphicalPresenterPtr.";
presentation_protocol_ = std::move(presentation_protocol);
if (auto graphical_presenter =
std::get_if<fuchsia::element::GraphicalPresenterPtr>(&presentation_protocol_)) {
graphical_presenter->set_error_handler([](zx_status_t status) {
FX_PLOGS(ERROR, status)
<< "GraphicalPresenter service channel (from session shell component) "
"unexpectedly closed.";
});
} else if (auto session_shell =
std::get_if<fuchsia::modular::SessionShellPtr>(&presentation_protocol_)) {
session_shell->set_error_handler([](zx_status_t status) {
FX_PLOGS(ERROR, status) << "SessionShell service channel (from session shell component) "
"unexpectedly closed.";
});
} else {
FX_LOGS(FATAL) << "Unhandled PresentationProtocolPtr alternative: "
<< presentation_protocol_.index();
FX_NOTREACHED();
}
// Re-attach/present pending views from previous calls to AttachOrPresentView()
for (auto& pending_call : pending_attach_or_present_view_calls) {
AttachOrPresentView(std::move(pending_call.story_id),
std::move(pending_call.view_holder_token));
}
pending_attach_or_present_view_calls.clear();
}
void StoryProviderImpl::Teardown(fit::function<void()> callback) {
// Closing all binding to this instance ensures that no new messages come
// in, though previous messages need to be processed. The stopping of
// stories is done on |operation_queue_| since that must strictly happen
// after all pending messgages have been processed.
bindings_.CloseAll();
if (auto graphical_presenter =
std::get_if<fuchsia::element::GraphicalPresenterPtr>(&presentation_protocol_)) {
graphical_presenter->set_error_handler(nullptr);
} else if (auto session_shell =
std::get_if<fuchsia::modular::SessionShellPtr>(&presentation_protocol_)) {
session_shell->set_error_handler(nullptr);
} else if (std::holds_alternative<std::monostate>(presentation_protocol_)) {
// Nothing to do. SetPresentationProtocol has not been called, so no error handlers to clear.
} else {
FX_LOGS(FATAL) << "Unhandled PresentationProtocolPtr alternative: "
<< presentation_protocol_.index();
FX_NOTREACHED();
}
operation_queue_.Add(std::make_unique<StopAllStoriesCall>(this, [] {}));
operation_queue_.Add(std::make_unique<StopStoryShellCall>(this, std::move(callback)));
}
// |fuchsia::modular::StoryProvider|
void StoryProviderImpl::Watch(
fidl::InterfaceHandle<fuchsia::modular::StoryProviderWatcher> watcher) {
auto watcher_ptr = watcher.Bind();
for (const auto& item : story_runtime_containers_) {
const auto& container = item.second;
FX_CHECK(container.current_data->has_story_info());
watcher_ptr->OnChange2(CloneStruct(container.current_data->story_info()),
container.controller_impl->runtime_state(),
fuchsia::modular::StoryVisibilityState::DEFAULT);
}
watchers_.AddInterfacePtr(std::move(watcher_ptr));
}
StoryControllerImpl* StoryProviderImpl::GetStoryControllerImpl(std::string story_id) {
auto it = story_runtime_containers_.find(story_id);
if (it == story_runtime_containers_.end()) {
return nullptr;
}
auto& container = it->second;
return container.controller_impl.get();
}
std::unique_ptr<AsyncHolderBase> StoryProviderImpl::StartStoryShell(
std::string story_id, fuchsia::ui::views::ViewToken view_token,
fidl::InterfaceRequest<fuchsia::modular::StoryShell> story_shell_request) {
// When we're supplied a StoryShellFactory, use it to get StoryShells instead
// of launching the story shell as a separate component. In this case, there
// is also nothing to preload, so ignore |preloaded_story_shell_app_|.
if (story_shell_factory_) {
story_shell_factory_->AttachStory(story_id, std::move(story_shell_request));
auto on_teardown = [this, story_id = std::move(story_id)](fit::function<void()> done) {
story_shell_factory_->DetachStory(story_id, std::move(done));
};
return std::make_unique<ClosureAsyncHolder>(/*name=*/story_id, std::move(on_teardown));
}
MaybeLoadStoryShell();
fuchsia::ui::app::ViewProviderPtr view_provider;
preloaded_story_shell_app_->services().ConnectToService(view_provider.NewRequest());
view_provider->CreateView(std::move(view_token.value), nullptr, nullptr);
preloaded_story_shell_app_->services().ConnectToService(std::move(story_shell_request));
auto story_shell_holder = std::move(preloaded_story_shell_app_);
return story_shell_holder;
}
void StoryProviderImpl::MaybeLoadStoryShell() {
if (preloaded_story_shell_app_) {
return;
}
auto service_list = fuchsia::sys::ServiceList::New();
for (auto service_name : component_context_info_.agent_runner->GetAgentServices()) {
service_list->names.push_back(service_name);
}
component_context_info_.agent_runner->PublishAgentServices(story_shell_config_.url(),
&story_shell_services_);
fuchsia::sys::ServiceProviderPtr service_provider;
story_shell_services_.AddBinding(service_provider.NewRequest());
service_list->provider = std::move(service_provider);
preloaded_story_shell_app_ = std::make_unique<AppClient<fuchsia::modular::Lifecycle>>(
session_environment_->GetLauncher(), CloneStruct(story_shell_config_), /*data_origin=*/"",
std::move(service_list));
}
fuchsia::modular::StoryInfo2Ptr StoryProviderImpl::GetCachedStoryInfo(std::string story_id) {
auto it = story_runtime_containers_.find(story_id);
if (it == story_runtime_containers_.end()) {
return nullptr;
}
FX_CHECK(it->second.current_data->has_story_info());
return CloneOptional(it->second.current_data->story_info());
}
// |fuchsia::modular::StoryProvider|
void StoryProviderImpl::GetStoryInfo(std::string story_id, GetStoryInfoCallback callback) {
operation_queue_.Add(std::make_unique<SyncCall>([this, story_id, callback = std::move(callback)] {
auto story_data = session_storage_->GetStoryData(story_id);
if (!story_data || !story_data->has_story_info()) {
callback(nullptr);
return;
}
callback(fidl::MakeOptional(StoryInfo2ToStoryInfo(story_data->story_info())));
}));
}
// |fuchsia::modular::StoryProvider|
void StoryProviderImpl::GetStoryInfo2(std::string story_id, GetStoryInfo2Callback callback) {
operation_queue_.Add(std::make_unique<SyncCall>([this, story_id, callback = std::move(callback)] {
auto story_data = session_storage_->GetStoryData(story_id);
if (!story_data || !story_data->has_story_info()) {
callback(fuchsia::modular::StoryInfo2{});
return;
}
callback(std::move(*story_data->mutable_story_info()));
}));
}
void StoryProviderImpl::AttachOrPresentView(std::string story_id,
fuchsia::ui::views::ViewHolderToken view_holder_token) {
if (std::holds_alternative<std::monostate>(presentation_protocol_)) {
// The presentation protocol has not been chosen yet. Pend the view request so it can be
// attached/presented once the protocol is chosen.
auto pending_call = PendingAttachOrPresentViewCall{
.story_id = std::move(story_id),
.view_holder_token = std::move(view_holder_token),
};
pending_attach_or_present_view_calls.push_back(std::move(pending_call));
} else if (std::holds_alternative<fuchsia::element::GraphicalPresenterPtr>(
presentation_protocol_)) {
PresentView(std::move(story_id), std::move(view_holder_token));
} else if (std::holds_alternative<fuchsia::modular::SessionShellPtr>(presentation_protocol_)) {
AttachView(std::move(story_id), std::move(view_holder_token));
} else {
FX_LOGS(FATAL) << "Unhandled PresentationProtocolPtr alternative: "
<< presentation_protocol_.index();
FX_NOTREACHED();
}
}
void StoryProviderImpl::DetachOrDismissView(std::string story_id, fit::function<void()> done) {
if (std::holds_alternative<std::monostate>(presentation_protocol_)) {
// If the view was dismissed before the presentation protocol has been selected, it was never
// attached/presented, so there's no need to dismiss/detach it.
done();
} else if (std::holds_alternative<fuchsia::element::GraphicalPresenterPtr>(
presentation_protocol_)) {
DismissView(std::move(story_id), std::move(done));
} else if (std::holds_alternative<fuchsia::modular::SessionShellPtr>(presentation_protocol_)) {
DetachView(std::move(story_id), std::move(done));
} else {
FX_LOGS(FATAL) << "Unhandled PresentationProtocolPtr alternative: "
<< presentation_protocol_.index();
FX_NOTREACHED();
}
}
void StoryProviderImpl::AttachView(std::string story_id,
fuchsia::ui::views::ViewHolderToken view_holder_token) {
FX_DCHECK(std::holds_alternative<fuchsia::modular::SessionShellPtr>(presentation_protocol_))
<< "AttachView expects a SessionShellPtr PresentationProtocolPtr";
auto& session_shell = std::get<fuchsia::modular::SessionShellPtr>(presentation_protocol_);
FX_CHECK(session_shell.get())
<< "The session shell component must keep alive a "
"fuchsia.modular.SessionShell service for sessionmgr to function.";
fuchsia::modular::ViewIdentifier view_id;
view_id.story_id = std::move(story_id);
session_shell->AttachView2(std::move(view_id), std::move(view_holder_token));
}
void StoryProviderImpl::DetachView(std::string story_id, fit::function<void()> done) {
FX_DCHECK(std::holds_alternative<fuchsia::modular::SessionShellPtr>(presentation_protocol_))
<< "DetachView expects a SessionShellPtr PresentationProtocolPtr";
auto& session_shell = std::get<fuchsia::modular::SessionShellPtr>(presentation_protocol_);
FX_CHECK(session_shell.get())
<< "The session shell component must keep alive a "
"fuchsia.modular.SessionShell service for sessionmgr to function.";
fuchsia::modular::ViewIdentifier view_id;
view_id.story_id = std::move(story_id);
session_shell->DetachView(std::move(view_id), std::move(done));
}
void StoryProviderImpl::PresentView(std::string story_id,
fuchsia::ui::views::ViewHolderToken view_holder_token) {
FX_DCHECK(std::holds_alternative<fuchsia::element::GraphicalPresenterPtr>(presentation_protocol_))
<< "PresentView expects a GraphicalPresenter PresentationProtocolPtr";
auto& graphical_presenter =
std::get<fuchsia::element::GraphicalPresenterPtr>(presentation_protocol_);
FX_CHECK(graphical_presenter.get())
<< "The session shell component must keep alive a fuchsia.element.GraphicalPresenter service "
"for sessionmgr to function.";
fuchsia::element::ViewSpec view_spec;
view_spec.set_view_holder_token(std::move(view_holder_token));
fuchsia::modular::internal::StoryDataPtr story_data = session_storage_->GetStoryData(story_id);
if (!story_data) {
FX_LOGS(WARNING) << "Not presenting view, story does not exist: " << story_id;
return;
}
if (story_data->story_info().has_annotations()) {
view_spec.set_annotations(
annotations::ToElementAnnotations(story_data->story_info().annotations()));
}
fuchsia::element::ViewControllerPtr view_controller;
view_controller.set_error_handler([weak_this = weak_factory_.GetWeakPtr(),
story_id](zx_status_t status) {
if (!weak_this) {
return;
}
auto finish_dismiss = [weak_this, story_id]() {
for (auto& callback : weak_this->dismiss_callbacks_[story_id]) {
callback();
}
// Remove view controllers from the map
weak_this->view_controllers_.erase(story_id);
weak_this->dismiss_callbacks_.erase(story_id);
weak_this->annotation_controllers_.erase(story_id);
};
// Check if the story is already deleted, stopped, or stopping.
// If it is, DismissView was previously called and the client closed ViewController
// in response, and there's no need to stop the story again.
auto it = weak_this->story_runtime_containers_.find(story_id);
if (it == weak_this->story_runtime_containers_.end() ||
it->second.controller_impl->runtime_state() == fuchsia::modular::StoryState::STOPPED ||
it->second.controller_impl->runtime_state() == fuchsia::modular::StoryState::STOPPING) {
finish_dismiss();
} else {
// Otherwise, the client closed the ViewController while the story was running,
// so treat is as a request to stop the story.
FX_PLOGS(WARNING, status) << "ViewController connection closed, stopping story: " << story_id;
weak_this->operation_queue_.Add(std::make_unique<StopStoryCall>(
story_id, /*skip_notifying_sessionshell=*/false, &weak_this->story_runtime_containers_,
[weak_this, story_id, finish_dismiss = std::move(finish_dismiss)] {
// Delete the story
weak_this->session_storage_->DeleteStory(story_id);
finish_dismiss();
}));
}
});
fuchsia::element::AnnotationControllerPtr annotation_controller;
annotation_controller.set_error_handler(
[weak_this = weak_factory_.GetWeakPtr(), story_id](zx_status_t status) {
if (!weak_this) {
return;
}
// Remove annotation controller from the map
weak_this->annotation_controllers_.erase(story_id);
});
auto annotation_controller_impl =
std::make_unique<AnnotationControllerImpl>(story_id, session_storage_);
annotation_controller_impl->Connect(annotation_controller.NewRequest());
graphical_presenter->PresentView(
std::move(view_spec), std::move(annotation_controller), view_controller.NewRequest(),
[weak_this = weak_factory_.GetWeakPtr(), story_id = std::move(story_id),
view_controller = std::move(view_controller),
annotation_controller_impl = std::move(annotation_controller_impl)](
const fuchsia::element::GraphicalPresenter_PresentView_Result& result) mutable {
if (!weak_this) {
return;
}
if (result.is_err()) {
if (result.err() == fuchsia::element::PresentViewError::INVALID_ARGS) {
FX_LOGS(ERROR) << "Error presenting view: PresentViewError "
<< static_cast<uint32_t>(result.err()) << " (INVALID_ARGS). "
<< "This is a bug!";
} else {
FX_LOGS(WARNING) << "Error presenting view: PresentViewError: "
<< static_cast<uint32_t>(result.err());
}
return;
}
weak_this->view_controllers_[story_id].push_back(std::move(view_controller));
weak_this->annotation_controllers_[story_id] = std::move(annotation_controller_impl);
});
}
void StoryProviderImpl::DismissView(std::string story_id, fit::function<void()> done) {
FX_DCHECK(std::holds_alternative<fuchsia::element::GraphicalPresenterPtr>(presentation_protocol_))
<< "DismissView expects a GraphicalPresenter PresentationProtocolPtr";
auto& graphical_presenter =
std::get<fuchsia::element::GraphicalPresenterPtr>(presentation_protocol_);
FX_CHECK(graphical_presenter.get())
<< "The session shell component keep alive a fuchsia.element.GraphicalPresenter service for "
"sessionmgr to function.";
auto controllers_it = view_controllers_.find(story_id);
if (controllers_it == view_controllers_.end()) {
FX_LOGS(WARNING) << "Not dismissing view, story ViewController does not exist: " << story_id;
dismiss_callbacks_.erase(story_id);
annotation_controllers_.erase(story_id);
done();
return;
}
for (auto it = view_controllers_[story_id].begin(); it != view_controllers_[story_id].end();) {
// Notify the ViewController to Dismiss the view, if it's connected, or erase the
// ViewController if it isn't.
if (auto& view_controller = *it) {
view_controller->Dismiss();
++it;
} else {
it = view_controllers_[story_id].erase(it);
}
}
dismiss_callbacks_[story_id].push_back(std::move(done));
// If all ViewControllers have been deleted because they are disconnected, clean up.
if (controllers_it->second.empty()) {
for (auto& callback : dismiss_callbacks_[story_id]) {
callback();
}
view_controllers_.erase(story_id);
dismiss_callbacks_.erase(story_id);
annotation_controllers_.erase(story_id);
}
}
void StoryProviderImpl::NotifyStoryStateChange(std::string story_id) {
auto it = story_runtime_containers_.find(story_id);
if (it == story_runtime_containers_.end()) {
// If this call arrives while DeleteStory() is in
// progress, the story controller might already be gone
// from here.
return;
}
NotifyStoryWatchers(it->second.current_data.get(), it->second.controller_impl->runtime_state());
}
// |fuchsia::modular::StoryProvider|
void StoryProviderImpl::GetController(
std::string story_id, fidl::InterfaceRequest<fuchsia::modular::StoryController> request) {
operation_queue_.Add(std::make_unique<LoadStoryRuntimeCall>(
this, session_storage_, story_id, session_inspect_node_,
[request = std::move(request)](StoryRuntimeContainer* story_controller_container) mutable {
if (story_controller_container) {
story_controller_container->controller_impl->Connect(std::move(request));
}
}));
}
// |fuchsia::modular::StoryProvider|
void StoryProviderImpl::GetStories(
fidl::InterfaceHandle<fuchsia::modular::StoryProviderWatcher> watcher,
GetStoriesCallback callback) {
operation_queue_.Add(std::make_unique<SyncCall>(
[this, watcher = std::move(watcher), callback = std::move(callback)]() mutable {
auto all_story_data = session_storage_->GetAllStoryData();
std::vector<fuchsia::modular::StoryInfo> result;
for (auto& story_data : all_story_data) {
if (!story_data.has_story_info()) {
continue;
}
result.push_back(StoryInfo2ToStoryInfo(story_data.story_info()));
}
if (watcher) {
watchers_.AddInterfacePtr(watcher.Bind());
}
callback(std::move(result));
}));
}
// |fuchsia::modular::StoryProvider|
void StoryProviderImpl::GetStories2(
fidl::InterfaceHandle<fuchsia::modular::StoryProviderWatcher> watcher,
GetStories2Callback callback) {
operation_queue_.Add(std::make_unique<SyncCall>(
[this, watcher = std::move(watcher), callback = std::move(callback)]() mutable {
auto all_story_data = session_storage_->GetAllStoryData();
std::vector<fuchsia::modular::StoryInfo2> result;
for (auto& story_data : all_story_data) {
if (!story_data.has_story_info()) {
continue;
}
result.push_back(std::move(*story_data.mutable_story_info()));
}
if (watcher) {
watchers_.AddInterfacePtr(watcher.Bind());
}
callback(std::move(result));
}));
}
void StoryProviderImpl::OnStoryStorageUpdated(
std::string story_id, const fuchsia::modular::internal::StoryData& story_data) {
// If we have a StoryRuntimeContainer for this story id, update our cached
// StoryData and get runtime state available from it.
//
// Otherwise, use defaults for an unloaded story and send a request for the
// story to start running (stories should start running by default).
fuchsia::modular::StoryState runtime_state = fuchsia::modular::StoryState::STOPPED;
auto it = story_runtime_containers_.find(story_data.story_info().id());
if (it != story_runtime_containers_.end()) {
auto& container = it->second;
runtime_state = container.controller_impl->runtime_state();
container.current_data = CloneOptional(story_data);
container.ResetInspect();
} else {
fuchsia::modular::StoryControllerPtr story_controller;
GetController(story_id, story_controller.NewRequest());
story_controller->RequestStart();
}
NotifyStoryWatchers(&story_data, runtime_state);
}
void StoryProviderImpl::OnStoryStorageDeleted(std::string story_id) {
operation_queue_.Add(
std::make_unique<StopStoryCall>(story_id, false /* skip_notifying_sessionshell */,
&story_runtime_containers_, [this, story_id] {
for (const auto& i : watchers_.ptrs()) {
(*i)->OnDelete(story_id);
}
}));
}
void StoryProviderImpl::NotifyStoryWatchers(const fuchsia::modular::internal::StoryData* story_data,
const fuchsia::modular::StoryState story_state) {
if (!story_data) {
return;
}
for (const auto& i : watchers_.ptrs()) {
if (!story_data->has_story_info()) {
continue;
}
(*i)->OnChange2(CloneStruct(story_data->story_info()), story_state,
fuchsia::modular::StoryVisibilityState::DEFAULT);
}
}
fuchsia::modular::StoryInfo StoryProviderImpl::StoryInfo2ToStoryInfo(
const fuchsia::modular::StoryInfo2& story_info_2) {
fuchsia::modular::StoryInfo story_info;
story_info.id = story_info_2.id();
story_info.last_focus_time = story_info_2.last_focus_time();
return story_info;
}
void StoryProviderImpl::StoryRuntimeContainer::InitializeInspect(
std::string story_id, inspect::Node* session_inspect_node) {
story_node = std::make_unique<inspect::Node>(session_inspect_node->CreateChild(story_id));
ResetInspect();
}
void StoryProviderImpl::StoryRuntimeContainer::ResetInspect() {
if (current_data->story_info().has_annotations()) {
for (const fuchsia::modular::Annotation& annotation :
current_data->story_info().annotations()) {
std::string value_str = modular::annotations::ToInspect(*annotation.value.get());
std::string key_with_prefix = "annotation: " + annotation.key;
if (annotation_inspect_properties.find(key_with_prefix) !=
annotation_inspect_properties.end()) {
annotation_inspect_properties[key_with_prefix].Set(value_str);
} else {
annotation_inspect_properties.insert(std::pair<const std::string, inspect::StringProperty>(
annotation.key, story_node->CreateString(key_with_prefix, value_str)));
}
}
}
}
} // namespace modular
| 43.122047 | 100 | 0.6929 | [
"object",
"vector"
] |
336aad8052089403d53ddd3c40f4a11462705203 | 5,239 | cpp | C++ | cpp/dependencies/despot/examples/cpp_models/tag/src/noisy_laser_tag/noisy_laser_tag.cpp | modanesh/magic | 2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422 | [
"MIT"
] | 7 | 2021-03-13T22:12:41.000Z | 2022-03-06T03:29:03.000Z | cpp/dependencies/despot/examples/cpp_models/tag/src/noisy_laser_tag/noisy_laser_tag.cpp | modanesh/magic | 2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422 | [
"MIT"
] | 1 | 2021-07-17T01:34:13.000Z | 2021-07-17T04:58:54.000Z | cpp/dependencies/despot/examples/cpp_models/tag/src/noisy_laser_tag/noisy_laser_tag.cpp | modanesh/magic | 2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422 | [
"MIT"
] | 4 | 2021-05-25T07:44:33.000Z | 2022-03-30T08:40:29.000Z | #include "noisy_laser_tag.h"
#include <math.h>
#include <cmath>
using namespace std;
namespace despot {
const OBS_TYPE ONE = 1;
int NoisyLaserTag::NBEAMS = 8;
int NoisyLaserTag::BITS_PER_READING = 7;
/* =============================================================================
* NoisyLaserTag class
* =============================================================================*/
NoisyLaserTag::NoisyLaserTag() :
BaseTag(),
noise_sigma_(2.5),
unit_size_(1.0) {
istringstream iss(RandomMap(7, 11, 8));
BaseTag::Init(iss);
Init();
robot_pos_unknown_ = true;
}
NoisyLaserTag::NoisyLaserTag(string params_file) :
BaseTag(params_file),
noise_sigma_(2.5),
unit_size_(1.0) {
Init();
robot_pos_unknown_ = true;
}
double NoisyLaserTag::LaserRange(const State& state, int dir) const {
Coord rob = floor_.GetCell(rob_[state.state_id]), opp = floor_.GetCell(
opp_[state.state_id]);
int d = 1;
while (true) {
Coord coord = rob + Compass::DIRECTIONS[dir] * d;
if (floor_.GetIndex(coord) == -1 || coord == opp)
break;
d++;
}
int x = Compass::DIRECTIONS[dir].x, y = Compass::DIRECTIONS[dir].y;
return d * sqrt(x * x + y * y);
}
void NoisyLaserTag::Init() {
for (int i = 0; i < NBEAMS; i++)
SetReading(same_loc_obs_, 101, i);
reading_distributions_.resize(NumStates());
for (int s = 0; s < NumStates(); s++) {
reading_distributions_[s].resize(NBEAMS);
for (int d = 0; d < NBEAMS; d++) {
double dist = LaserRange(*states_[s], d);
for (int reading = 0; reading < dist / unit_size_; reading++) {
double min_noise = reading * unit_size_ - dist;
double max_noise = min(dist, (reading + 1) * unit_size_) - dist;
double prob =
2
* (gausscdf(max_noise, 0, noise_sigma_)
- (reading > 0 ?
gausscdf(min_noise, 0, noise_sigma_) : 0 /*min_noise = -infty*/));
reading_distributions_[s][d].push_back(prob);
}
}
}
}
bool NoisyLaserTag::Step(State& state, double random_num, ACT_TYPE action,
double& reward) const {
Random random(random_num);
bool terminal = BaseTag::Step(state, random.NextDouble(), action, reward);
return terminal;
}
bool NoisyLaserTag::Step(State& state, double random_num, ACT_TYPE action, double& reward,
OBS_TYPE& obs) const {
Random random(random_num);
bool terminal = BaseTag::Step(state, random.NextDouble(), action, reward);
if (terminal) {
obs = same_loc_obs_;
} else {
if (rob_[state.state_id] == opp_[state.state_id])
obs = same_loc_obs_;
else {
const vector<vector<double> >& distribution = reading_distributions_[state.state_id];
obs = 0;
for (int dir = 0; dir < NBEAMS; dir++) {
double mass = random.NextDouble();
int reading = 0;
for (; reading < distribution[dir].size(); reading++) {
mass -= distribution[dir][reading];
if (mass < Globals::TINY)
break;
}
SetReading(obs, reading, dir);
}
}
}
return terminal;
}
double NoisyLaserTag::ObsProb(OBS_TYPE obs, const State& state, ACT_TYPE action) const {
if (rob_[state.state_id] == opp_[state.state_id])
return obs == same_loc_obs_;
double prod = 1.0;
for (int dir = 0; dir < NBEAMS; dir++) {
int reading = GetReading(obs, dir);
if (reading >= LaserRange(state, dir) / unit_size_)
return 0;
double prob_mass = reading_distributions_[state.state_id][dir][reading];
prod *= prob_mass;
}
return prod;
}
void NoisyLaserTag::PrintObs(const State& state, OBS_TYPE obs, ostream& out) const {
for (int i = 0; i < NBEAMS; i++)
out << GetReading(obs, i) << " ";
out << endl;
}
int NoisyLaserTag::GetReading(OBS_TYPE obs, OBS_TYPE dir) {
return (obs >> (dir * BITS_PER_READING)) & ((ONE << BITS_PER_READING) - 1);
}
void NoisyLaserTag::SetReading(OBS_TYPE& obs, OBS_TYPE reading, OBS_TYPE dir) {
// Clear bits
obs &= ~(((ONE << BITS_PER_READING) - 1) << (dir * BITS_PER_READING));
// Set bits
obs |= reading << (dir * BITS_PER_READING);
}
int NoisyLaserTag::GetBucket(double noisy) const {
return (int) std::floor(noisy / unit_size_);
}
Belief* NoisyLaserTag::InitialBelief(const State* start, string type) const {
assert(start != NULL);
vector<State*> particles;
int N = floor_.NumCells();
double wgt = 1.0 / N / N;
for (int rob = 0; rob < N; rob++) {
for (int opp = 0; opp < N; opp++) {
TagState* state = static_cast<TagState*>(Allocate(
RobOppIndicesToStateIndex(rob_[start->state_id], opp), wgt));
particles.push_back(state);
}
}
ParticleBelief* belief = new ParticleBelief(particles, this);
belief->state_indexer(this);
return belief;
}
ostream& operator<<(ostream& os, const NoisyLaserTag& lasertag) {
for (int s = 0; s < lasertag.NumStates(); s++) {
os << "State " << s << " " << lasertag.opp_[s] << " "
<< lasertag.rob_[s] << " " << lasertag.floor_.NumCells() << endl;
lasertag.PrintState(*lasertag.states_[s], os);
for (int d = 0; d < lasertag.NBEAMS; d++) {
os << d;
for (int i = 0; i < lasertag.reading_distributions_[s][d].size(); i++)
os << " " << lasertag.reading_distributions_[s][d][i];
os << endl;
}
}
return os;
}
void NoisyLaserTag::Observe(const Belief* belief, ACT_TYPE action,
map<OBS_TYPE, double>& obss) const {
cerr << "Exit: Two many observations!" << endl;
exit(0);
}
} //namespace despot
| 27.286458 | 90 | 0.637526 | [
"vector"
] |
336e392fa84e92b5644d55ef83f60ed5639a6d3c | 12,304 | cc | C++ | util/env_basic_test.cc | RedisLabs/rocksdb | 9b5adea97fa67823905d3996d3f228316075db79 | [
"BSD-3-Clause"
] | 1 | 2016-08-29T00:13:51.000Z | 2016-08-29T00:13:51.000Z | util/env_basic_test.cc | RedisLabs/rocksdb | 9b5adea97fa67823905d3996d3f228316075db79 | [
"BSD-3-Clause"
] | null | null | null | util/env_basic_test.cc | RedisLabs/rocksdb | 9b5adea97fa67823905d3996d3f228316075db79 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <memory>
#include <string>
#include <vector>
#include "rocksdb/env.h"
#include "rocksdb/utilities/env_registry.h"
#include "util/mock_env.h"
#include "util/testharness.h"
namespace rocksdb {
// Normalizes trivial differences across Envs such that these test cases can
// run on all Envs.
class NormalizingEnvWrapper : public EnvWrapper {
public:
explicit NormalizingEnvWrapper(Env* base) : EnvWrapper(base) {}
// Removes . and .. from directory listing
virtual Status GetChildren(const std::string& dir,
std::vector<std::string>* result) override {
Status status = EnvWrapper::GetChildren(dir, result);
if (status.ok()) {
result->erase(std::remove_if(result->begin(), result->end(),
[](const std::string& s) {
return s == "." || s == "..";
}),
result->end());
}
return status;
}
// Removes . and .. from directory listing
virtual Status GetChildrenFileAttributes(
const std::string& dir, std::vector<FileAttributes>* result) override {
Status status = EnvWrapper::GetChildrenFileAttributes(dir, result);
if (status.ok()) {
result->erase(std::remove_if(result->begin(), result->end(),
[](const FileAttributes& fa) {
return fa.name == "." || fa.name == "..";
}),
result->end());
}
return status;
}
};
class EnvBasicTestWithParam : public testing::Test,
public ::testing::WithParamInterface<Env*> {
public:
Env* env_;
const EnvOptions soptions_;
std::string test_dir_;
EnvBasicTestWithParam() : env_(GetParam()) {
test_dir_ = test::TmpDir(env_) + "/env_basic_test";
}
void SetUp() {
env_->CreateDirIfMissing(test_dir_);
}
void TearDown() {
std::vector<std::string> files;
env_->GetChildren(test_dir_, &files);
for (const auto& file : files) {
// don't know whether it's file or directory, try both. The tests must
// only create files or empty directories, so one must succeed, else the
// directory's corrupted.
Status s = env_->DeleteFile(test_dir_ + "/" + file);
if (!s.ok()) {
ASSERT_OK(env_->DeleteDir(test_dir_ + "/" + file));
}
}
}
};
class EnvMoreTestWithParam : public EnvBasicTestWithParam {};
static std::unique_ptr<Env> def_env(new NormalizingEnvWrapper(Env::Default()));
INSTANTIATE_TEST_CASE_P(EnvDefault, EnvBasicTestWithParam,
::testing::Values(def_env.get()));
INSTANTIATE_TEST_CASE_P(EnvDefault, EnvMoreTestWithParam,
::testing::Values(def_env.get()));
static std::unique_ptr<Env> mock_env(new MockEnv(Env::Default()));
INSTANTIATE_TEST_CASE_P(MockEnv, EnvBasicTestWithParam,
::testing::Values(mock_env.get()));
#ifndef ROCKSDB_LITE
static std::unique_ptr<Env> mem_env(NewMemEnv(Env::Default()));
INSTANTIATE_TEST_CASE_P(MemEnv, EnvBasicTestWithParam,
::testing::Values(mem_env.get()));
namespace {
// Returns a vector of 0 or 1 Env*, depending whether an Env is registered for
// TEST_ENV_URI.
//
// The purpose of returning an empty vector (instead of nullptr) is that gtest
// ValuesIn() will skip running tests when given an empty collection.
std::vector<Env*> GetCustomEnvs() {
static Env* custom_env;
static std::unique_ptr<Env> custom_env_guard;
static bool init = false;
if (!init) {
init = true;
const char* uri = getenv("TEST_ENV_URI");
if (uri != nullptr) {
custom_env = NewEnvFromUri(uri, &custom_env_guard);
}
}
std::vector<Env*> res;
if (custom_env != nullptr) {
res.emplace_back(custom_env);
}
return res;
}
} // anonymous namespace
INSTANTIATE_TEST_CASE_P(CustomEnv, EnvBasicTestWithParam,
::testing::ValuesIn(GetCustomEnvs()));
INSTANTIATE_TEST_CASE_P(CustomEnv, EnvMoreTestWithParam,
::testing::ValuesIn(GetCustomEnvs()));
#endif // ROCKSDB_LITE
TEST_P(EnvBasicTestWithParam, Basics) {
uint64_t file_size;
unique_ptr<WritableFile> writable_file;
std::vector<std::string> children;
// Check that the directory is empty.
ASSERT_EQ(Status::NotFound(), env_->FileExists(test_dir_ + "/non_existent"));
ASSERT_TRUE(!env_->GetFileSize(test_dir_ + "/non_existent", &file_size).ok());
ASSERT_OK(env_->GetChildren(test_dir_, &children));
ASSERT_EQ(0U, children.size());
// Create a file.
ASSERT_OK(env_->NewWritableFile(test_dir_ + "/f", &writable_file, soptions_));
ASSERT_OK(writable_file->Close());
writable_file.reset();
// Check that the file exists.
ASSERT_OK(env_->FileExists(test_dir_ + "/f"));
ASSERT_OK(env_->GetFileSize(test_dir_ + "/f", &file_size));
ASSERT_EQ(0U, file_size);
ASSERT_OK(env_->GetChildren(test_dir_, &children));
ASSERT_EQ(1U, children.size());
ASSERT_EQ("f", children[0]);
// Write to the file.
ASSERT_OK(env_->NewWritableFile(test_dir_ + "/f", &writable_file, soptions_));
ASSERT_OK(writable_file->Append("abc"));
ASSERT_OK(writable_file->Close());
writable_file.reset();
// Check for expected size.
ASSERT_OK(env_->GetFileSize(test_dir_ + "/f", &file_size));
ASSERT_EQ(3U, file_size);
// Check that renaming works.
ASSERT_TRUE(!env_->RenameFile(test_dir_ + "/non_existent", "/g").ok());
ASSERT_OK(env_->RenameFile(test_dir_ + "/f", test_dir_ + "/g"));
ASSERT_EQ(Status::NotFound(), env_->FileExists(test_dir_ + "/f"));
ASSERT_OK(env_->FileExists(test_dir_ + "/g"));
ASSERT_OK(env_->GetFileSize(test_dir_ + "/g", &file_size));
ASSERT_EQ(3U, file_size);
// Check that opening non-existent file fails.
unique_ptr<SequentialFile> seq_file;
unique_ptr<RandomAccessFile> rand_file;
ASSERT_TRUE(!env_->NewSequentialFile(test_dir_ + "/non_existent", &seq_file,
soptions_)
.ok());
ASSERT_TRUE(!seq_file);
ASSERT_TRUE(!env_->NewRandomAccessFile(test_dir_ + "/non_existent",
&rand_file, soptions_)
.ok());
ASSERT_TRUE(!rand_file);
// Check that deleting works.
ASSERT_TRUE(!env_->DeleteFile(test_dir_ + "/non_existent").ok());
ASSERT_OK(env_->DeleteFile(test_dir_ + "/g"));
ASSERT_EQ(Status::NotFound(), env_->FileExists(test_dir_ + "/g"));
ASSERT_OK(env_->GetChildren(test_dir_, &children));
ASSERT_EQ(0U, children.size());
}
TEST_P(EnvBasicTestWithParam, ReadWrite) {
unique_ptr<WritableFile> writable_file;
unique_ptr<SequentialFile> seq_file;
unique_ptr<RandomAccessFile> rand_file;
Slice result;
char scratch[100];
ASSERT_OK(env_->NewWritableFile(test_dir_ + "/f", &writable_file, soptions_));
ASSERT_OK(writable_file->Append("hello "));
ASSERT_OK(writable_file->Append("world"));
ASSERT_OK(writable_file->Close());
writable_file.reset();
// Read sequentially.
ASSERT_OK(env_->NewSequentialFile(test_dir_ + "/f", &seq_file, soptions_));
ASSERT_OK(seq_file->Read(5, &result, scratch)); // Read "hello".
ASSERT_EQ(0, result.compare("hello"));
ASSERT_OK(seq_file->Skip(1));
ASSERT_OK(seq_file->Read(1000, &result, scratch)); // Read "world".
ASSERT_EQ(0, result.compare("world"));
ASSERT_OK(seq_file->Read(1000, &result, scratch)); // Try reading past EOF.
ASSERT_EQ(0U, result.size());
ASSERT_OK(seq_file->Skip(100)); // Try to skip past end of file.
ASSERT_OK(seq_file->Read(1000, &result, scratch));
ASSERT_EQ(0U, result.size());
// Random reads.
ASSERT_OK(env_->NewRandomAccessFile(test_dir_ + "/f", &rand_file, soptions_));
ASSERT_OK(rand_file->Read(6, 5, &result, scratch)); // Read "world".
ASSERT_EQ(0, result.compare("world"));
ASSERT_OK(rand_file->Read(0, 5, &result, scratch)); // Read "hello".
ASSERT_EQ(0, result.compare("hello"));
ASSERT_OK(rand_file->Read(10, 100, &result, scratch)); // Read "d".
ASSERT_EQ(0, result.compare("d"));
// Too high offset.
ASSERT_TRUE(rand_file->Read(1000, 5, &result, scratch).ok());
}
TEST_P(EnvBasicTestWithParam, Misc) {
unique_ptr<WritableFile> writable_file;
ASSERT_OK(env_->NewWritableFile(test_dir_ + "/b", &writable_file, soptions_));
// These are no-ops, but we test they return success.
ASSERT_OK(writable_file->Sync());
ASSERT_OK(writable_file->Flush());
ASSERT_OK(writable_file->Close());
writable_file.reset();
}
TEST_P(EnvBasicTestWithParam, LargeWrite) {
const size_t kWriteSize = 300 * 1024;
char* scratch = new char[kWriteSize * 2];
std::string write_data;
for (size_t i = 0; i < kWriteSize; ++i) {
write_data.append(1, static_cast<char>(i));
}
unique_ptr<WritableFile> writable_file;
ASSERT_OK(env_->NewWritableFile(test_dir_ + "/f", &writable_file, soptions_));
ASSERT_OK(writable_file->Append("foo"));
ASSERT_OK(writable_file->Append(write_data));
ASSERT_OK(writable_file->Close());
writable_file.reset();
unique_ptr<SequentialFile> seq_file;
Slice result;
ASSERT_OK(env_->NewSequentialFile(test_dir_ + "/f", &seq_file, soptions_));
ASSERT_OK(seq_file->Read(3, &result, scratch)); // Read "foo".
ASSERT_EQ(0, result.compare("foo"));
size_t read = 0;
std::string read_data;
while (read < kWriteSize) {
ASSERT_OK(seq_file->Read(kWriteSize - read, &result, scratch));
read_data.append(result.data(), result.size());
read += result.size();
}
ASSERT_TRUE(write_data == read_data);
delete [] scratch;
}
TEST_P(EnvMoreTestWithParam, GetModTime) {
ASSERT_OK(env_->CreateDirIfMissing(test_dir_ + "/dir1"));
uint64_t mtime1 = 0x0;
ASSERT_OK(env_->GetFileModificationTime(test_dir_ + "/dir1", &mtime1));
}
TEST_P(EnvMoreTestWithParam, MakeDir) {
ASSERT_OK(env_->CreateDir(test_dir_ + "/j"));
ASSERT_OK(env_->FileExists(test_dir_ + "/j"));
std::vector<std::string> children;
env_->GetChildren(test_dir_, &children);
ASSERT_EQ(1U, children.size());
// fail because file already exists
ASSERT_TRUE(!env_->CreateDir(test_dir_ + "/j").ok());
ASSERT_OK(env_->CreateDirIfMissing(test_dir_ + "/j"));
ASSERT_OK(env_->DeleteDir(test_dir_ + "/j"));
ASSERT_EQ(Status::NotFound(), env_->FileExists(test_dir_ + "/j"));
}
TEST_P(EnvMoreTestWithParam, GetChildren) {
// empty folder returns empty vector
std::vector<std::string> children;
std::vector<Env::FileAttributes> childAttr;
ASSERT_OK(env_->CreateDirIfMissing(test_dir_));
ASSERT_OK(env_->GetChildren(test_dir_, &children));
ASSERT_OK(env_->FileExists(test_dir_));
ASSERT_OK(env_->GetChildrenFileAttributes(test_dir_, &childAttr));
ASSERT_EQ(0U, children.size());
ASSERT_EQ(0U, childAttr.size());
// folder with contents returns relative path to test dir
ASSERT_OK(env_->CreateDirIfMissing(test_dir_ + "/linda"));
ASSERT_OK(env_->CreateDirIfMissing(test_dir_ + "/wanning"));
ASSERT_OK(env_->CreateDirIfMissing(test_dir_ + "/jiang"));
ASSERT_OK(env_->GetChildren(test_dir_, &children));
ASSERT_OK(env_->GetChildrenFileAttributes(test_dir_, &childAttr));
ASSERT_EQ(3U, children.size());
ASSERT_EQ(3U, childAttr.size());
for (auto each : children) {
env_->DeleteDir(test_dir_ + "/" + each);
} // necessary for default POSIX env
// non-exist directory returns IOError
ASSERT_OK(env_->DeleteDir(test_dir_));
ASSERT_TRUE(!env_->FileExists(test_dir_).ok());
ASSERT_TRUE(!env_->GetChildren(test_dir_, &children).ok());
ASSERT_TRUE(!env_->GetChildrenFileAttributes(test_dir_, &childAttr).ok());
// if dir is a file, returns IOError
ASSERT_OK(env_->CreateDir(test_dir_));
unique_ptr<WritableFile> writable_file;
ASSERT_OK(
env_->NewWritableFile(test_dir_ + "/file", &writable_file, soptions_));
ASSERT_OK(writable_file->Close());
writable_file.reset();
ASSERT_TRUE(!env_->GetChildren(test_dir_ + "/file", &children).ok());
ASSERT_EQ(0U, children.size());
}
} // namespace rocksdb
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.976608 | 80 | 0.67344 | [
"vector"
] |
337216a9757ff9cf4892b81367cd636d5c91c94e | 7,419 | hpp | C++ | source/stub/h2_stub.hpp | lingjf/h2un | 7735c2f07f58ea8b92a9e9608c9b45c98c94c670 | [
"Apache-2.0"
] | null | null | null | source/stub/h2_stub.hpp | lingjf/h2un | 7735c2f07f58ea8b92a9e9608c9b45c98c94c670 | [
"Apache-2.0"
] | null | null | null | source/stub/h2_stub.hpp | lingjf/h2un | 7735c2f07f58ea8b92a9e9608c9b45c98c94c670 | [
"Apache-2.0"
] | null | null | null | // STUB( Source , Destination )
// STUB( Function, Signature, Destination )
// STUB( ClassType, Method , Signature, Destination )
// STUB( Object, ClassType, Method , Signature, Destination )
#define H2STUB(...) H2PP_VARIADIC_CALL(__H2STUB_, __VA_ARGS__)
#define __H2STUB_2(Source, Destination) h2::h2_runner::stub(h2::h2_fp<>::A(Source), (void*)Destination, #Source, H2_FILINE)
#define __H2STUB_3(Function, Signature, Destination) h2::h2_runner::stub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(Signature)>::A(H2PP_REMOVE_PARENTHESES_IF(Function)), (void*)(Destination), #Function, H2_FILINE)
#define __H2STUB_4(ClassType, Method, Signature, Destination) h2::h2_stuber<__COUNTER__, H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(Signature)>::I(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(Signature)>::A(&H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)), #ClassType "::" #Method, H2_FILINE) = Destination
#define __H2STUB_5(Object, ClassType, Method, Signature, Destination) h2::h2_stuber<__COUNTER__, H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(Signature)>::I(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(Signature)>::B(h2::h2_pointer_if(Object), &H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)), #ClassType "::" #Method, H2_FILINE) = Destination
#define H2UNSTUB(...) H2PP_VARIADIC_CALL(__H2UNSTUB_, __VA_ARGS__)
#define __H2UNSTUB_1(Source) h2::h2_runner::unstub(h2::h2_fp<>::A(Source))
#define __H2UNSTUB_2(Function, Signature) h2::h2_runner::unstub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(Signature)>::A(H2PP_REMOVE_PARENTHESES_IF(Function)))
#define __H2UNSTUB_3(ClassType, Method, Signature) h2::h2_runner::unstub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(Signature)>::A(&H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)))
#define __H2UNSTUB_4(Object, ClassType, Method, Signature) h2::h2_runner::unstub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(Signature)>::B(h2::h2_pointer_if(Object), &H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)))
// STUBS( Function, ReturnType, ArgumentTypes ) { }
// STUBS( ClassType, Method , ReturnType, ArgumentTypes ) { }
// STUBS( Object, ClassType, Method , ReturnType, ArgumentTypes ) { }
#define H2UNSTUBS(...) H2PP_VARIADIC_CALL(__H2UNSTUBS_, __VA_ARGS__)
#define __H2UNSTUBS_1(Source) h2::h2_runner::unstub(h2::h2_fp<>::A(Source))
#define __H2UNSTUBS_3(Function, ReturnType, ArgumentTypes) h2::h2_runner::unstub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::A(H2PP_REMOVE_PARENTHESES_IF(Function)))
#define __H2UNSTUBS_4(ClassType, Method, ReturnType, ArgumentTypes) h2::h2_runner::unstub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::A(&H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)))
#define __H2UNSTUBS_5(Object, ClassType, Method, ReturnType, ArgumentTypes) h2::h2_runner::unstub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::B(h2::h2_pointer_if(Object), &H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)))
#define H2STUBS(...) H2PP_VARIADIC_CALL(__H2STUBS_, __VA_ARGS__)
#define __H2STUBS_3(Function, ReturnType, ArgumentTypes) ___H2STUBS_3(Function, ReturnType, ArgumentTypes, H2PP_UNIQUE(t_stub3))
#define __H2STUBS_4(ClassType, Method, ReturnType, ArgumentTypes) H2PP_CAT(__H2STUBS_4_, H2PP_IS_EMPTY ArgumentTypes)(ClassType, Method, ReturnType, ArgumentTypes)
#define __H2STUBS_4_0(ClassType, Method, ReturnType, ArgumentTypes) h2::h2_stuber<__COUNTER__, H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::I(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::A(&H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)), #ClassType "::" #Method, H2_FILINE) = [](H2PP_REMOVE_PARENTHESES_IF(ClassType) * This, H2PP_REMOVE_PARENTHESES(ArgumentTypes)) -> H2PP_REMOVE_PARENTHESES_IF(ReturnType)
#define __H2STUBS_4_1(ClassType, Method, ReturnType, ArgumentTypes) h2::h2_stuber<__COUNTER__, H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::I(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::A(&H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)), #ClassType "::" #Method, H2_FILINE) = [](H2PP_REMOVE_PARENTHESES_IF(ClassType) * This) -> H2PP_REMOVE_PARENTHESES_IF(ReturnType)
#define __H2STUBS_5(Object, ClassType, Method, ReturnType, ArgumentTypes) H2PP_CAT(__H2STUBS_5_, H2PP_IS_EMPTY ArgumentTypes)(Object, ClassType, Method, ReturnType, ArgumentTypes)
#define __H2STUBS_5_0(Object, ClassType, Method, ReturnType, ArgumentTypes) h2::h2_stuber<__COUNTER__, H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::I(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::B(h2::h2_pointer_if(Object), &H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)), #ClassType "::" #Method, H2_FILINE) = [](H2PP_REMOVE_PARENTHESES_IF(ClassType) * This, H2PP_REMOVE_PARENTHESES(ArgumentTypes)) -> H2PP_REMOVE_PARENTHESES_IF(ReturnType)
#define __H2STUBS_5_1(Object, ClassType, Method, ReturnType, ArgumentTypes) h2::h2_stuber<__COUNTER__, H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::I(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ClassType), H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::B(h2::h2_pointer_if(Object), &H2PP_REMOVE_PARENTHESES_IF(ClassType)::H2PP_REMOVE_PARENTHESES_IF(Method)), #ClassType "::" #Method, H2_FILINE) = [](H2PP_REMOVE_PARENTHESES_IF(ClassType) * This) -> H2PP_REMOVE_PARENTHESES_IF(ReturnType)
#define ___H2STUBS_3(Function, ReturnType, ArgumentTypes, Q) \
struct { \
void operator=(ReturnType(*dstfp) ArgumentTypes) \
{ \
h2::h2_runner::stub(h2::h2_fp<H2PP_REMOVE_PARENTHESES_IF(ReturnType) ArgumentTypes>::A(H2PP_REMOVE_PARENTHESES_IF(Function)), (void*)(dstfp), #Function, H2_FILINE); \
} \
} Q; \
Q = [] ArgumentTypes -> ReturnType /* captureless lambda implicit cast to function pointer */
| 172.534884 | 577 | 0.707643 | [
"object"
] |
33722a371dfedaf128dc0b650fac4765576a543f | 68,576 | cpp | C++ | src/vizdoom/src/g_game.cpp | johny-c/ViZDoom | 6fe0d2470872adbfa5d18c53c7704e6ff103cacc | [
"MIT"
] | 1,102 | 2017-02-02T15:39:57.000Z | 2022-03-23T09:43:29.000Z | src/vizdoom/src/g_game.cpp | johny-c/ViZDoom | 6fe0d2470872adbfa5d18c53c7704e6ff103cacc | [
"MIT"
] | 339 | 2017-02-17T09:55:38.000Z | 2022-03-29T11:44:01.000Z | src/vizdoom/src/g_game.cpp | johny-c/ViZDoom | 6fe0d2470872adbfa5d18c53c7704e6ff103cacc | [
"MIT"
] | 331 | 2017-02-02T15:34:42.000Z | 2022-03-23T02:42:24.000Z | // Emacs style mode select -*- C++ -*-
//-----------------------------------------------------------------------------
//
// $Id:$
//
// Copyright (C) 1993-1996 by id Software, Inc.
//
// This source is available for distribution and/or modification
// only under the terms of the DOOM Source Code License as
// published by id Software. All rights reserved.
//
// The source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// FITNESS FOR A PARTICULAR PURPOSE. See the DOOM Source Code License
// for more details.
//
// $Log:$
//
// DESCRIPTION: none
//
//-----------------------------------------------------------------------------
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <time.h>
#ifdef __APPLE__
#include <CoreServices/CoreServices.h>
#endif
#include "templates.h"
#include "version.h"
#include "doomdef.h"
#include "doomstat.h"
#include "d_protocol.h"
#include "d_netinf.h"
#include "intermission/intermission.h"
#include "m_argv.h"
#include "m_misc.h"
#include "menu/menu.h"
#include "m_random.h"
#include "m_crc32.h"
#include "i_system.h"
#include "i_input.h"
#include "p_saveg.h"
#include "p_tick.h"
#include "d_main.h"
#include "wi_stuff.h"
#include "hu_stuff.h"
#include "st_stuff.h"
#include "am_map.h"
#include "c_console.h"
#include "c_cvars.h"
#include "c_bind.h"
#include "c_dispatch.h"
#include "v_video.h"
#include "w_wad.h"
#include "p_local.h"
#include "s_sound.h"
#include "gstrings.h"
#include "r_sky.h"
#include "g_game.h"
#include "g_level.h"
#include "b_bot.h" //Added by MC:
#include "sbar.h"
#include "m_swap.h"
#include "m_png.h"
#include "gi.h"
#include "a_keys.h"
#include "a_artifacts.h"
#include "r_data/r_translate.h"
#include "cmdlib.h"
#include "d_net.h"
#include "d_event.h"
#include "p_acs.h"
#include "p_effect.h"
#include "m_joy.h"
#include "farchive.h"
#include "r_renderer.h"
#include "r_data/colormaps.h"
#include <zlib.h>
#include "g_hub.h"
//VIZDOOM_CODE
#include "viz_main.h"
#include "viz_input.h"
#include "viz_defines.h"
EXTERN_CVAR (Bool, viz_controlled)
EXTERN_CVAR (Bool, viz_async)
EXTERN_CVAR (Bool, viz_allow_input)
static FRandom pr_dmspawn ("DMSpawn");
static FRandom pr_pspawn ("PlayerSpawn");
const int SAVEPICWIDTH = 216;
const int SAVEPICHEIGHT = 162;
bool G_CheckDemoStatus (void);
void G_ReadDemoTiccmd (ticcmd_t *cmd, int player);
void G_WriteDemoTiccmd (ticcmd_t *cmd, int player, int buf);
void G_PlayerReborn (int player);
void G_DoNewGame (void);
void G_DoLoadGame (void);
void G_DoPlayDemo (void);
void G_DoCompleted (void);
void G_DoVictory (void);
void G_DoWorldDone (void);
void G_DoSaveGame (bool okForQuicksave, FString filename, const char *description);
void G_DoAutoSave ();
void STAT_Write(FILE *file);
void STAT_Read(PNGHandle *png);
FIntCVar gameskill ("skill", 2, CVAR_SERVERINFO|CVAR_LATCH);
CVAR (Int, deathmatch, 0, CVAR_SERVERINFO|CVAR_LATCH);
CVAR (Bool, chasedemo, false, 0);
CVAR (Bool, storesavepic, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
CVAR (Bool, longsavemessages, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
CVAR (String, save_dir, "", CVAR_ARCHIVE|CVAR_GLOBALCONFIG);
CVAR (Bool, cl_waitforsave, true, CVAR_ARCHIVE | CVAR_GLOBALCONFIG);
EXTERN_CVAR (Float, con_midtime);
//==========================================================================
//
// CVAR displaynametags
//
// Selects whether to display name tags or not when changing weapons/items
//
//==========================================================================
CUSTOM_CVAR (Int, displaynametags, 0, CVAR_ARCHIVE)
{
if (self < 0 || self > 3)
{
self = 0;
}
}
CVAR(Int, nametagcolor, CR_GOLD, CVAR_ARCHIVE)
gameaction_t gameaction;
gamestate_t gamestate = GS_STARTUP;
int paused;
bool pauseext;
bool sendpause; // send a pause event next tic
bool sendsave; // send a save event next tic
bool sendturn180; // [RH] send a 180 degree turn next tic
bool usergame; // ok to save / end game
bool insave; // Game is saving - used to block exit commands
bool timingdemo; // if true, exit with report on completion
bool nodrawers; // for comparative timing purposes
bool noblit; // for comparative timing purposes
bool viewactive;
bool netgame; // only true if packets are broadcast
bool multiplayer;
player_t players[MAXPLAYERS];
bool playeringame[MAXPLAYERS];
int consoleplayer; // player taking events
int gametic;
CVAR(Bool, demo_compress, true, CVAR_ARCHIVE|CVAR_GLOBALCONFIG);
FString newdemoname;
FString newdemomap;
FString demoname;
bool demorecording;
bool demoplayback;
bool demonew; // [RH] Only used around G_InitNew for demos
int demover;
BYTE* demobuffer;
BYTE* demo_p;
BYTE* democompspot;
BYTE* demobodyspot;
size_t maxdemosize;
BYTE* zdemformend; // end of FORM ZDEM chunk
BYTE* zdembodyend; // end of ZDEM BODY chunk
bool singledemo; // quit after playing a demo from cmdline
bool precache = true; // if true, load all graphics at start
wbstartstruct_t wminfo; // parms for world map / intermission
short consistancy[MAXPLAYERS][BACKUPTICS];
#define MAXPLMOVE (forwardmove[1])
#define TURBOTHRESHOLD 12800
float normforwardmove[2] = {0x19, 0x32}; // [RH] For setting turbo from console
float normsidemove[2] = {0x18, 0x28}; // [RH] Ditto
fixed_t forwardmove[2], sidemove[2];
fixed_t angleturn[4] = {640, 1280, 320, 320}; // + slow turn
fixed_t flyspeed[2] = {1*256, 3*256};
int lookspeed[2] = {450, 512};
#define SLOWTURNTICS 6
CVAR (Bool, cl_run, false, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) // Always run?
CVAR (Bool, invertmouse, false, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) // Invert mouse look down/up?
CVAR (Bool, freelook, false, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) // Always mlook?
CVAR (Bool, lookstrafe, false, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) // Always strafe with mouse?
CVAR (Float, m_pitch, 1.f, CVAR_GLOBALCONFIG|CVAR_ARCHIVE) // Mouse speeds
CVAR (Float, m_yaw, 1.f, CVAR_GLOBALCONFIG|CVAR_ARCHIVE)
CVAR (Float, m_forward, 1.f, CVAR_GLOBALCONFIG|CVAR_ARCHIVE)
CVAR (Float, m_side, 2.f, CVAR_GLOBALCONFIG|CVAR_ARCHIVE)
int turnheld; // for accelerative turning
// mouse values are used once
int mousex;
int mousey;
FString savegamefile;
char savedescription[SAVESTRINGSIZE];
// [RH] Name of screenshot file to generate (usually NULL)
FString shotfile;
AActor* bodyque[BODYQUESIZE];
int bodyqueslot;
void R_ExecuteSetViewSize (void);
FString savename;
FString BackupSaveName;
bool SendLand;
const AInventory *SendItemUse, *SendItemDrop;
EXTERN_CVAR (Int, team)
CVAR (Bool, teamplay, false, CVAR_SERVERINFO)
// [RH] Allow turbo setting anytime during game
CUSTOM_CVAR (Float, turbo, 100.f, 0)
{
if (self < 10.f)
{
self = 10.f;
}
else if (self > 255.f)
{
self = 255.f;
}
else
{
double scale = self * 0.01;
forwardmove[0] = (int)(normforwardmove[0]*scale);
forwardmove[1] = (int)(normforwardmove[1]*scale);
sidemove[0] = (int)(normsidemove[0]*scale);
sidemove[1] = (int)(normsidemove[1]*scale);
}
}
CCMD (turnspeeds)
{
if (argv.argc() == 1)
{
Printf ("Current turn speeds: %d %d %d %d\n", angleturn[0],
angleturn[1], angleturn[2], angleturn[3]);
}
else
{
int i;
for (i = 1; i <= 4 && i < argv.argc(); ++i)
{
angleturn[i-1] = atoi (argv[i]);
}
if (i <= 2)
{
angleturn[1] = angleturn[0] * 2;
}
if (i <= 3)
{
angleturn[2] = angleturn[0] / 2;
}
if (i <= 4)
{
angleturn[3] = angleturn[2];
}
}
}
CCMD (slot)
{
if (argv.argc() > 1)
{
int slot = atoi (argv[1]);
if (slot < NUM_WEAPON_SLOTS)
{
SendItemUse = players[consoleplayer].weapons.Slots[slot].PickWeapon (&players[consoleplayer],
!(dmflags2 & DF2_DONTCHECKAMMO));
}
}
}
CCMD (centerview)
{
Net_WriteByte (DEM_CENTERVIEW);
}
CCMD(crouch)
{
Net_WriteByte(DEM_CROUCH);
}
CCMD (land)
{
SendLand = true;
}
CCMD (pause)
{
sendpause = true;
}
CCMD (turn180)
{
sendturn180 = true;
}
CCMD (weapnext)
{
SendItemUse = players[consoleplayer].weapons.PickNextWeapon (&players[consoleplayer]);
// [BC] Option to display the name of the weapon being cycled to.
if ((displaynametags & 2) && StatusBar && SmallFont && SendItemUse)
{
StatusBar->AttachMessage(new DHUDMessageFadeOut(SmallFont, SendItemUse->GetTag(),
1.5f, 0.90f, 0, 0, (EColorRange)*nametagcolor, 2.f, 0.35f), MAKE_ID( 'W', 'E', 'P', 'N' ));
}
}
CCMD (weapprev)
{
SendItemUse = players[consoleplayer].weapons.PickPrevWeapon (&players[consoleplayer]);
// [BC] Option to display the name of the weapon being cycled to.
if ((displaynametags & 2) && StatusBar && SmallFont && SendItemUse)
{
StatusBar->AttachMessage(new DHUDMessageFadeOut(SmallFont, SendItemUse->GetTag(),
1.5f, 0.90f, 0, 0, (EColorRange)*nametagcolor, 2.f, 0.35f), MAKE_ID( 'W', 'E', 'P', 'N' ));
}
}
CCMD (invnext)
{
AInventory *next;
if (who == NULL)
return;
if (who->InvSel != NULL)
{
if ((next = who->InvSel->NextInv()) != NULL)
{
who->InvSel = next;
}
else
{
// Select the first item in the inventory
if (!(who->Inventory->ItemFlags & IF_INVBAR))
{
who->InvSel = who->Inventory->NextInv();
}
else
{
who->InvSel = who->Inventory;
}
}
if ((displaynametags & 1) && StatusBar && SmallFont && who->InvSel)
StatusBar->AttachMessage (new DHUDMessageFadeOut (SmallFont, who->InvSel->GetTag(),
1.5f, 0.80f, 0, 0, (EColorRange)*nametagcolor, 2.f, 0.35f), MAKE_ID('S','I','N','V'));
}
who->player->inventorytics = 5*TICRATE;
}
CCMD (invprev)
{
AInventory *item, *newitem;
if (who == NULL)
return;
if (who->InvSel != NULL)
{
if ((item = who->InvSel->PrevInv()) != NULL)
{
who->InvSel = item;
}
else
{
// Select the last item in the inventory
item = who->InvSel;
while ((newitem = item->NextInv()) != NULL)
{
item = newitem;
}
who->InvSel = item;
}
if ((displaynametags & 1) && StatusBar && SmallFont && who->InvSel)
StatusBar->AttachMessage (new DHUDMessageFadeOut (SmallFont, who->InvSel->GetTag(),
1.5f, 0.80f, 0, 0, (EColorRange)*nametagcolor, 2.f, 0.35f), MAKE_ID('S','I','N','V'));
}
who->player->inventorytics = 5*TICRATE;
}
CCMD (invuseall)
{
SendItemUse = (const AInventory *)1;
}
CCMD (invuse)
{
if (players[consoleplayer].inventorytics == 0)
{
if (players[consoleplayer].mo) SendItemUse = players[consoleplayer].mo->InvSel;
}
players[consoleplayer].inventorytics = 0;
}
CCMD(invquery)
{
AInventory *inv = players[consoleplayer].mo->InvSel;
if (inv != NULL)
{
Printf(PRINT_HIGH, "%s (%dx)\n", inv->GetTag(), inv->Amount);
}
}
CCMD (use)
{
if (argv.argc() > 1 && who != NULL)
{
SendItemUse = who->FindInventory (PClass::FindClass (argv[1]));
}
}
CCMD (invdrop)
{
if (players[consoleplayer].mo) SendItemDrop = players[consoleplayer].mo->InvSel;
}
CCMD (weapdrop)
{
SendItemDrop = players[consoleplayer].ReadyWeapon;
}
CCMD (drop)
{
if (argv.argc() > 1 && who != NULL)
{
SendItemDrop = who->FindInventory (PClass::FindClass (argv[1]));
}
}
const PClass *GetFlechetteType(AActor *other);
CCMD (useflechette)
{ // Select from one of arti_poisonbag1-3, whichever the player has
static const ENamedName bagnames[3] =
{
NAME_ArtiPoisonBag1,
NAME_ArtiPoisonBag2,
NAME_ArtiPoisonBag3
};
if (who == NULL)
return;
const PClass *type = GetFlechetteType(who);
if (type != NULL)
{
AInventory *item;
if ( (item = who->FindInventory (type) ))
{
SendItemUse = item;
return;
}
}
// The default flechette could not be found. Try all 3 types then.
for (int j = 0; j < 3; ++j)
{
AInventory *item;
if ( (item = who->FindInventory (bagnames[j])) )
{
SendItemUse = item;
break;
}
}
}
CCMD (select)
{
if (argv.argc() > 1)
{
AInventory *item = who->FindInventory (PClass::FindClass (argv[1]));
if (item != NULL)
{
who->InvSel = item;
}
}
who->player->inventorytics = 5*TICRATE;
}
static inline int joyint(double val)
{
if (val >= 0)
{
return int(ceil(val));
}
else
{
return int(floor(val));
}
}
//
// G_BuildTiccmd
// Builds a ticcmd from all of the available inputs
// or reads it from the demo buffer.
// If recording a demo, write it out
//
//VIZDOOM_CODE
void G_BuildTiccmd (ticcmd_t *cmd)
{
int strafe;
int speed;
int forward;
int side;
int fly;
ticcmd_t *base;
base = I_BaseTiccmd (); // empty, or external driver
*cmd = *base;
cmd->consistancy = consistancy[consoleplayer][(maketic/ticdup)%BACKUPTICS];
strafe = Button_Strafe.bDown;
speed = Button_Speed.bDown ^ (int)cl_run;
//VIZDOOM_CODE
forward = LocalForward;
side = LocalSide;
fly = LocalFly;
LocalForward = LocalSide = LocalFly = 0;
// [RH] only use two stage accelerative turning on the keyboard
// and not the joystick, since we treat the joystick as
// the analog device it is.
if (Button_Left.bDown || Button_Right.bDown)
turnheld += ticdup;
else
turnheld = 0;
// let movement keys cancel each other out
if (strafe)
{
if (Button_Right.bDown)
side += sidemove[speed];
if (Button_Left.bDown)
side -= sidemove[speed];
}
else
{
int tspeed = speed;
if (turnheld < SLOWTURNTICS)
tspeed += 2; // slow turn
if (Button_Right.bDown)
{
G_AddViewAngle (angleturn[tspeed]);
LocalKeyboardTurner = true;
}
if (Button_Left.bDown)
{
G_AddViewAngle (-angleturn[tspeed]);
LocalKeyboardTurner = true;
}
}
if (Button_LookUp.bDown)
{
G_AddViewPitch (lookspeed[speed]);
LocalKeyboardTurner = true;
}
if (Button_LookDown.bDown)
{
G_AddViewPitch (-lookspeed[speed]);
LocalKeyboardTurner = true;
}
if (Button_MoveUp.bDown)
fly += flyspeed[speed];
if (Button_MoveDown.bDown)
fly -= flyspeed[speed];
if (Button_Klook.bDown)
{
if (Button_Forward.bDown)
G_AddViewPitch (lookspeed[speed]);
if (Button_Back.bDown)
G_AddViewPitch (-lookspeed[speed]);
}
else
{
if (Button_Forward.bDown)
forward += forwardmove[speed];
if (Button_Back.bDown)
forward -= forwardmove[speed];
}
if (Button_MoveRight.bDown)
side += sidemove[speed];
if (Button_MoveLeft.bDown)
side -= sidemove[speed];
// buttons
if (Button_Attack.bDown) cmd->ucmd.buttons |= BT_ATTACK;
if (Button_AltAttack.bDown) cmd->ucmd.buttons |= BT_ALTATTACK;
if (Button_Use.bDown) cmd->ucmd.buttons |= BT_USE;
if (Button_Jump.bDown) cmd->ucmd.buttons |= BT_JUMP;
if (Button_Crouch.bDown) cmd->ucmd.buttons |= BT_CROUCH;
if (Button_Zoom.bDown) cmd->ucmd.buttons |= BT_ZOOM;
if (Button_Reload.bDown) cmd->ucmd.buttons |= BT_RELOAD;
if (Button_User1.bDown) cmd->ucmd.buttons |= BT_USER1;
if (Button_User2.bDown) cmd->ucmd.buttons |= BT_USER2;
if (Button_User3.bDown) cmd->ucmd.buttons |= BT_USER3;
if (Button_User4.bDown) cmd->ucmd.buttons |= BT_USER4;
if (Button_Speed.bDown) cmd->ucmd.buttons |= BT_SPEED;
if (Button_Strafe.bDown) cmd->ucmd.buttons |= BT_STRAFE;
if (Button_MoveRight.bDown) cmd->ucmd.buttons |= BT_MOVERIGHT;
if (Button_MoveLeft.bDown) cmd->ucmd.buttons |= BT_MOVELEFT;
if (Button_LookDown.bDown) cmd->ucmd.buttons |= BT_LOOKDOWN;
if (Button_LookUp.bDown) cmd->ucmd.buttons |= BT_LOOKUP;
if (Button_Back.bDown) cmd->ucmd.buttons |= BT_BACK;
if (Button_Forward.bDown) cmd->ucmd.buttons |= BT_FORWARD;
if (Button_Right.bDown) cmd->ucmd.buttons |= BT_RIGHT;
if (Button_Left.bDown) cmd->ucmd.buttons |= BT_LEFT;
if (Button_MoveDown.bDown) cmd->ucmd.buttons |= BT_MOVEDOWN;
if (Button_MoveUp.bDown) cmd->ucmd.buttons |= BT_MOVEUP;
if (Button_ShowScores.bDown) cmd->ucmd.buttons |= BT_SHOWSCORES;
// Handle joysticks/game controllers.
float joyaxes[NUM_JOYAXIS];
I_GetAxes(joyaxes);
// Remap some axes depending on button state.
if (Button_Strafe.bDown || (Button_Mlook.bDown && lookstrafe))
{
joyaxes[JOYAXIS_Side] = joyaxes[JOYAXIS_Yaw];
joyaxes[JOYAXIS_Yaw] = 0;
}
if (Button_Mlook.bDown)
{
joyaxes[JOYAXIS_Pitch] = joyaxes[JOYAXIS_Forward];
joyaxes[JOYAXIS_Forward] = 0;
}
if (joyaxes[JOYAXIS_Pitch] != 0)
{
G_AddViewPitch(joyint(joyaxes[JOYAXIS_Pitch] * 2048));
LocalKeyboardTurner = true;
}
if (joyaxes[JOYAXIS_Yaw] != 0)
{
G_AddViewAngle(joyint(-1280 * joyaxes[JOYAXIS_Yaw]));
LocalKeyboardTurner = true;
}
side -= joyint(sidemove[speed] * joyaxes[JOYAXIS_Side]);
forward += joyint(joyaxes[JOYAXIS_Forward] * forwardmove[speed]);
fly += joyint(joyaxes[JOYAXIS_Up] * 2048);
// Handle mice.
//VIZDOOM_CODE
if (!Button_Mlook.bDown && !freelook) {
int value = (int) ((float) mousey * m_forward);
if(!*viz_controlled) forward += value;
else{
if(*viz_allow_input){
value = VIZ_AxisFilter(VIZ_BT_FORWARD_BACKWARD_AXIS, value);
forward += value;
}
}
}
if (strafe || lookstrafe) {
int value = (int) ((float) mousex * m_side);
if(!*viz_controlled) side += value;
else{
if(*viz_allow_input){
value = VIZ_AxisFilter(VIZ_BT_LEFT_RIGHT_AXIS, value);
side += value;
}
}
}
mousex = mousey = 0;
cmd->ucmd.pitch = LocalViewPitch >> 16;
if (SendLand) {
SendLand = false;
fly = -32768;
}
// Build command.
if (forward > MAXPLMOVE)
forward = MAXPLMOVE;
else if (forward < -MAXPLMOVE)
forward = -MAXPLMOVE;
if (side > MAXPLMOVE)
side = MAXPLMOVE;
else if (side < -MAXPLMOVE)
side = -MAXPLMOVE;
cmd->ucmd.forwardmove += forward;
cmd->ucmd.sidemove += side;
cmd->ucmd.yaw = LocalViewAngle >> 16;
cmd->ucmd.upmove = fly;
LocalViewAngle = 0;
LocalViewPitch = 0;
// special buttons
if (sendturn180)
{
sendturn180 = false;
cmd->ucmd.buttons |= BT_TURN180;
}
if (sendpause)
{
sendpause = false;
Net_WriteByte (DEM_PAUSE);
}
if (sendsave)
{
sendsave = false;
Net_WriteByte (DEM_SAVEGAME);
Net_WriteString (savegamefile);
Net_WriteString (savedescription);
savegamefile = "";
}
if (SendItemUse == (const AInventory *)1)
{
Net_WriteByte (DEM_INVUSEALL);
SendItemUse = NULL;
}
else if (SendItemUse != NULL)
{
Net_WriteByte(DEM_INVUSE);
Net_WriteLong(SendItemUse->InventoryID);
SendItemUse = NULL;
}
if (SendItemDrop != NULL)
{
Net_WriteByte (DEM_INVDROP);
Net_WriteLong (SendItemDrop->InventoryID);
SendItemDrop = NULL;
}
cmd->ucmd.forwardmove <<= 8;
cmd->ucmd.sidemove <<= 8;
//VIZDOOM_CODE
//if(*viz_controlled) VIZ_ReadCmdState(cmd);
}
//[Graf Zahl] This really helps if the mouse update rate can't be increased!
CVAR (Bool, smooth_mouse, false, CVAR_GLOBALCONFIG|CVAR_ARCHIVE)
//VIZDOOM_CODE
void G_AddViewPitch (int look)
{
if (gamestate == GS_TITLELEVEL)
{
return;
}
look <<= 16;
if (players[consoleplayer].playerstate != PST_DEAD && // No adjustment while dead.
players[consoleplayer].ReadyWeapon != NULL && // No adjustment if no weapon.
players[consoleplayer].ReadyWeapon->FOVScale > 0) // No adjustment if it is non-positive.
{
look = int(look * players[consoleplayer].ReadyWeapon->FOVScale);
}
if (!level.IsFreelookAllowed())
{
LocalViewPitch = 0;
}
else if (look > 0)
{
// Avoid overflowing
if (LocalViewPitch > INT_MAX - look)
{
LocalViewPitch = 0x78000000;
}
else
{
LocalViewPitch = MIN(LocalViewPitch + look, 0x78000000);
}
}
else if (look < 0)
{
// Avoid overflowing
if (LocalViewPitch < INT_MIN - look)
{
LocalViewPitch = -0x78000000;
}
else
{
LocalViewPitch = MAX(LocalViewPitch + look, -0x78000000);
}
}
if (look != 0)
{
LocalKeyboardTurner = smooth_mouse;
}
}
void G_AddViewAngle (int yaw)
{
if (gamestate == GS_TITLELEVEL)
{
return;
}
yaw <<= 16;
if (players[consoleplayer].playerstate != PST_DEAD && // No adjustment while dead.
players[consoleplayer].ReadyWeapon != NULL && // No adjustment if no weapon.
players[consoleplayer].ReadyWeapon->FOVScale > 0) // No adjustment if it is non-positive.
{
yaw = int(yaw * players[consoleplayer].ReadyWeapon->FOVScale);
}
LocalViewAngle -= yaw;
if (yaw != 0)
{
LocalKeyboardTurner = smooth_mouse;
}
}
CVAR (Bool, bot_allowspy, false, 0)
enum {
SPY_CANCEL = 0,
SPY_NEXT,
SPY_PREV,
};
// [RH] Spy mode has been separated into two console commands.
// One goes forward; the other goes backward.
static void ChangeSpy (int changespy)
{
// If you're not in a level, then you can't spy.
if (gamestate != GS_LEVEL)
{
return;
}
// If not viewing through a player, return your eyes to your own head.
if (players[consoleplayer].camera->player == NULL)
{
// When watching demos, you will just have to wait until your player
// has done this for you, since it could desync otherwise.
if (!demoplayback)
{
Net_WriteByte(DEM_REVERTCAMERA);
}
return;
}
// We may not be allowed to spy on anyone.
if (dmflags2 & DF2_DISALLOW_SPYING)
return;
// Otherwise, cycle to the next player.
bool checkTeam = !demoplayback && deathmatch;
int pnum = consoleplayer;
if (changespy != SPY_CANCEL)
{
player_t *player = players[consoleplayer].camera->player;
// only use the camera as starting index if it's a valid player.
if (player != NULL) pnum = int(players[consoleplayer].camera->player - players);
int step = (changespy == SPY_NEXT) ? 1 : -1;
do
{
pnum += step;
pnum &= MAXPLAYERS-1;
if (playeringame[pnum] &&
(!checkTeam || players[pnum].mo->IsTeammate (players[consoleplayer].mo) ||
(bot_allowspy && players[pnum].Bot != NULL)))
{
break;
}
} while (pnum != consoleplayer);
}
players[consoleplayer].camera = players[pnum].mo;
S_UpdateSounds(players[consoleplayer].camera);
StatusBar->AttachToPlayer (&players[pnum]);
if (demoplayback || multiplayer)
{
StatusBar->ShowPlayerName ();
}
}
CCMD (spynext)
{
// allow spy mode changes even during the demo
ChangeSpy (SPY_NEXT);
}
CCMD (spyprev)
{
// allow spy mode changes even during the demo
ChangeSpy (SPY_PREV);
}
CCMD (spycancel)
{
// allow spy mode changes even during the demo
ChangeSpy (SPY_CANCEL);
}
//
// G_Responder
// Get info needed to make ticcmd_ts for the players.
//
bool G_Responder (event_t *ev)
{
// any other key pops up menu if in demos
// [RH] But only if the key isn't bound to a "special" command
if (gameaction == ga_nothing &&
(demoplayback || gamestate == GS_DEMOSCREEN || gamestate == GS_TITLELEVEL))
{
const char *cmd = Bindings.GetBind (ev->data1);
if (ev->type == EV_KeyDown)
{
if (!cmd || (
strnicmp (cmd, "menu_", 5) &&
stricmp (cmd, "toggleconsole") &&
stricmp (cmd, "sizeup") &&
stricmp (cmd, "sizedown") &&
stricmp (cmd, "togglemap") &&
stricmp (cmd, "spynext") &&
stricmp (cmd, "spyprev") &&
stricmp (cmd, "chase") &&
stricmp (cmd, "+showscores") &&
stricmp (cmd, "bumpgamma") &&
stricmp (cmd, "screenshot")))
{
M_StartControlPanel(true);
M_SetMenu(NAME_Mainmenu, -1);
return true;
}
else
{
return C_DoKey (ev, &Bindings, &DoubleBindings);
}
}
//VIZDOOM_CODE
if (cmd && cmd[0] == '+')
return C_DoKey (ev, &Bindings, &DoubleBindings);
return false;
}
if (CT_Responder (ev))
return true; // chat ate the event
if (gamestate == GS_LEVEL)
{
if (ST_Responder (ev))
return true; // status window ate it
if (!viewactive && AM_Responder (ev, false))
return true; // automap ate it
}
else if (gamestate == GS_FINALE)
{
if (F_Responder (ev))
return true; // finale ate the event
}
switch (ev->type)
{
case EV_KeyDown:
if (C_DoKey (ev, &Bindings, &DoubleBindings))
return true;
break;
case EV_KeyUp:
C_DoKey (ev, &Bindings, &DoubleBindings);
break;
// [RH] mouse buttons are sent as key up/down events
case EV_Mouse:
mousex = (int)(ev->x * mouse_sensitivity);
mousey = (int)(ev->y * mouse_sensitivity);
break;
}
// [RH] If the view is active, give the automap a chance at
// the events *last* so that any bound keys get precedence.
if (gamestate == GS_LEVEL && viewactive)
return AM_Responder (ev, true);
return (ev->type == EV_KeyDown ||
ev->type == EV_Mouse);
}
//
// G_Ticker
// Make ticcmd_ts for the players.
//
extern FTexture *Page;
void G_Ticker ()
{
int i;
gamestate_t oldgamestate;
// do player reborns if needed
for (i = 0; i < MAXPLAYERS; i++)
{
if (playeringame[i])
{
if (players[i].playerstate == PST_GONE)
{
G_DoPlayerPop(i);
}
if (players[i].playerstate == PST_REBORN || players[i].playerstate == PST_ENTER)
{
G_DoReborn(i, false);
}
}
}
if (ToggleFullscreen)
{
static char toggle_fullscreen[] = "toggle fullscreen";
ToggleFullscreen = false;
AddCommandString (toggle_fullscreen);
}
// do things to change the game state
oldgamestate = gamestate;
while (gameaction != ga_nothing)
{
if (gameaction == ga_newgame2)
{
gameaction = ga_newgame;
break;
}
switch (gameaction)
{
case ga_loadlevel:
G_DoLoadLevel (-1, false);
break;
case ga_recordgame:
G_CheckDemoStatus();
G_RecordDemo(newdemoname);
G_BeginRecording(newdemomap);
case ga_newgame2: // Silence GCC (see above)
case ga_newgame:
G_DoNewGame ();
break;
case ga_loadgame:
case ga_loadgamehidecon:
case ga_autoloadgame:
G_DoLoadGame ();
break;
case ga_savegame:
G_DoSaveGame (true, savegamefile, savedescription);
gameaction = ga_nothing;
savegamefile = "";
savedescription[0] = '\0';
break;
case ga_autosave:
G_DoAutoSave ();
gameaction = ga_nothing;
break;
case ga_loadgameplaydemo:
G_DoLoadGame ();
// fallthrough
case ga_playdemo:
G_DoPlayDemo ();
break;
case ga_completed:
G_DoCompleted ();
break;
case ga_slideshow:
if (gamestate == GS_LEVEL) F_StartIntermission(level.info->slideshow, FSTATE_InLevel);
break;
case ga_worlddone:
G_DoWorldDone ();
break;
case ga_screenshot:
M_ScreenShot (shotfile);
shotfile = "";
gameaction = ga_nothing;
break;
case ga_fullconsole:
C_FullConsole ();
gameaction = ga_nothing;
break;
case ga_togglemap:
AM_ToggleMap ();
gameaction = ga_nothing;
break;
case ga_nothing:
break;
}
C_AdjustBottom ();
}
if (oldgamestate != gamestate)
{
if (oldgamestate == GS_DEMOSCREEN && Page != NULL)
{
Page->Unload();
Page = NULL;
}
else if (oldgamestate == GS_FINALE)
{
F_EndFinale ();
}
}
// get commands, check consistancy, and build new consistancy check
int buf = (gametic/ticdup)%BACKUPTICS;
// [RH] Include some random seeds and player stuff in the consistancy
// check, not just the player's x position like BOOM.
DWORD rngsum = FRandom::StaticSumSeeds ();
//Added by MC: For some of that bot stuff. The main bot function.
bglobal.Main ();
for (i = 0; i < MAXPLAYERS; i++)
{
if (playeringame[i])
{
ticcmd_t *cmd = &players[i].cmd;
ticcmd_t *newcmd = &netcmds[i][buf];
if ((gametic % ticdup) == 0)
{
RunNetSpecs (i, buf);
}
if (demorecording)
{
G_WriteDemoTiccmd (newcmd, i, buf);
}
players[i].oldbuttons = cmd->ucmd.buttons;
// If the user alt-tabbed away, paused gets set to -1. In this case,
// we do not want to read more demo commands until paused is no
// longer negative.
if (demoplayback)
{
G_ReadDemoTiccmd (cmd, i);
}
else
{
memcpy(cmd, newcmd, sizeof(ticcmd_t));
}
// check for turbo cheats
if (cmd->ucmd.forwardmove > TURBOTHRESHOLD &&
!(gametic&31) && ((gametic>>5)&(MAXPLAYERS-1)) == i )
{
Printf ("%s is turbo!\n", players[i].userinfo.GetName());
}
if (netgame && players[i].Bot == NULL && !demoplayback && (gametic%ticdup) == 0)
{
//players[i].inconsistant = 0;
if (gametic > BACKUPTICS*ticdup && consistancy[i][buf] != cmd->consistancy)
{
players[i].inconsistant = gametic - BACKUPTICS*ticdup;
}
if (players[i].mo)
{
DWORD sum = rngsum + players[i].mo->X() + players[i].mo->Y() + players[i].mo->Z()
+ players[i].mo->angle + players[i].mo->pitch;
sum ^= players[i].health;
consistancy[i][buf] = sum;
}
else
{
consistancy[i][buf] = rngsum;
}
}
}
}
// do main actions
switch (gamestate)
{
case GS_LEVEL:
P_Ticker ();
AM_Ticker ();
break;
case GS_TITLELEVEL:
P_Ticker ();
break;
case GS_INTERMISSION:
WI_Ticker ();
break;
case GS_FINALE:
F_Ticker ();
break;
case GS_DEMOSCREEN:
D_PageTicker ();
break;
case GS_STARTUP:
if (gameaction == ga_nothing)
{
gamestate = GS_FULLCONSOLE;
gameaction = ga_fullconsole;
}
break;
default:
break;
}
}
//
// PLAYER STRUCTURE FUNCTIONS
// also see P_SpawnPlayer in P_Mobj
//
//
// G_PlayerFinishLevel
// Called when a player completes a level.
//
// flags is checked for RESETINVENTORY and RESETHEALTH only.
void G_PlayerFinishLevel (int player, EFinishLevelType mode, int flags)
{
AInventory *item, *next;
player_t *p;
p = &players[player];
if (p->morphTics != 0)
{ // Undo morph
P_UndoPlayerMorph (p, p, 0, true);
}
// Strip all current powers, unless moving in a hub and the power is okay to keep.
item = p->mo->Inventory;
while (item != NULL)
{
next = item->Inventory;
if (item->IsKindOf (RUNTIME_CLASS(APowerup)))
{
if (deathmatch || ((mode != FINISH_SameHub || !(item->ItemFlags & IF_HUBPOWER))
&& !(item->ItemFlags & IF_PERSISTENTPOWER))) // Keep persistent powers in non-deathmatch games
{
item->Destroy ();
}
}
item = next;
}
if (p->ReadyWeapon != NULL &&
p->ReadyWeapon->WeaponFlags&WIF_POWERED_UP &&
p->PendingWeapon == p->ReadyWeapon->SisterWeapon)
{
// Unselect powered up weapons if the unpowered counterpart is pending
p->ReadyWeapon=p->PendingWeapon;
}
// reset invisibility to default
if (p->mo->GetDefault()->flags & MF_SHADOW)
{
p->mo->flags |= MF_SHADOW;
}
else
{
p->mo->flags &= ~MF_SHADOW;
}
p->mo->RenderStyle = p->mo->GetDefault()->RenderStyle;
p->mo->alpha = p->mo->GetDefault()->alpha;
p->extralight = 0; // cancel gun flashes
p->fixedcolormap = NOFIXEDCOLORMAP; // cancel ir goggles
p->fixedlightlevel = -1;
p->damagecount = 0; // no palette changes
p->bonuscount = 0;
p->poisoncount = 0;
p->inventorytics = 0;
if (mode != FINISH_SameHub)
{
// Take away flight and keys (and anything else with IF_INTERHUBSTRIP set)
item = p->mo->Inventory;
while (item != NULL)
{
next = item->Inventory;
if (item->InterHubAmount < 1)
{
item->Destroy ();
}
item = next;
}
}
if (mode == FINISH_NoHub && !(level.flags2 & LEVEL2_KEEPFULLINVENTORY))
{ // Reduce all owned (visible) inventory to defined maximum interhub amount
for (item = p->mo->Inventory; item != NULL; item = item->Inventory)
{
// If the player is carrying more samples of an item than allowed, reduce amount accordingly
if (item->ItemFlags & IF_INVBAR && item->Amount > item->InterHubAmount)
{
item->Amount = item->InterHubAmount;
}
}
}
// Resets player health to default if not dead.
if ((flags & CHANGELEVEL_RESETHEALTH) && p->playerstate != PST_DEAD)
{
p->health = p->mo->health = p->mo->SpawnHealth();
}
// Clears the entire inventory and gives back the defaults for starting a game
if ((flags & CHANGELEVEL_RESETINVENTORY) && p->playerstate != PST_DEAD)
{
p->mo->ClearInventory();
p->mo->GiveDefaultInventory();
}
}
//
// G_PlayerReborn
// Called after a player dies
// almost everything is cleared and initialized
//
void G_PlayerReborn (int player)
{
player_t* p;
int frags[MAXPLAYERS];
int fragcount; // [RH] Cumulative frags
int killcount;
int itemcount;
int secretcount;
int chasecam;
BYTE currclass;
userinfo_t userinfo; // [RH] Save userinfo
APlayerPawn *actor;
const PClass *cls;
FString log;
DBot *Bot; //Added by MC:
p = &players[player];
memcpy (frags, p->frags, sizeof(frags));
fragcount = p->fragcount;
killcount = p->killcount;
itemcount = p->itemcount;
secretcount = p->secretcount;
currclass = p->CurrentPlayerClass;
userinfo.TransferFrom(p->userinfo);
actor = p->mo;
cls = p->cls;
log = p->LogText;
chasecam = p->cheats & CF_CHASECAM;
Bot = p->Bot; //Added by MC:
// Reset player structure to its defaults
p->~player_t();
::new(p) player_t;
memcpy (p->frags, frags, sizeof(p->frags));
p->health = actor->health;
p->fragcount = fragcount;
p->killcount = killcount;
p->itemcount = itemcount;
p->secretcount = secretcount;
p->CurrentPlayerClass = currclass;
p->userinfo.TransferFrom(userinfo);
p->mo = actor;
p->cls = cls;
p->LogText = log;
p->cheats |= chasecam;
p->Bot = Bot; //Added by MC:
p->oldbuttons = ~0, p->attackdown = true; p->usedown = true; // don't do anything immediately
p->original_oldbuttons = ~0;
p->playerstate = PST_LIVE;
if (gamestate != GS_TITLELEVEL)
{
// [GRB] Give inventory specified in DECORATE
actor->GiveDefaultInventory ();
p->ReadyWeapon = p->PendingWeapon;
}
//Added by MC: Init bot structure.
if (p->Bot != NULL)
{
botskill_t skill = p->Bot->skill;
p->Bot->Clear ();
p->Bot->player = p;
p->Bot->skill = skill;
}
}
//
// G_CheckSpot
// Returns false if the player cannot be respawned
// at the given mapthing spot
// because something is occupying it
//
bool G_CheckSpot (int playernum, FPlayerStart *mthing)
{
fixed_t x;
fixed_t y;
fixed_t z, oldz;
int i;
if (mthing->type == 0) return false;
x = mthing->x;
y = mthing->y;
z = mthing->z;
if (!(level.flags & LEVEL_USEPLAYERSTARTZ))
{
z = 0;
}
z += P_PointInSector (x, y)->floorplane.ZatPoint (x, y);
if (!players[playernum].mo)
{ // first spawn of level, before corpses
for (i = 0; i < playernum; i++)
if (players[i].mo && players[i].mo->X() == x && players[i].mo->Y() == y)
return false;
return true;
}
oldz = players[playernum].mo->Z(); // [RH] Need to save corpse's z-height
players[playernum].mo->SetZ(z); // [RH] Checks are now full 3-D
// killough 4/2/98: fix bug where P_CheckPosition() uses a non-solid
// corpse to detect collisions with other players in DM starts
//
// Old code:
// if (!P_CheckPosition (players[playernum].mo, x, y))
// return false;
players[playernum].mo->flags |= MF_SOLID;
i = P_CheckPosition(players[playernum].mo, x, y);
players[playernum].mo->flags &= ~MF_SOLID;
players[playernum].mo->SetZ(oldz); // [RH] Restore corpse's height
if (!i)
return false;
return true;
}
//
// G_DeathMatchSpawnPlayer
// Spawns a player at one of the random death match spots
// called at level load and each death
//
// [RH] Returns the distance of the closest player to the given mapthing
static fixed_t PlayersRangeFromSpot (FPlayerStart *spot)
{
fixed_t closest = INT_MAX;
fixed_t distance;
int i;
for (i = 0; i < MAXPLAYERS; i++)
{
if (!playeringame[i] || !players[i].mo || players[i].health <= 0)
continue;
distance = players[i].mo->AproxDistance (spot->x, spot->y);
if (distance < closest)
closest = distance;
}
return closest;
}
// [RH] Select the deathmatch spawn spot farthest from everyone.
static FPlayerStart *SelectFarthestDeathmatchSpot (size_t selections)
{
fixed_t bestdistance = 0;
FPlayerStart *bestspot = NULL;
unsigned int i;
for (i = 0; i < selections; i++)
{
fixed_t distance = PlayersRangeFromSpot (&deathmatchstarts[i]);
if (distance > bestdistance)
{
bestdistance = distance;
bestspot = &deathmatchstarts[i];
}
}
return bestspot;
}
// [RH] Select a deathmatch spawn spot at random (original mechanism)
static FPlayerStart *SelectRandomDeathmatchSpot (int playernum, unsigned int selections)
{
unsigned int i, j;
for (j = 0; j < 20; j++)
{
i = pr_dmspawn() % selections;
if (G_CheckSpot (playernum, &deathmatchstarts[i]) )
{
return &deathmatchstarts[i];
}
}
// [RH] return a spot anyway, since we allow telefragging when a player spawns
return &deathmatchstarts[i];
}
void G_DeathMatchSpawnPlayer (int playernum)
{
unsigned int selections;
FPlayerStart *spot;
selections = deathmatchstarts.Size ();
// [RH] We can get by with just 1 deathmatch start
if (selections < 1)
I_Error ("No deathmatch starts");
// At level start, none of the players have mobjs attached to them,
// so we always use the random deathmatch spawn. During the game,
// though, we use whatever dmflags specifies.
if ((dmflags & DF_SPAWN_FARTHEST) && players[playernum].mo)
spot = SelectFarthestDeathmatchSpot (selections);
else
spot = SelectRandomDeathmatchSpot (playernum, selections);
if (spot == NULL)
{ // No good spot, so the player will probably get stuck.
// We were probably using select farthest above, and all
// the spots were taken.
spot = G_PickPlayerStart(playernum, PPS_FORCERANDOM);
if (!G_CheckSpot(playernum, spot))
{ // This map doesn't have enough coop spots for this player
// to use one.
spot = SelectRandomDeathmatchSpot(playernum, selections);
if (spot == NULL)
{ // We have a player 1 start, right?
spot = &playerstarts[0];
if (spot->type == 0)
{ // Fine, whatever.
spot = &deathmatchstarts[0];
}
}
}
}
AActor *mo = P_SpawnPlayer(spot, playernum);
if (mo != NULL) P_PlayerStartStomp(mo);
// TODO: Causes crash - fix
//VIZ_DebugMsg(4, VIZ_FUNC, "playernum: %d (%s), spot: %d %d %d", gametic, playernum, players[playernum].userinfo.GetName(), spot->x, spot->y, spot->z);
}
//
// G_PickPlayerStart
//
FPlayerStart *G_PickPlayerStart(int playernum, int flags)
{
if (AllPlayerStarts.Size() == 0) // No starts to pick
{
return NULL;
}
if ((level.flags2 & LEVEL2_RANDOMPLAYERSTARTS) || (flags & PPS_FORCERANDOM) ||
playerstarts[playernum].type == 0)
{
if (!(flags & PPS_NOBLOCKINGCHECK))
{
TArray<FPlayerStart *> good_starts;
unsigned int i;
// Find all unblocked player starts.
for (i = 0; i < AllPlayerStarts.Size(); ++i)
{
if (G_CheckSpot(playernum, &AllPlayerStarts[i]))
{
good_starts.Push(&AllPlayerStarts[i]);
}
}
if (good_starts.Size() > 0)
{ // Pick an open spot at random.
return good_starts[pr_pspawn(good_starts.Size())];
}
}
// Pick a spot at random, whether it's open or not.
return &AllPlayerStarts[pr_pspawn(AllPlayerStarts.Size())];
}
return &playerstarts[playernum];
}
//
// G_QueueBody
//
static void G_QueueBody (AActor *body)
{
// flush an old corpse if needed
int modslot = bodyqueslot%BODYQUESIZE;
if (bodyqueslot >= BODYQUESIZE && bodyque[modslot] != NULL)
{
bodyque[modslot]->Destroy ();
}
bodyque[modslot] = body;
// Copy the player's translation, so that if they change their color later, only
// their current body will change and not all their old corpses.
if (GetTranslationType(body->Translation) == TRANSLATION_Players ||
GetTranslationType(body->Translation) == TRANSLATION_PlayersExtra)
{
*translationtables[TRANSLATION_PlayerCorpses][modslot] = *TranslationToTable(body->Translation);
body->Translation = TRANSLATION(TRANSLATION_PlayerCorpses,modslot);
translationtables[TRANSLATION_PlayerCorpses][modslot]->UpdateNative();
}
const int skinidx = body->player->userinfo.GetSkin();
if (0 != skinidx && !(body->flags4 & MF4_NOSKIN))
{
// Apply skin's scale to actor's scale, it will be lost otherwise
const AActor *const defaultActor = body->GetDefault();
const FPlayerSkin &skin = skins[skinidx];
body->scaleX = Scale(body->scaleX, skin.ScaleX, defaultActor->scaleX);
body->scaleY = Scale(body->scaleY, skin.ScaleY, defaultActor->scaleY);
}
bodyqueslot++;
}
//
// G_DoReborn
//
void G_DoReborn (int playernum, bool freshbot)
{
if (!multiplayer && !(level.flags2 & LEVEL2_ALLOWRESPAWN))
{
if (BackupSaveName.Len() > 0 && FileExists (BackupSaveName.GetChars()))
{ // Load game from the last point it was saved
savename = BackupSaveName;
gameaction = ga_autoloadgame;
}
else
{ // Reload the level from scratch
bool indemo = demoplayback;
BackupSaveName = "";
G_InitNew (level.MapName, false);
demoplayback = indemo;
// gameaction = ga_loadlevel;
}
}
else
{
// respawn at the start
// first disassociate the corpse
if (players[playernum].mo)
{
G_QueueBody (players[playernum].mo);
players[playernum].mo->player = NULL;
}
// spawn at random spot if in deathmatch
if (deathmatch)
{
G_DeathMatchSpawnPlayer (playernum);
return;
}
if (!(level.flags2 & LEVEL2_RANDOMPLAYERSTARTS) &&
playerstarts[playernum].type != 0 &&
G_CheckSpot (playernum, &playerstarts[playernum]))
{
AActor *mo = P_SpawnPlayer(&playerstarts[playernum], playernum);
if (mo != NULL) P_PlayerStartStomp(mo, true);
}
else
{ // try to spawn at any random player's spot
FPlayerStart *start = G_PickPlayerStart(playernum, PPS_FORCERANDOM);
AActor *mo = P_SpawnPlayer(start, playernum);
if (mo != NULL) P_PlayerStartStomp(mo, true);
}
}
}
//
// G_DoReborn
//
void G_DoPlayerPop(int playernum)
{
playeringame[playernum] = false;
if (deathmatch)
{
Printf("%s left the game with %d frags\n",
players[playernum].userinfo.GetName(),
players[playernum].fragcount);
}
else
{
Printf("%s left the game\n", players[playernum].userinfo.GetName());
}
// [RH] Revert each player to their own view if spying through the player who left
for (int ii = 0; ii < MAXPLAYERS; ++ii)
{
if (playeringame[ii] && players[ii].camera == players[playernum].mo)
{
players[ii].camera = players[ii].mo;
if (ii == consoleplayer && StatusBar != NULL)
{
StatusBar->AttachToPlayer(&players[ii]);
}
}
}
// [RH] Make the player disappear
FBehavior::StaticStopMyScripts(players[playernum].mo);
// [RH] Let the scripts know the player left
FBehavior::StaticStartTypedScripts(SCRIPT_Disconnect, players[playernum].mo, true, playernum, true);
if (players[playernum].mo != NULL)
{
P_DisconnectEffect(players[playernum].mo);
players[playernum].mo->player = NULL;
players[playernum].mo->Destroy();
if (!(players[playernum].mo->ObjectFlags & OF_EuthanizeMe))
{ // We just destroyed a morphed player, so now the original player
// has taken their place. Destroy that one too.
players[playernum].mo->Destroy();
}
players[playernum].mo = NULL;
players[playernum].camera = NULL;
}
}
void G_ScreenShot (char *filename)
{
shotfile = filename;
gameaction = ga_screenshot;
}
//
// G_InitFromSavegame
// Can be called by the startup code or the menu task.
//
void G_LoadGame (const char* name, bool hidecon)
{
if (name != NULL)
{
savename = name;
gameaction = !hidecon ? ga_loadgame : ga_loadgamehidecon;
}
}
static bool CheckSingleWad (char *name, bool &printRequires, bool printwarn)
{
if (name == NULL)
{
return true;
}
if (Wads.CheckIfWadLoaded (name) < 0)
{
if (printwarn)
{
if (!printRequires)
{
Printf ("This savegame needs these wads:\n%s", name);
}
else
{
Printf (", %s", name);
}
}
printRequires = true;
delete[] name;
return false;
}
delete[] name;
return true;
}
// Return false if not all the needed wads have been loaded.
bool G_CheckSaveGameWads (PNGHandle *png, bool printwarn)
{
char *text;
bool printRequires = false;
text = M_GetPNGText (png, "Game WAD");
CheckSingleWad (text, printRequires, printwarn);
text = M_GetPNGText (png, "Map WAD");
CheckSingleWad (text, printRequires, printwarn);
if (printRequires)
{
if (printwarn)
{
Printf ("\n");
}
return false;
}
return true;
}
void G_DoLoadGame ()
{
char sigcheck[20];
char *text = NULL;
char *map;
bool hidecon;
if (gameaction != ga_autoloadgame)
{
demoplayback = false;
}
hidecon = gameaction == ga_loadgamehidecon;
gameaction = ga_nothing;
FILE *stdfile = fopen (savename.GetChars(), "rb");
if (stdfile == NULL)
{
Printf ("Could not read savegame '%s'\n", savename.GetChars());
return;
}
PNGHandle *png = M_VerifyPNG (stdfile);
if (png == NULL)
{
fclose (stdfile);
Printf ("'%s' is not a valid (PNG) savegame\n", savename.GetChars());
return;
}
SaveVersion = 0;
// Check whether this savegame actually has been created by a compatible engine.
// Since there are ZDoom derivates using the exact same savegame format but
// with mutual incompatibilities this check simplifies things significantly.
char *engine = M_GetPNGText (png, "Engine");
if (engine == NULL || 0 != strcmp (engine, GAMESIG))
{
// Make a special case for the message printed for old savegames that don't
// have this information.
if (engine == NULL)
{
Printf ("Savegame is from an incompatible version\n");
}
else
{
Printf ("Savegame is from another ZDoom-based engine: %s\n", engine);
delete[] engine;
}
delete png;
fclose (stdfile);
return;
}
if (engine != NULL)
{
delete[] engine;
}
SaveVersion = 0;
if (!M_GetPNGText (png, "ZDoom Save Version", sigcheck, 20) ||
0 != strncmp (sigcheck, SAVESIG, 9) || // ZDOOMSAVE is the first 9 chars
(SaveVersion = atoi (sigcheck+9)) < MINSAVEVER)
{
delete png;
fclose (stdfile);
Printf ("Savegame is from an incompatible version");
if (SaveVersion != 0)
{
Printf(": %d (%d is the oldest supported)", SaveVersion, MINSAVEVER);
}
Printf("\n");
return;
}
if (!G_CheckSaveGameWads (png, true))
{
fclose (stdfile);
return;
}
map = M_GetPNGText (png, "Current Map");
if (map == NULL)
{
Printf ("Savegame is missing the current map\n");
fclose (stdfile);
return;
}
// Now that it looks like we can load this save, hide the fullscreen console if it was up
// when the game was selected from the menu.
if (hidecon && gamestate == GS_FULLCONSOLE)
{
gamestate = GS_HIDECONSOLE;
}
// Read intermission data for hubs
G_ReadHubInfo(png);
bglobal.RemoveAllBots (true);
text = M_GetPNGText (png, "Important CVARs");
if (text != NULL)
{
BYTE *vars_p = (BYTE *)text;
C_ReadCVars (&vars_p);
delete[] text;
if (SaveVersion <= 4509)
{
// account for the flag shuffling for making freelook a 3-state option
INTBOOL flag = dmflags & DF_YES_FREELOOK;
dmflags = dmflags & ~DF_YES_FREELOOK;
if (flag) dmflags2 = dmflags2 | DF2_RESPAWN_SUPER;
}
}
// dearchive all the modifications
if (M_FindPNGChunk (png, MAKE_ID('p','t','I','c')) == 8)
{
DWORD time[2];
fread (&time, 8, 1, stdfile);
time[0] = BigLong((unsigned int)time[0]);
time[1] = BigLong((unsigned int)time[1]);
level.time = Scale (time[1], TICRATE, time[0]);
}
else
{ // No ptIc chunk so we don't know how long the user was playing
level.time = 0;
}
G_ReadSnapshots (png);
// load a base level
savegamerestore = true; // Use the player actors in the savegame
bool demoplaybacksave = demoplayback;
G_InitNew (map, false);
demoplayback = demoplaybacksave;
delete[] map;
savegamerestore = false;
STAT_Read(png);
FRandom::StaticReadRNGState(png);
P_ReadACSDefereds(png);
P_ReadACSVars(png);
NextSkill = -1;
if (M_FindPNGChunk (png, MAKE_ID('s','n','X','t')) == 1)
{
BYTE next;
fread (&next, 1, 1, stdfile);
NextSkill = next;
}
if (level.info->snapshot != NULL)
{
delete level.info->snapshot;
level.info->snapshot = NULL;
}
BackupSaveName = savename;
delete png;
fclose (stdfile);
// At this point, the GC threshold is likely a lot higher than the
// amount of memory in use, so bring it down now by starting a
// collection.
GC::StartCollection();
}
//
// G_SaveGame
// Called by the menu task.
// Description is a 24 byte text string
//
void G_SaveGame (const char *filename, const char *description)
{
if (sendsave || gameaction == ga_savegame)
{
Printf ("A game save is still pending.\n");
return;
}
else if (!usergame)
{
Printf ("not in a saveable game\n");
}
else if (gamestate != GS_LEVEL)
{
Printf ("not in a level\n");
}
else if (players[consoleplayer].health <= 0 && !multiplayer)
{
Printf ("player is dead in a single-player game\n");
}
else
{
savegamefile = filename;
strncpy (savedescription, description, sizeof(savedescription)-1);
savedescription[sizeof(savedescription)-1] = '\0';
sendsave = true;
}
}
FString G_BuildSaveName (const char *prefix, int slot)
{
FString name;
FString leader;
const char *slash = "";
leader = Args->CheckValue ("-savedir");
if (leader.IsEmpty())
{
leader = save_dir;
if (leader.IsEmpty())
{
leader = M_GetSavegamesPath();
}
}
size_t len = leader.Len();
if (leader[0] != '\0' && leader[len-1] != '\\' && leader[len-1] != '/')
{
slash = "/";
}
name << leader << slash;
name = NicePath(name);
CreatePath(name);
name << prefix;
if (slot >= 0)
{
name.AppendFormat("%d.zds", slot);
}
return name;
}
CVAR (Int, autosavenum, 0, CVAR_NOSET|CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
static int nextautosave = -1;
CVAR (Int, disableautosave, 0, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
CUSTOM_CVAR (Int, autosavecount, 4, CVAR_ARCHIVE|CVAR_GLOBALCONFIG)
{
if (self < 0)
self = 0;
if (self > 20)
self = 20;
}
extern void P_CalcHeight (player_t *);
void G_DoAutoSave ()
{
char description[SAVESTRINGSIZE];
FString file;
// Keep up to four autosaves at a time
UCVarValue num;
const char *readableTime;
int count = autosavecount != 0 ? autosavecount : 1;
if (nextautosave == -1)
{
nextautosave = (autosavenum + 1) % count;
}
num.Int = nextautosave;
autosavenum.ForceSet (num, CVAR_Int);
file = G_BuildSaveName ("auto", nextautosave);
if (!(level.flags2 & LEVEL2_NOAUTOSAVEHINT))
{
nextautosave = (nextautosave + 1) % count;
}
else
{
// This flag can only be used once per level
level.flags2 &= ~LEVEL2_NOAUTOSAVEHINT;
}
readableTime = myasctime ();
strcpy (description, "Autosave ");
strncpy (description+9, readableTime+4, 12);
description[9+12] = 0;
G_DoSaveGame (false, file, description);
}
static void PutSaveWads (FILE *file)
{
const char *name;
// Name of IWAD
name = Wads.GetWadName (FWadCollection::IWAD_FILENUM);
M_AppendPNGText (file, "Game WAD", name);
// Name of wad the map resides in
if (Wads.GetLumpFile (level.lumpnum) > 1)
{
name = Wads.GetWadName (Wads.GetLumpFile (level.lumpnum));
M_AppendPNGText (file, "Map WAD", name);
}
}
static void PutSaveComment (FILE *file)
{
char comment[256];
const char *readableTime;
WORD len;
int levelTime;
// Get the current date and time
readableTime = myasctime ();
strncpy (comment, readableTime, 10);
strncpy (comment+10, readableTime+19, 5);
strncpy (comment+15, readableTime+10, 9);
comment[24] = 0;
M_AppendPNGText (file, "Creation Time", comment);
// Get level name
//strcpy (comment, level.level_name);
mysnprintf(comment, countof(comment), "%s - %s", level.MapName.GetChars(), level.LevelName.GetChars());
len = (WORD)strlen (comment);
comment[len] = '\n';
// Append elapsed time
levelTime = level.time / TICRATE;
mysnprintf (comment + len + 1, countof(comment) - len - 1, "time: %02d:%02d:%02d",
levelTime/3600, (levelTime%3600)/60, levelTime%60);
comment[len+16] = 0;
// Write out the comment
M_AppendPNGText (file, "Comment", comment);
}
static void PutSavePic (FILE *file, int width, int height)
{
if (width <= 0 || height <= 0 || !storesavepic)
{
M_CreateDummyPNG (file);
}
else
{
Renderer->WriteSavePic(&players[consoleplayer], file, width, height);
}
}
void G_DoSaveGame (bool okForQuicksave, FString filename, const char *description)
{
char buf[100];
// Do not even try, if we're not in a level. (Can happen after
// a demo finishes playback.)
if (lines == NULL || sectors == NULL || gamestate != GS_LEVEL)
{
return;
}
if (demoplayback)
{
filename = G_BuildSaveName ("demosave.zds", -1);
}
if (cl_waitforsave)
I_FreezeTime(true);
insave = true;
G_SnapshotLevel ();
FILE *stdfile = fopen (filename, "wb");
if (stdfile == NULL)
{
Printf ("Could not create savegame '%s'\n", filename.GetChars());
insave = false;
I_FreezeTime(false);
return;
}
SaveVersion = SAVEVER;
PutSavePic (stdfile, SAVEPICWIDTH, SAVEPICHEIGHT);
mysnprintf(buf, countof(buf), GAMENAME " %s", GetVersionString());
M_AppendPNGText (stdfile, "Software", buf);
M_AppendPNGText (stdfile, "Engine", GAMESIG);
M_AppendPNGText (stdfile, "ZDoom Save Version", SAVESIG);
M_AppendPNGText (stdfile, "Title", description);
M_AppendPNGText (stdfile, "Current Map", level.MapName);
PutSaveWads (stdfile);
PutSaveComment (stdfile);
// Intermission stats for hubs
G_WriteHubInfo(stdfile);
{
FString vars = C_GetMassCVarString(CVAR_SERVERINFO);
M_AppendPNGText (stdfile, "Important CVARs", vars.GetChars());
}
if (level.time != 0 || level.maptime != 0)
{
DWORD time[2] = { DWORD(BigLong(TICRATE)), DWORD(BigLong(level.time)) };
M_AppendPNGChunk (stdfile, MAKE_ID('p','t','I','c'), (BYTE *)&time, 8);
}
G_WriteSnapshots (stdfile);
STAT_Write(stdfile);
FRandom::StaticWriteRNGState (stdfile);
P_WriteACSDefereds (stdfile);
P_WriteACSVars(stdfile);
if (NextSkill != -1)
{
BYTE next = NextSkill;
M_AppendPNGChunk (stdfile, MAKE_ID('s','n','X','t'), &next, 1);
}
M_FinishPNG (stdfile);
fclose (stdfile);
M_NotifyNewSave (filename.GetChars(), description, okForQuicksave);
// Check whether the file is ok.
bool success = false;
stdfile = fopen (filename.GetChars(), "rb");
if (stdfile != NULL)
{
PNGHandle *pngh = M_VerifyPNG(stdfile);
if (pngh != NULL)
{
success = true;
delete pngh;
}
fclose(stdfile);
}
if (success)
{
if (longsavemessages) Printf ("%s (%s)\n", GStrings("GGSAVED"), filename.GetChars());
else Printf ("%s\n", GStrings("GGSAVED"));
}
else Printf(PRINT_HIGH, "Save failed\n");
BackupSaveName = filename;
// We don't need the snapshot any longer.
if (level.info->snapshot != NULL)
{
delete level.info->snapshot;
level.info->snapshot = NULL;
}
insave = false;
I_FreezeTime(false);
}
//
// DEMO RECORDING
//
void G_ReadDemoTiccmd (ticcmd_t *cmd, int player)
{
int id = DEM_BAD;
while (id != DEM_USERCMD && id != DEM_EMPTYUSERCMD)
{
if (!demorecording && demo_p >= zdembodyend)
{
// nothing left in the BODY chunk, so end playback.
G_CheckDemoStatus ();
break;
}
id = ReadByte (&demo_p);
switch (id)
{
case DEM_STOP:
// end of demo stream
G_CheckDemoStatus ();
break;
case DEM_USERCMD:
UnpackUserCmd (&cmd->ucmd, &cmd->ucmd, &demo_p);
break;
case DEM_EMPTYUSERCMD:
// leave cmd->ucmd unchanged
break;
case DEM_DROPPLAYER:
{
BYTE i = ReadByte (&demo_p);
if (i < MAXPLAYERS)
{
playeringame[i] = false;
}
}
break;
default:
Net_DoCommand (id, &demo_p, player);
break;
}
}
VIZ_ReadUserCmdState(&cmd->ucmd, player);
}
bool stoprecording;
CCMD (stop)
{
stoprecording = true;
}
extern BYTE *lenspot;
void G_WriteDemoTiccmd (ticcmd_t *cmd, int player, int buf)
{
BYTE *specdata;
int speclen;
if (stoprecording)
{ // use "stop" console command to end demo recording
G_CheckDemoStatus ();
if (!netgame)
{
gameaction = ga_fullconsole;
}
return;
}
// [RH] Write any special "ticcmds" for this player to the demo
if ((specdata = NetSpecs[player][buf].GetData (&speclen)) && gametic % ticdup == 0)
{
memcpy (demo_p, specdata, speclen);
demo_p += speclen;
NetSpecs[player][buf].SetData (NULL, 0);
}
// [RH] Now write out a "normal" ticcmd.
WriteUserCmdMessage (&cmd->ucmd, &players[player].cmd.ucmd, &demo_p);
// [RH] Bigger safety margin
if (demo_p > demobuffer + maxdemosize - 64)
{
ptrdiff_t pos = demo_p - demobuffer;
ptrdiff_t spot = lenspot - demobuffer;
ptrdiff_t comp = democompspot - demobuffer;
ptrdiff_t body = demobodyspot - demobuffer;
// [RH] Allocate more space for the demo
maxdemosize += 0x20000;
demobuffer = (BYTE *)M_Realloc (demobuffer, maxdemosize);
demo_p = demobuffer + pos;
lenspot = demobuffer + spot;
democompspot = demobuffer + comp;
demobodyspot = demobuffer + body;
}
}
//
// G_RecordDemo
//
void G_RecordDemo (const char* name)
{
usergame = false;
demoname = name;
FixPathSeperator (demoname);
DefaultExtension (demoname, ".lmp");
maxdemosize = 0x20000;
demobuffer = (BYTE *)M_Malloc (maxdemosize);
demorecording = true;
}
// [RH] Demos are now saved as IFF FORMs. I've also removed support
// for earlier ZDEMs since I didn't want to bother supporting
// something that probably wasn't used much (if at all).
void G_BeginRecording (const char *startmap)
{
int i;
if (startmap == NULL)
{
startmap = level.MapName;
}
demo_p = demobuffer;
WriteLong (FORM_ID, &demo_p); // Write FORM ID
demo_p += 4; // Leave space for len
WriteLong (ZDEM_ID, &demo_p); // Write ZDEM ID
// Write header chunk
StartChunk (ZDHD_ID, &demo_p);
WriteWord (DEMOGAMEVERSION, &demo_p); // Write ZDoom version
*demo_p++ = 2; // Write minimum version needed to use this demo.
*demo_p++ = 3; // (Useful?)
strcpy((char*)demo_p, startmap); // Write name of map demo was recorded on.
demo_p += strlen(startmap) + 1;
WriteLong(rngseed, &demo_p); // Write RNG seed
*demo_p++ = consoleplayer;
FinishChunk (&demo_p);
// Write player info chunks
for (i = 0; i < MAXPLAYERS; i++)
{
if (playeringame[i])
{
StartChunk (UINF_ID, &demo_p);
WriteByte ((BYTE)i, &demo_p);
D_WriteUserInfoStrings (i, &demo_p);
FinishChunk (&demo_p);
}
}
// It is possible to start a "multiplayer" game with only one player,
// so checking the number of players when playing back the demo is not
// enough.
if (multiplayer)
{
StartChunk (NETD_ID, &demo_p);
FinishChunk (&demo_p);
}
// Write cvars chunk
StartChunk (VARS_ID, &demo_p);
C_WriteCVars (&demo_p, CVAR_SERVERINFO|CVAR_DEMOSAVE);
FinishChunk (&demo_p);
// Write weapon ordering chunk
StartChunk (WEAP_ID, &demo_p);
P_WriteDemoWeaponsChunk(&demo_p);
FinishChunk (&demo_p);
// Indicate body is compressed
StartChunk (COMP_ID, &demo_p);
democompspot = demo_p;
WriteLong (0, &demo_p);
FinishChunk (&demo_p);
// Begin BODY chunk
StartChunk (BODY_ID, &demo_p);
demobodyspot = demo_p;
}
//
// G_PlayDemo
//
FString defdemoname;
void G_DeferedPlayDemo (const char *name)
{
defdemoname = name;
gameaction = (gameaction == ga_loadgame) ? ga_loadgameplaydemo : ga_playdemo;
}
CCMD (playdemo)
{
if (netgame)
{
Printf("End your current netgame first!");
return;
}
if (demorecording)
{
Printf("End your current demo first!");
return;
}
if (argv.argc() > 1)
{
G_DeferedPlayDemo (argv[1]);
singledemo = true;
}
}
CCMD (timedemo)
{
if (argv.argc() > 1)
{
G_TimeDemo (argv[1]);
singledemo = true;
}
}
// [RH] Process all the information in a FORM ZDEM
// until a BODY chunk is entered.
bool G_ProcessIFFDemo (FString &mapname)
{
bool headerHit = false;
bool bodyHit = false;
int numPlayers = 0;
int id, len, i;
uLong uncompSize = 0;
BYTE *nextchunk;
demoplayback = true;
for (i = 0; i < MAXPLAYERS; i++)
playeringame[i] = 0;
len = ReadLong (&demo_p);
zdemformend = demo_p + len + (len & 1);
// Check to make sure this is a ZDEM chunk file.
// TODO: Support multiple FORM ZDEMs in a CAT. Might be useful.
id = ReadLong (&demo_p);
if (id != ZDEM_ID)
{
Printf ("Not a " GAMENAME " demo file!\n");
return true;
}
// Process all chunks until a BODY chunk is encountered.
while (demo_p < zdemformend && !bodyHit)
{
id = ReadLong (&demo_p);
len = ReadLong (&demo_p);
nextchunk = demo_p + len + (len & 1);
if (nextchunk > zdemformend)
{
Printf ("Demo is mangled!\n");
return true;
}
switch (id)
{
case ZDHD_ID:
headerHit = true;
demover = ReadWord (&demo_p); // ZDoom version demo was created with
if (demover < MINDEMOVERSION)
{
Printf ("Demo requires an older version of " GAMENAME "!\n");
//return true;
}
if (ReadWord (&demo_p) > DEMOGAMEVERSION) // Minimum ZDoom version
{
Printf ("Demo requires a newer version of " GAMENAME "!\n");
return true;
}
if (demover >= 0x21a)
{
mapname = (char*)demo_p;
demo_p += mapname.Len() + 1;
}
else
{
mapname = FString((char*)demo_p, 8);
demo_p += 8;
}
rngseed = ReadLong (&demo_p);
// Only reset the RNG if this demo is not in conjunction with a savegame.
if (mapname[0] != 0)
{
FRandom::StaticClearRandom ();
}
consoleplayer = *demo_p++;
break;
case VARS_ID:
C_ReadCVars (&demo_p);
break;
case UINF_ID:
i = ReadByte (&demo_p);
if (!playeringame[i])
{
playeringame[i] = 1;
numPlayers++;
}
D_ReadUserInfoStrings (i, &demo_p, false);
break;
case NETD_ID:
multiplayer = true;
break;
case WEAP_ID:
P_ReadDemoWeaponsChunk(&demo_p);
break;
case BODY_ID:
bodyHit = true;
zdembodyend = demo_p + len;
break;
case COMP_ID:
uncompSize = ReadLong (&demo_p);
break;
}
if (!bodyHit)
demo_p = nextchunk;
}
if (!headerHit)
{
Printf ("Demo has no header!\n");
return true;
}
if (!numPlayers)
{
Printf ("Demo has no players!\n");
return true;
}
if (!bodyHit)
{
zdembodyend = NULL;
Printf ("Demo has no BODY chunk!\n");
return true;
}
if (numPlayers > 1)
multiplayer = netgame = true;
if (uncompSize > 0)
{
BYTE *uncompressed = (BYTE*)M_Malloc(uncompSize);
int r = uncompress (uncompressed, &uncompSize, demo_p, uLong(zdembodyend - demo_p));
if (r != Z_OK)
{
Printf ("Could not decompress demo! %s\n", M_ZLibError(r).GetChars());
M_Free(uncompressed);
return true;
}
M_Free (demobuffer);
zdembodyend = uncompressed + uncompSize;
demobuffer = demo_p = uncompressed;
}
return false;
}
void G_DoPlayDemo (void)
{
FString mapname;
int demolump;
gameaction = ga_nothing;
// [RH] Allow for demos not loaded as lumps
demolump = Wads.CheckNumForFullName (defdemoname, true);
if (demolump >= 0)
{
int demolen = Wads.LumpLength (demolump);
demobuffer = (BYTE *)M_Malloc(demolen);
Wads.ReadLump (demolump, demobuffer);
}
else
{
FixPathSeperator (defdemoname);
DefaultExtension (defdemoname, ".lmp");
M_ReadFileMalloc (defdemoname, &demobuffer);
}
demo_p = demobuffer;
Printf ("Playing demo %s\n", defdemoname.GetChars());
C_BackupCVars (); // [RH] Save cvars that might be affected by demo
if (ReadLong (&demo_p) != FORM_ID)
{
const char *eek = "Cannot play non-" GAMENAME " demos.\n";
C_ForgetCVars();
M_Free(demobuffer);
demo_p = demobuffer = NULL;
if (singledemo)
{
I_Error ("%s", eek);
}
else
{
Printf (PRINT_BOLD, "%s", eek);
gameaction = ga_nothing;
}
}
else if (G_ProcessIFFDemo (mapname))
{
C_RestoreCVars();
gameaction = ga_nothing;
demoplayback = false;
}
else
{
// don't spend a lot of time in loadlevel
precache = false;
demonew = true;
if (mapname.Len() != 0)
{
G_InitNew (mapname, false);
}
else if (numsectors == 0)
{
I_Error("Cannot play demo without its savegame\n");
}
C_HideConsole ();
demonew = false;
precache = true;
usergame = false;
demoplayback = true;
}
}
//
// G_TimeDemo
//
void G_TimeDemo (const char* name)
{
nodrawers = !!Args->CheckParm ("-nodraw");
noblit = !!Args->CheckParm ("-noblit");
timingdemo = true;
singletics = true;
defdemoname = name;
gameaction = (gameaction == ga_loadgame) ? ga_loadgameplaydemo : ga_playdemo;
}
/*
===================
=
= G_CheckDemoStatus
=
= Called after a death or level completion to allow demos to be cleaned up
= Returns true if a new demo loop action will take place
===================
*/
bool G_CheckDemoStatus (void)
{
if (!demorecording)
{ // [RH] Restore the player's userinfo settings.
D_SetupUserInfo();
}
if (demoplayback)
{
extern int starttime;
int endtime = 0;
if (timingdemo)
endtime = I_GetTime (false) - starttime;
C_RestoreCVars (); // [RH] Restore cvars demo might have changed
M_Free (demobuffer);
demobuffer = NULL;
P_SetupWeapons_ntohton();
demoplayback = false;
netgame = false;
multiplayer = false;
singletics = false;
for (int i = 1; i < MAXPLAYERS; i++)
playeringame[i] = 0;
consoleplayer = 0;
players[0].camera = NULL;
if (StatusBar != NULL)
{
StatusBar->AttachToPlayer (&players[0]);
}
if (singledemo || timingdemo)
{
if (timingdemo)
{
// Trying to get back to a stable state after timing a demo
// seems to cause problems. I don't feel like fixing that
// right now.
I_FatalError ("timed %i gametics in %i realtics (%.1f fps)\n"
"(This is not really an error.)", gametic,
endtime, (float)gametic/(float)endtime*(float)TICRATE);
}
else
{
Printf ("Demo ended.\n");
}
gameaction = ga_fullconsole;
timingdemo = false;
return false;
}
else
{
D_AdvanceDemo ();
}
return true;
}
if (demorecording)
{
BYTE *formlen;
WriteByte (DEM_STOP, &demo_p);
if (demo_compress)
{
// Now that the entire BODY chunk has been created, replace it with
// a compressed version. If the BODY successfully compresses, the
// contents of the COMP chunk will be changed to indicate the
// uncompressed size of the BODY.
uLong len = uLong(demo_p - demobodyspot);
uLong outlen = (len + len/100 + 12);
Byte *compressed = new Byte[outlen];
int r = compress2 (compressed, &outlen, demobodyspot, len, 9);
if (r == Z_OK && outlen < len)
{
formlen = democompspot;
WriteLong (len, &democompspot);
memcpy (demobodyspot, compressed, outlen);
demo_p = demobodyspot + outlen;
}
delete[] compressed;
}
FinishChunk (&demo_p);
formlen = demobuffer + 4;
WriteLong (int(demo_p - demobuffer - 8), &formlen);
bool saved = M_WriteFile (demoname, demobuffer, int(demo_p - demobuffer));
M_Free (demobuffer);
demorecording = false;
stoprecording = false;
if (saved)
{
Printf ("Demo %s recorded\n", demoname.GetChars());
}
else
{
Printf ("Demo %s could not be saved\n", demoname.GetChars());
}
}
return false;
}
| 23.549451 | 154 | 0.63566 | [
"solid"
] |
3372531e2762e10493e7f4385a07c60867dca2ed | 19,348 | cpp | C++ | examples/ex19p.cpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | examples/ex19p.cpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | examples/ex19p.cpp | henrykrumb/mfem | 91143731cfc9d154c07a6af9f18c7aabb6f72b46 | [
"BSD-3-Clause"
] | null | null | null | // MFEM Example 19 - Parallel Version
//
// Compile with: make ex19p
//
// Sample runs:
// mpirun -np 2 ex19p -m ../data/beam-quad.mesh
// mpirun -np 2 ex19p -m ../data/beam-tri.mesh
// mpirun -np 2 ex19p -m ../data/beam-hex.mesh
// mpirun -np 2 ex19p -m ../data/beam-tet.mesh
// mpirun -np 2 ex19p -m ../data/beam-wedge.mesh
//
// Description: This examples solves a quasi-static incompressible nonlinear
// elasticity problem of the form 0 = H(x), where H is an
// incompressible hyperelastic model and x is a block state vector
// containing displacement and pressure variables. The geometry of
// the domain is assumed to be as follows:
//
// +---------------------+
// boundary --->| |<--- boundary
// attribute 1 | | attribute 2
// (fixed) +---------------------+ (fixed, nonzero)
//
// The example demonstrates the use of block nonlinear operators
// (the class RubberOperator defining H(x)) as well as a nonlinear
// Newton solver for the quasi-static problem. Each Newton step
// requires the inversion of a Jacobian matrix, which is done
// through a (preconditioned) inner solver. The specialized block
// preconditioner is implemented as a user-defined solver.
//
// We recommend viewing examples 2, 5, and 10 before viewing this
// example.
#include "mfem.hpp"
#include <memory>
#include <iostream>
#include <fstream>
using namespace std;
using namespace mfem;
// Custom block preconditioner for the Jacobian of the incompressible nonlinear
// elasticity operator. It has the form
//
// P^-1 = [ K^-1 0 ][ I -B^T ][ I 0 ]
// [ 0 I ][ 0 I ][ 0 -\gamma S^-1 ]
//
// where the original Jacobian has the form
//
// J = [ K B^T ]
// [ B 0 ]
//
// and K^-1 is an approximation of the inverse of the displacement part of the
// Jacobian and S^-1 is an approximation of the inverse of the Schur
// complement S = B K^-1 B^T. The Schur complement is approximated using
// a mass matrix of the pressure variables.
class JacobianPreconditioner : public Solver
{
protected:
// Finite element spaces for setting up preconditioner blocks
Array<ParFiniteElementSpace *> spaces;
// Offsets for extracting block vector segments
Array<int> &block_trueOffsets;
// Jacobian for block access
BlockOperator *jacobian;
// Scaling factor for the pressure mass matrix in the block preconditioner
double gamma;
// Objects for the block preconditioner application
Operator *pressure_mass;
Solver *mass_pcg;
Solver *mass_prec;
Solver *stiff_pcg;
Solver *stiff_prec;
public:
JacobianPreconditioner(Array<ParFiniteElementSpace *> &fes,
Operator &mass, Array<int> &offsets);
virtual void Mult(const Vector &k, Vector &y) const;
virtual void SetOperator(const Operator &op);
virtual ~JacobianPreconditioner();
};
// After spatial discretization, the rubber model can be written as:
// 0 = H(x)
// where x is the block vector representing the deformation and pressure and
// H(x) is the nonlinear incompressible neo-Hookean operator.
class RubberOperator : public Operator
{
protected:
// Finite element spaces
Array<ParFiniteElementSpace *> spaces;
// Block nonlinear form
ParBlockNonlinearForm *Hform;
// Pressure mass matrix for the preconditioner
Operator *pressure_mass;
// Newton solver for the hyperelastic operator
NewtonSolver newton_solver;
// Solver for the Jacobian solve in the Newton method
Solver *j_solver;
// Preconditioner for the Jacobian
Solver *j_prec;
// Shear modulus coefficient
Coefficient μ
// Block offsets for variable access
Array<int> &block_trueOffsets;
public:
RubberOperator(Array<ParFiniteElementSpace *> &fes, Array<Array<int> *>&ess_bdr,
Array<int> &block_trueOffsets, double rel_tol, double abs_tol,
int iter, Coefficient &mu);
// Required to use the native newton solver
virtual Operator &GetGradient(const Vector &xp) const;
virtual void Mult(const Vector &k, Vector &y) const;
// Driver for the newton solver
void Solve(Vector &xp) const;
virtual ~RubberOperator();
};
// Visualization driver
void visualize(ostream &out, ParMesh *mesh, ParGridFunction *deformed_nodes,
ParGridFunction *field, const char *field_name = NULL,
bool init_vis = false);
// Configuration definition functions
void ReferenceConfiguration(const Vector &x, Vector &y);
void InitialDeformation(const Vector &x, Vector &y);
int main(int argc, char *argv[])
{
// 1. Initialize MPI
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// 2. Parse command-line options
const char *mesh_file = "../data/beam-tet.mesh";
int ser_ref_levels = 0;
int par_ref_levels = 0;
int order = 2;
bool visualization = true;
double newton_rel_tol = 1e-4;
double newton_abs_tol = 1e-6;
int newton_iter = 500;
double mu = 1.0;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
"Number of times to refine the mesh uniformly in serial.");
args.AddOption(&par_ref_levels, "-rp", "--refine-parallel",
"Number of times to refine the mesh uniformly in parallel.");
args.AddOption(&order, "-o", "--order",
"Order (degree) of the finite elements.");
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.AddOption(&newton_rel_tol, "-rel", "--relative-tolerance",
"Relative tolerance for the Newton solve.");
args.AddOption(&newton_abs_tol, "-abs", "--absolute-tolerance",
"Absolute tolerance for the Newton solve.");
args.AddOption(&newton_iter, "-it", "--newton-iterations",
"Maximum iterations for the Newton solve.");
args.AddOption(&mu, "-mu", "--shear-modulus",
"Shear modulus for the neo-Hookean material.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 3. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral and hexahedral meshes
// with the same code.
Mesh *mesh = new Mesh(mesh_file, 1, 1);
int dim = mesh->Dimension();
// 4. Refine the mesh in serial to increase the resolution. In this example
// we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is
// a command-line parameter.
for (int lev = 0; lev < ser_ref_levels; lev++)
{
mesh->UniformRefinement();
}
// 5. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
delete mesh;
for (int lev = 0; lev < par_ref_levels; lev++)
{
pmesh->UniformRefinement();
}
// 6. Define the shear modulus for the incompressible Neo-Hookean material
ConstantCoefficient c_mu(mu);
// 7. Define the finite element spaces for displacement and pressure
// (Taylor-Hood elements). By default, the displacement (u/x) is a second
// order vector field, while the pressure (p) is a linear scalar function.
H1_FECollection quad_coll(order, dim);
H1_FECollection lin_coll(order-1, dim);
ParFiniteElementSpace R_space(pmesh, &quad_coll, dim, Ordering::byVDIM);
ParFiniteElementSpace W_space(pmesh, &lin_coll);
Array<ParFiniteElementSpace *> spaces(2);
spaces[0] = &R_space;
spaces[1] = &W_space;
HYPRE_Int glob_R_size = R_space.GlobalTrueVSize();
HYPRE_Int glob_W_size = W_space.GlobalTrueVSize();
// 8. Define the Dirichlet conditions (set to boundary attribute 1 and 2)
Array<Array<int> *> ess_bdr(2);
Array<int> ess_bdr_u(R_space.GetMesh()->bdr_attributes.Max());
Array<int> ess_bdr_p(W_space.GetMesh()->bdr_attributes.Max());
ess_bdr_p = 0;
ess_bdr_u = 0;
ess_bdr_u[0] = 1;
ess_bdr_u[1] = 1;
ess_bdr[0] = &ess_bdr_u;
ess_bdr[1] = &ess_bdr_p;
// 9. Print the mesh statistics
if (myid == 0)
{
std::cout << "***********************************************************\n";
std::cout << "dim(u) = " << glob_R_size << "\n";
std::cout << "dim(p) = " << glob_W_size << "\n";
std::cout << "dim(u+p) = " << glob_R_size + glob_W_size << "\n";
std::cout << "***********************************************************\n";
}
// 10. Define the block structure of the solution vector (u then p)
Array<int> block_trueOffsets(3);
block_trueOffsets[0] = 0;
block_trueOffsets[1] = R_space.TrueVSize();
block_trueOffsets[2] = W_space.TrueVSize();
block_trueOffsets.PartialSum();
BlockVector xp(block_trueOffsets);
// 11. Define grid functions for the current configuration, reference
// configuration, final deformation, and pressure
ParGridFunction x_gf(&R_space);
ParGridFunction x_ref(&R_space);
ParGridFunction x_def(&R_space);
ParGridFunction p_gf(&W_space);
VectorFunctionCoefficient deform(dim, InitialDeformation);
VectorFunctionCoefficient refconfig(dim, ReferenceConfiguration);
x_gf.ProjectCoefficient(deform);
x_ref.ProjectCoefficient(refconfig);
p_gf = 0.0;
// 12. Set up the block solution vectors
x_gf.GetTrueDofs(xp.GetBlock(0));
p_gf.GetTrueDofs(xp.GetBlock(1));
// 13. Initialize the incompressible neo-Hookean operator
RubberOperator oper(spaces, ess_bdr, block_trueOffsets,
newton_rel_tol, newton_abs_tol, newton_iter, c_mu);
// 14. Solve the Newton system
oper.Solve(xp);
// 15. Distribute the shared degrees of freedom
x_gf.Distribute(xp.GetBlock(0));
p_gf.Distribute(xp.GetBlock(1));
// 16. Compute the final deformation
subtract(x_gf, x_ref, x_def);
// 17. Visualize the results if requested
socketstream vis_u, vis_p;
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
vis_u.open(vishost, visport);
vis_u.precision(8);
visualize(vis_u, pmesh, &x_gf, &x_def, "Deformation", true);
// Make sure all ranks have sent their 'u' solution before initiating
// another set of GLVis connections (one from each rank):
MPI_Barrier(pmesh->GetComm());
vis_p.open(vishost, visport);
vis_p.precision(8);
visualize(vis_p, pmesh, &x_gf, &p_gf, "Pressure", true);
}
// 18. Save the displaced mesh, the final deformation, and the pressure
{
GridFunction *nodes = &x_gf;
int owns_nodes = 0;
pmesh->SwapNodes(nodes, owns_nodes);
ostringstream mesh_name, pressure_name, deformation_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
pressure_name << "pressure." << setfill('0') << setw(6) << myid;
deformation_name << "deformation." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream pressure_ofs(pressure_name.str().c_str());
pressure_ofs.precision(8);
p_gf.Save(pressure_ofs);
ofstream deformation_ofs(deformation_name.str().c_str());
deformation_ofs.precision(8);
x_def.Save(deformation_ofs);
}
// 19. Free the used memory
delete pmesh;
MPI_Finalize();
return 0;
}
JacobianPreconditioner::JacobianPreconditioner(Array<ParFiniteElementSpace *>
&fes,
Operator &mass,
Array<int> &offsets)
: Solver(offsets[2]), block_trueOffsets(offsets), pressure_mass(&mass)
{
fes.Copy(spaces);
gamma = 0.00001;
// The mass matrix and preconditioner do not change every Newton cycle, so
// we only need to define them once
HypreBoomerAMG *mass_prec_amg = new HypreBoomerAMG();
mass_prec_amg->SetPrintLevel(0);
mass_prec = mass_prec_amg;
CGSolver *mass_pcg_iter = new CGSolver(spaces[0]->GetComm());
mass_pcg_iter->SetRelTol(1e-12);
mass_pcg_iter->SetAbsTol(1e-12);
mass_pcg_iter->SetMaxIter(200);
mass_pcg_iter->SetPrintLevel(0);
mass_pcg_iter->SetPreconditioner(*mass_prec);
mass_pcg_iter->SetOperator(*pressure_mass);
mass_pcg_iter->iterative_mode = false;
mass_pcg = mass_pcg_iter;
// The stiffness matrix does change every Newton cycle, so we will define it
// during SetOperator
stiff_pcg = NULL;
stiff_prec = NULL;
}
void JacobianPreconditioner::Mult(const Vector &k, Vector &y) const
{
// Extract the blocks from the input and output vectors
Vector disp_in(k.GetData() + block_trueOffsets[0],
block_trueOffsets[1]-block_trueOffsets[0]);
Vector pres_in(k.GetData() + block_trueOffsets[1],
block_trueOffsets[2]-block_trueOffsets[1]);
Vector disp_out(y.GetData() + block_trueOffsets[0],
block_trueOffsets[1]-block_trueOffsets[0]);
Vector pres_out(y.GetData() + block_trueOffsets[1],
block_trueOffsets[2]-block_trueOffsets[1]);
Vector temp(block_trueOffsets[1]-block_trueOffsets[0]);
Vector temp2(block_trueOffsets[1]-block_trueOffsets[0]);
// Perform the block elimination for the preconditioner
mass_pcg->Mult(pres_in, pres_out);
pres_out *= -gamma;
jacobian->GetBlock(0,1).Mult(pres_out, temp);
subtract(disp_in, temp, temp2);
stiff_pcg->Mult(temp2, disp_out);
}
void JacobianPreconditioner::SetOperator(const Operator &op)
{
jacobian = (BlockOperator *) &op;
// Initialize the stiffness preconditioner and solver
if (stiff_prec == NULL)
{
HypreBoomerAMG *stiff_prec_amg = new HypreBoomerAMG();
stiff_prec_amg->SetPrintLevel(0);
stiff_prec_amg->SetElasticityOptions(spaces[0]);
stiff_prec = stiff_prec_amg;
GMRESSolver *stiff_pcg_iter = new GMRESSolver(spaces[0]->GetComm());
stiff_pcg_iter->SetRelTol(1e-8);
stiff_pcg_iter->SetAbsTol(1e-8);
stiff_pcg_iter->SetMaxIter(200);
stiff_pcg_iter->SetPrintLevel(0);
stiff_pcg_iter->SetPreconditioner(*stiff_prec);
stiff_pcg_iter->iterative_mode = false;
stiff_pcg = stiff_pcg_iter;
}
// At each Newton cycle, compute the new stiffness AMG preconditioner by
// updating the iterative solver which, in turn, updates its preconditioner
stiff_pcg->SetOperator(jacobian->GetBlock(0,0));
}
JacobianPreconditioner::~JacobianPreconditioner()
{
delete mass_pcg;
delete mass_prec;
delete stiff_prec;
delete stiff_pcg;
}
RubberOperator::RubberOperator(Array<ParFiniteElementSpace *> &fes,
Array<Array<int> *> &ess_bdr,
Array<int> &trueOffsets,
double rel_tol,
double abs_tol,
int iter,
Coefficient &c_mu)
: Operator(fes[0]->TrueVSize() + fes[1]->TrueVSize()),
newton_solver(fes[0]->GetComm()), mu(c_mu), block_trueOffsets(trueOffsets)
{
Array<Vector *> rhs(2);
rhs = NULL; // Set all entries in the array
fes.Copy(spaces);
// Define the block nonlinear form
Hform = new ParBlockNonlinearForm(spaces);
// Add the incompressible neo-Hookean integrator
Hform->AddDomainIntegrator(new IncompressibleNeoHookeanIntegrator(mu));
// Set the essential boundary conditions
Hform->SetEssentialBC(ess_bdr, rhs);
// Compute the pressure mass stiffness matrix
ParBilinearForm *a = new ParBilinearForm(spaces[1]);
ConstantCoefficient one(1.0);
OperatorHandle mass(Operator::Hypre_ParCSR);
a->AddDomainIntegrator(new MassIntegrator(one));
a->Assemble();
a->Finalize();
a->ParallelAssemble(mass);
delete a;
mass.SetOperatorOwner(false);
pressure_mass = mass.Ptr();
// Initialize the Jacobian preconditioner
JacobianPreconditioner *jac_prec =
new JacobianPreconditioner(fes, *pressure_mass, block_trueOffsets);
j_prec = jac_prec;
// Set up the Jacobian solver
GMRESSolver *j_gmres = new GMRESSolver(spaces[0]->GetComm());
j_gmres->iterative_mode = false;
j_gmres->SetRelTol(1e-12);
j_gmres->SetAbsTol(1e-12);
j_gmres->SetMaxIter(300);
j_gmres->SetPrintLevel(0);
j_gmres->SetPreconditioner(*j_prec);
j_solver = j_gmres;
// Set the newton solve parameters
newton_solver.iterative_mode = true;
newton_solver.SetSolver(*j_solver);
newton_solver.SetOperator(*this);
newton_solver.SetPrintLevel(1);
newton_solver.SetRelTol(rel_tol);
newton_solver.SetAbsTol(abs_tol);
newton_solver.SetMaxIter(iter);
}
// Solve the Newton system
void RubberOperator::Solve(Vector &xp) const
{
Vector zero;
newton_solver.Mult(zero, xp);
MFEM_VERIFY(newton_solver.GetConverged(),
"Newton Solver did not converge.");
}
// compute: y = H(x,p)
void RubberOperator::Mult(const Vector &k, Vector &y) const
{
Hform->Mult(k, y);
}
// Compute the Jacobian from the nonlinear form
Operator &RubberOperator::GetGradient(const Vector &xp) const
{
return Hform->GetGradient(xp);
}
RubberOperator::~RubberOperator()
{
delete Hform;
delete pressure_mass;
delete j_solver;
delete j_prec;
}
// Inline visualization
void visualize(ostream &out, ParMesh *mesh, ParGridFunction *deformed_nodes,
ParGridFunction *field, const char *field_name, bool init_vis)
{
if (!out)
{
return;
}
GridFunction *nodes = deformed_nodes;
int owns_nodes = 0;
mesh->SwapNodes(nodes, owns_nodes);
out << "parallel " << mesh->GetNRanks() << " " << mesh->GetMyRank() << "\n";
out << "solution\n" << *mesh << *field;
mesh->SwapNodes(nodes, owns_nodes);
if (init_vis)
{
out << "window_size 800 800\n";
out << "window_title '" << field_name << "'\n";
if (mesh->SpaceDimension() == 2)
{
out << "view 0 0\n"; // view from top
out << "keys jlA\n"; // turn off perspective and light, +anti-aliasing
}
out << "keys cmA\n"; // show colorbar and mesh, +anti-aliasing
out << "autoscale value\n"; // update value-range; keep mesh-extents fixed
}
out << flush;
}
void ReferenceConfiguration(const Vector &x, Vector &y)
{
// Set the reference, stress free, configuration
y = x;
}
void InitialDeformation(const Vector &x, Vector &y)
{
// Set the initial configuration. Having this different from the reference
// configuration can help convergence
y = x;
y[1] = x[1] + 0.25*x[0];
}
| 32.627319 | 83 | 0.647457 | [
"mesh",
"geometry",
"vector",
"model"
] |
33745fe634144d27a35c985f9cde04f512efcbcf | 2,782 | hpp | C++ | AOS/include/DNA.hpp | thaisacs/oi-dbt | 8637bc5dbb74d6a32debeef483c8d347c3591d0a | [
"MIT"
] | null | null | null | AOS/include/DNA.hpp | thaisacs/oi-dbt | 8637bc5dbb74d6a32debeef483c8d347c3591d0a | [
"MIT"
] | null | null | null | AOS/include/DNA.hpp | thaisacs/oi-dbt | 8637bc5dbb74d6a32debeef483c8d347c3591d0a | [
"MIT"
] | 1 | 2019-08-15T17:56:09.000Z | 2019-08-15T17:56:09.000Z | #pragma once
#include <codeAnalyzer.hpp>
#include <AOSParams.hpp>
#include <searchSpace.hpp>
#include <util.hpp>
#include <vector>
#include <iostream>
#include <memory>
namespace dbt {
class DNA {
protected:
std::unique_ptr<CodeAnalyzer> CA;
std::vector<uint16_t> Gene;
uint64_t ExecutionTime, CompilationTime, Fitness;
double CompilationWeight, ExecutionWeight;
public:
DNA(double, double, std::vector<uint16_t>);
DNA(unsigned, unsigned, double, double, InitialSearchSpaceType);
void calculateFitness(std::unique_ptr<llvm::Module>, unsigned, const std::string&,
const std::string&, const std::string&);
uint16_t getLocus(unsigned);
std::vector<uint16_t> getGene();
double getFitness();
void setFitness(double);
void setCompilationTime(double);
double getCompilationTime();
void setExecutionTime(double);
double getExecutionTime();
};
class GADNA : public DNA {
double Probability;
public:
GADNA(double CW, double EW, std::vector<uint16_t> Gene) :
DNA(CW, EW, std::move(Gene)) {}
GADNA(unsigned Size, unsigned Min, double CompilationWeight, double ExecutionWeight,
InitialSearchSpaceType Type) :
DNA(Size, Min, CompilationWeight, ExecutionWeight, Type), Probability(0) {}
double getProbability();
void setProbability(double);
GADNA* crossover(GADNA*);
void mutate(double);
GADNA* clone();
void calculateProbability(uint64_t);
void print(const std::string&, const std::string&, const std::string&);
};
class RMHCDNA : public DNA {
public:
RMHCDNA(double CW, double EW, std::vector<uint16_t> Gene) :
DNA(CW, EW, std::move(Gene)) {}
RMHCDNA(unsigned Size, unsigned Min, double CompilationWeight, double ExecutionWeight,
InitialSearchSpaceType Type) :
DNA(Size, Min, CompilationWeight, ExecutionWeight, Type) {}
RMHCDNA* clone();
void mutate();
void print(const std::string&, const std::string&, const std::string&);
};
class SRMHCDNA : public DNA {
public:
SRMHCDNA(std::vector<uint16_t> Gene) :
DNA(0, 0, std::move(Gene)) {}
SRMHCDNA(unsigned Size, unsigned Min, InitialSearchSpaceType Type) :
DNA(Size, Min, 0, 0, Type) {}
void mutate();
SRMHCDNA* clone();
void print(const std::string&, const std::string&, const std::string&);
};
class RANDOMDNA : public DNA {
public:
RANDOMDNA(std::vector<uint16_t> Gene) :
DNA(0, 0, std::move(Gene)) {}
RANDOMDNA(unsigned Size, unsigned Min, InitialSearchSpaceType Type) :
DNA(Size, Min, 0, 0, Type) {}
void mutate();
RANDOMDNA* clone();
void print(const std::string&, const std::string&, const std::string&);
};
}
| 29.284211 | 91 | 0.659597 | [
"vector"
] |
3378e9979d479d658dd8bf65be5201b7e9fa8fef | 44,960 | cc | C++ | chrome/browser/chromeos/login/existing_user_controller.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/login/existing_user_controller.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/login/existing_user_controller.cc | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-04-04T13:34:56.000Z | 2020-11-04T07:17:52.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/chromeos/login/existing_user_controller.h"
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/boot_times_recorder.h"
#include "chrome/browser/chromeos/customization/customization_document.h"
#include "chrome/browser/chromeos/login/auth/chrome_login_performer.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/session/user_session_manager.h"
#include "chrome/browser/chromeos/login/signin_specifics.h"
#include "chrome/browser/chromeos/login/startup_utils.h"
#include "chrome/browser/chromeos/login/ui/login_display_host.h"
#include "chrome/browser/chromeos/login/ui/user_adding_screen.h"
#include "chrome/browser/chromeos/login/user_flow.h"
#include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
#include "chrome/browser/chromeos/policy/device_local_account.h"
#include "chrome/browser/chromeos/policy/device_local_account_policy_service.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/system/device_disabling_manager.h"
#include "chrome/browser/signin/easy_unlock_service.h"
#include "chrome/browser/ui/ash/accessibility/automation_manager_ash.h"
#include "chrome/browser/ui/webui/chromeos/login/l10n_util.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power_manager_client.h"
#include "chromeos/dbus/session_manager_client.h"
#include "chromeos/login/user_names.h"
#include "chromeos/settings/cros_settings_names.h"
#include "components/google/core/browser/google_util.h"
#include "components/policy/core/common/cloud/cloud_policy_core.h"
#include "components/policy/core/common/cloud/cloud_policy_store.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/core/common/policy_service.h"
#include "components/policy/core/common/policy_types.h"
#include "components/user_manager/user_manager.h"
#include "components/user_manager/user_type.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/user_metrics.h"
#include "google_apis/gaia/gaia_auth_util.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/http/http_auth_cache.h"
#include "net/http/http_network_session.h"
#include "net/http/http_transaction_factory.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"
#include "policy/policy_constants.h"
#include "ui/accessibility/ax_enums.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/widget/widget.h"
namespace chromeos {
namespace {
// URL for account creation.
const char kCreateAccountURL[] =
"https://accounts.google.com/NewAccount?service=mail";
// Delay for transferring the auth cache to the system profile.
const long int kAuthCacheTransferDelayMs = 2000;
// Delay for restarting the ui if safe-mode login has failed.
const long int kSafeModeRestartUiDelayMs = 30000;
// Makes a call to the policy subsystem to reload the policy when we detect
// authentication change.
void RefreshPoliciesOnUIThread() {
if (g_browser_process->policy_service())
g_browser_process->policy_service()->RefreshPolicies(base::Closure());
}
// Copies any authentication details that were entered in the login profile in
// the mail profile to make sure all subsystems of Chrome can access the network
// with the provided authentication which are possibly for a proxy server.
void TransferContextAuthenticationsOnIOThread(
net::URLRequestContextGetter* default_profile_context_getter,
net::URLRequestContextGetter* browser_process_context_getter) {
net::HttpAuthCache* new_cache =
browser_process_context_getter->GetURLRequestContext()->
http_transaction_factory()->GetSession()->http_auth_cache();
net::HttpAuthCache* old_cache =
default_profile_context_getter->GetURLRequestContext()->
http_transaction_factory()->GetSession()->http_auth_cache();
new_cache->UpdateAllFrom(*old_cache);
VLOG(1) << "Main request context populated with authentication data.";
// Last but not least tell the policy subsystem to refresh now as it might
// have been stuck until now too.
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&RefreshPoliciesOnUIThread));
}
// Record UMA for password login of regular user when Easy sign-in is enabled.
void RecordPasswordLoginEvent(const UserContext& user_context) {
EasyUnlockService* easy_unlock_service =
EasyUnlockService::Get(ProfileHelper::GetSigninProfile());
if (user_context.GetUserType() == user_manager::USER_TYPE_REGULAR &&
user_context.GetAuthFlow() == UserContext::AUTH_FLOW_OFFLINE &&
easy_unlock_service) {
easy_unlock_service->RecordPasswordLoginEvent(user_context.GetUserID());
}
}
bool CanShowDebuggingFeatures() {
// We need to be on the login screen and in dev mode to show this menu item.
return base::CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kSystemDevMode) &&
base::CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kLoginManager) &&
!user_manager::UserManager::Get()->IsSessionStarted();
}
} // namespace
// static
ExistingUserController* ExistingUserController::current_controller_ = NULL;
////////////////////////////////////////////////////////////////////////////////
// ExistingUserController, public:
ExistingUserController::ExistingUserController(LoginDisplayHost* host)
: auth_status_consumer_(NULL),
host_(host),
login_display_(host_->CreateLoginDisplay(this)),
num_login_attempts_(0),
cros_settings_(CrosSettings::Get()),
offline_failed_(false),
is_login_in_progress_(false),
password_changed_(false),
auth_mode_(LoginPerformer::AUTH_MODE_EXTENSION),
signin_screen_ready_(false),
network_state_helper_(new login::NetworkStateHelper),
weak_factory_(this) {
DCHECK(current_controller_ == NULL);
current_controller_ = this;
registrar_.Add(this,
chrome::NOTIFICATION_USER_LIST_CHANGED,
content::NotificationService::AllSources());
registrar_.Add(this,
chrome::NOTIFICATION_AUTH_SUPPLIED,
content::NotificationService::AllSources());
registrar_.Add(this,
chrome::NOTIFICATION_SESSION_STARTED,
content::NotificationService::AllSources());
show_user_names_subscription_ = cros_settings_->AddSettingsObserver(
kAccountsPrefShowUserNamesOnSignIn,
base::Bind(&ExistingUserController::DeviceSettingsChanged,
base::Unretained(this)));
allow_new_user_subscription_ = cros_settings_->AddSettingsObserver(
kAccountsPrefAllowNewUser,
base::Bind(&ExistingUserController::DeviceSettingsChanged,
base::Unretained(this)));
allow_guest_subscription_ = cros_settings_->AddSettingsObserver(
kAccountsPrefAllowGuest,
base::Bind(&ExistingUserController::DeviceSettingsChanged,
base::Unretained(this)));
allow_supervised_user_subscription_ = cros_settings_->AddSettingsObserver(
kAccountsPrefSupervisedUsersEnabled,
base::Bind(&ExistingUserController::DeviceSettingsChanged,
base::Unretained(this)));
users_subscription_ = cros_settings_->AddSettingsObserver(
kAccountsPrefUsers,
base::Bind(&ExistingUserController::DeviceSettingsChanged,
base::Unretained(this)));
local_account_auto_login_id_subscription_ =
cros_settings_->AddSettingsObserver(
kAccountsPrefDeviceLocalAccountAutoLoginId,
base::Bind(&ExistingUserController::ConfigurePublicSessionAutoLogin,
base::Unretained(this)));
local_account_auto_login_delay_subscription_ =
cros_settings_->AddSettingsObserver(
kAccountsPrefDeviceLocalAccountAutoLoginDelay,
base::Bind(&ExistingUserController::ConfigurePublicSessionAutoLogin,
base::Unretained(this)));
}
void ExistingUserController::Init(const user_manager::UserList& users) {
time_init_ = base::Time::Now();
UpdateLoginDisplay(users);
ConfigurePublicSessionAutoLogin();
}
void ExistingUserController::UpdateLoginDisplay(
const user_manager::UserList& users) {
bool show_users_on_signin;
user_manager::UserList filtered_users;
cros_settings_->GetBoolean(kAccountsPrefShowUserNamesOnSignIn,
&show_users_on_signin);
for (user_manager::UserList::const_iterator it = users.begin();
it != users.end();
++it) {
// TODO(xiyuan): Clean user profile whose email is not in whitelist.
bool meets_supervised_requirements =
(*it)->GetType() != user_manager::USER_TYPE_SUPERVISED ||
user_manager::UserManager::Get()->AreSupervisedUsersAllowed();
bool meets_whitelist_requirements =
CrosSettings::IsWhitelisted((*it)->email(), NULL) ||
!(*it)->HasGaiaAccount();
// Public session accounts are always shown on login screen.
bool meets_show_users_requirements =
show_users_on_signin ||
(*it)->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT;
if (meets_supervised_requirements &&
meets_whitelist_requirements &&
meets_show_users_requirements) {
filtered_users.push_back(*it);
}
}
// If no user pods are visible, fallback to single new user pod which will
// have guest session link.
bool show_guest;
cros_settings_->GetBoolean(kAccountsPrefAllowGuest, &show_guest);
show_users_on_signin |= !filtered_users.empty();
show_guest &= !filtered_users.empty();
bool show_new_user = true;
login_display_->set_parent_window(GetNativeWindow());
login_display_->Init(
filtered_users, show_guest, show_users_on_signin, show_new_user);
host_->OnPreferencesChanged();
}
////////////////////////////////////////////////////////////////////////////////
// ExistingUserController, content::NotificationObserver implementation:
//
void ExistingUserController::Observe(
int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (type == chrome::NOTIFICATION_SESSION_STARTED) {
// Stop listening to any notification once session has started.
// Sign in screen objects are marked for deletion with DeleteSoon so
// make sure no object would be used after session has started.
// http://crbug.com/125276
registrar_.RemoveAll();
return;
}
if (type == chrome::NOTIFICATION_USER_LIST_CHANGED) {
DeviceSettingsChanged();
return;
}
if (type == chrome::NOTIFICATION_AUTH_SUPPLIED) {
// Possibly the user has authenticated against a proxy server and we might
// need the credentials for enrollment and other system requests from the
// main |g_browser_process| request context (see bug
// http://crosbug.com/24861). So we transfer any credentials to the global
// request context here.
// The issue we have here is that the NOTIFICATION_AUTH_SUPPLIED is sent
// just after the UI is closed but before the new credentials were stored
// in the profile. Therefore we have to give it some time to make sure it
// has been updated before we copy it.
VLOG(1) << "Authentication was entered manually, possibly for proxyauth.";
scoped_refptr<net::URLRequestContextGetter> browser_process_context_getter =
g_browser_process->system_request_context();
Profile* signin_profile = ProfileHelper::GetSigninProfile();
scoped_refptr<net::URLRequestContextGetter> signin_profile_context_getter =
signin_profile->GetRequestContext();
DCHECK(browser_process_context_getter.get());
DCHECK(signin_profile_context_getter.get());
content::BrowserThread::PostDelayedTask(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&TransferContextAuthenticationsOnIOThread,
signin_profile_context_getter,
browser_process_context_getter),
base::TimeDelta::FromMilliseconds(kAuthCacheTransferDelayMs));
}
}
////////////////////////////////////////////////////////////////////////////////
// ExistingUserController, private:
ExistingUserController::~ExistingUserController() {
UserSessionManager::GetInstance()->DelegateDeleted(this);
if (current_controller_ == this) {
current_controller_ = NULL;
} else {
NOTREACHED() << "More than one controller are alive.";
}
DCHECK(login_display_.get());
}
////////////////////////////////////////////////////////////////////////////////
// ExistingUserController, LoginDisplay::Delegate implementation:
//
void ExistingUserController::CancelPasswordChangedFlow() {
login_performer_.reset(NULL);
PerformLoginFinishedActions(true /* start public session timer */);
}
void ExistingUserController::CreateAccount() {
content::RecordAction(base::UserMetricsAction("Login.CreateAccount"));
guest_mode_url_ = google_util::AppendGoogleLocaleParam(
GURL(kCreateAccountURL), g_browser_process->GetApplicationLocale());
Login(UserContext(user_manager::USER_TYPE_GUEST, std::string()),
SigninSpecifics());
}
void ExistingUserController::CompleteLogin(const UserContext& user_context) {
login_display_->set_signin_completed(true);
if (!host_) {
// Complete login event was generated already from UI. Ignore notification.
return;
}
ContinueLoginIfDeviceNotDisabled(base::Bind(
&ExistingUserController::DoCompleteLogin,
weak_factory_.GetWeakPtr(),
user_context));
}
base::string16 ExistingUserController::GetConnectedNetworkName() {
return network_state_helper_->GetCurrentNetworkName();
}
bool ExistingUserController::IsSigninInProgress() const {
return is_login_in_progress_;
}
void ExistingUserController::Login(const UserContext& user_context,
const SigninSpecifics& specifics) {
ContinueLoginIfDeviceNotDisabled(base::Bind(
&ExistingUserController::DoLogin,
weak_factory_.GetWeakPtr(),
user_context,
specifics));
}
void ExistingUserController::PerformLogin(
const UserContext& user_context,
LoginPerformer::AuthorizationMode auth_mode) {
// TODO(antrim): remove this output once crash reason is found.
LOG(ERROR) << "Setting flow from PerformLogin";
ChromeUserManager::Get()
->GetUserFlow(user_context.GetUserID())
->SetHost(host_);
BootTimesRecorder::Get()->RecordLoginAttempted();
// Use the same LoginPerformer for subsequent login as it has state
// such as Authenticator instance.
if (!login_performer_.get() || num_login_attempts_ <= 1) {
// Only one instance of LoginPerformer should exist at a time.
login_performer_.reset(NULL);
login_performer_.reset(new ChromeLoginPerformer(this));
}
if (gaia::ExtractDomainName(user_context.GetUserID()) ==
chromeos::login::kSupervisedUserDomain) {
login_performer_->LoginAsSupervisedUser(user_context);
} else {
login_performer_->PerformLogin(user_context, auth_mode);
RecordPasswordLoginEvent(user_context);
}
SendAccessibilityAlert(
l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_LOGIN_SIGNING_IN));
}
void ExistingUserController::MigrateUserData(const std::string& old_password) {
// LoginPerformer instance has state of the user so it should exist.
if (login_performer_.get())
login_performer_->RecoverEncryptedData(old_password);
}
void ExistingUserController::OnSigninScreenReady() {
signin_screen_ready_ = true;
StartPublicSessionAutoLoginTimer();
}
void ExistingUserController::OnStartEnterpriseEnrollment() {
if (KioskAppManager::Get()->IsConsumerKioskDeviceWithAutoLaunch()) {
LOG(WARNING) << "Enterprise enrollment is not available after kiosk auto "
"launch is set.";
return;
}
DeviceSettingsService::Get()->GetOwnershipStatusAsync(
base::Bind(&ExistingUserController::OnEnrollmentOwnershipCheckCompleted,
weak_factory_.GetWeakPtr()));
}
void ExistingUserController::OnStartEnableDebuggingScreen() {
if (CanShowDebuggingFeatures())
ShowEnableDebuggingScreen();
}
void ExistingUserController::OnStartKioskEnableScreen() {
KioskAppManager::Get()->GetConsumerKioskAutoLaunchStatus(
base::Bind(
&ExistingUserController::OnConsumerKioskAutoLaunchCheckCompleted,
weak_factory_.GetWeakPtr()));
}
void ExistingUserController::OnStartKioskAutolaunchScreen() {
ShowKioskAutolaunchScreen();
}
void ExistingUserController::ResyncUserData() {
// LoginPerformer instance has state of the user so it should exist.
if (login_performer_.get())
login_performer_->ResyncEncryptedData();
}
void ExistingUserController::SetDisplayEmail(const std::string& email) {
display_email_ = email;
}
void ExistingUserController::ShowWrongHWIDScreen() {
host_->StartWizard(WizardController::kWrongHWIDScreenName);
}
void ExistingUserController::Signout() {
NOTREACHED();
}
void ExistingUserController::OnConsumerKioskAutoLaunchCheckCompleted(
KioskAppManager::ConsumerKioskAutoLaunchStatus status) {
if (status == KioskAppManager::CONSUMER_KIOSK_AUTO_LAUNCH_CONFIGURABLE)
ShowKioskEnableScreen();
}
void ExistingUserController::OnEnrollmentOwnershipCheckCompleted(
DeviceSettingsService::OwnershipStatus status) {
if (status == DeviceSettingsService::OWNERSHIP_NONE) {
ShowEnrollmentScreen();
} else if (status == DeviceSettingsService::OWNERSHIP_TAKEN) {
// On a device that is already owned we might want to allow users to
// re-enroll if the policy information is invalid.
CrosSettingsProvider::TrustedStatus trusted_status =
CrosSettings::Get()->PrepareTrustedValues(
base::Bind(
&ExistingUserController::OnEnrollmentOwnershipCheckCompleted,
weak_factory_.GetWeakPtr(), status));
if (trusted_status == CrosSettingsProvider::PERMANENTLY_UNTRUSTED) {
ShowEnrollmentScreen();
}
} else {
// OwnershipService::GetStatusAsync is supposed to return either
// OWNERSHIP_NONE or OWNERSHIP_TAKEN.
NOTREACHED();
}
}
void ExistingUserController::ShowEnrollmentScreen() {
host_->StartWizard(WizardController::kEnrollmentScreenName);
}
void ExistingUserController::ShowResetScreen() {
host_->StartWizard(WizardController::kResetScreenName);
}
void ExistingUserController::ShowEnableDebuggingScreen() {
host_->StartWizard(WizardController::kEnableDebuggingScreenName);
}
void ExistingUserController::ShowKioskEnableScreen() {
host_->StartWizard(WizardController::kKioskEnableScreenName);
}
void ExistingUserController::ShowKioskAutolaunchScreen() {
host_->StartWizard(WizardController::kKioskAutolaunchScreenName);
}
void ExistingUserController::ShowTPMError() {
login_display_->SetUIEnabled(false);
login_display_->ShowErrorScreen(LoginDisplay::TPM_ERROR);
}
////////////////////////////////////////////////////////////////////////////////
// ExistingUserController, LoginPerformer::Delegate implementation:
//
void ExistingUserController::OnAuthFailure(const AuthFailure& failure) {
offline_failed_ = true;
guest_mode_url_ = GURL::EmptyGURL();
std::string error = failure.GetErrorString();
PerformLoginFinishedActions(false /* don't start public session timer */);
if (ChromeUserManager::Get()
->GetUserFlow(last_login_attempt_username_)
->HandleLoginFailure(failure)) {
return;
}
if (failure.reason() == AuthFailure::OWNER_REQUIRED) {
ShowError(IDS_LOGIN_ERROR_OWNER_REQUIRED, error);
content::BrowserThread::PostDelayedTask(
content::BrowserThread::UI, FROM_HERE,
base::Bind(&SessionManagerClient::StopSession,
base::Unretained(DBusThreadManager::Get()->
GetSessionManagerClient())),
base::TimeDelta::FromMilliseconds(kSafeModeRestartUiDelayMs));
} else if (failure.reason() == AuthFailure::TPM_ERROR) {
ShowTPMError();
} else if (!online_succeeded_for_.empty()) {
ShowGaiaPasswordChanged(online_succeeded_for_);
} else if (last_login_attempt_username_ == chromeos::login::kGuestUserName) {
// Show no errors, just re-enable input.
login_display_->ClearAndEnablePassword();
StartPublicSessionAutoLoginTimer();
} else {
// Check networking after trying to login in case user is
// cached locally or the local admin account.
bool is_known_user = user_manager::UserManager::Get()->IsKnownUser(
last_login_attempt_username_);
if (!network_state_helper_->IsConnected()) {
if (is_known_user)
ShowError(IDS_LOGIN_ERROR_AUTHENTICATING, error);
else
ShowError(IDS_LOGIN_ERROR_OFFLINE_FAILED_NETWORK_NOT_CONNECTED, error);
} else {
// TODO(nkostylev): Cleanup rest of ClientLogin related code.
if (failure.reason() == AuthFailure::NETWORK_AUTH_FAILED &&
failure.error().state() ==
GoogleServiceAuthError::HOSTED_NOT_ALLOWED) {
ShowError(IDS_LOGIN_ERROR_AUTHENTICATING_HOSTED, error);
} else {
if (!is_known_user)
ShowError(IDS_LOGIN_ERROR_AUTHENTICATING_NEW, error);
else
ShowError(IDS_LOGIN_ERROR_AUTHENTICATING, error);
}
}
login_display_->ClearAndEnablePassword();
StartPublicSessionAutoLoginTimer();
}
// Reset user flow to default, so that special flow will not affect next
// attempt.
ChromeUserManager::Get()->ResetUserFlow(last_login_attempt_username_);
if (auth_status_consumer_)
auth_status_consumer_->OnAuthFailure(failure);
// Clear the recorded displayed email so it won't affect any future attempts.
display_email_.clear();
}
void ExistingUserController::OnAuthSuccess(const UserContext& user_context) {
is_login_in_progress_ = false;
offline_failed_ = false;
login_display_->set_signin_completed(true);
// Login performer will be gone so cache this value to use
// once profile is loaded.
password_changed_ = login_performer_->password_changed();
auth_mode_ = login_performer_->auth_mode();
ChromeUserManager::Get()
->GetUserFlow(user_context.GetUserID())
->HandleLoginSuccess(user_context);
StopPublicSessionAutoLoginTimer();
const bool has_auth_cookies =
login_performer_->auth_mode() == LoginPerformer::AUTH_MODE_EXTENSION &&
user_context.GetAuthCode().empty();
// LoginPerformer instance will delete itself in case of successful auth.
login_performer_->set_delegate(NULL);
ignore_result(login_performer_.release());
UserSessionManager::StartSessionType start_session_type =
UserAddingScreen::Get()->IsRunning()
? UserSessionManager::SECONDARY_USER_SESSION
: UserSessionManager::PRIMARY_USER_SESSION;
UserSessionManager::GetInstance()->StartSession(
user_context, start_session_type, has_auth_cookies,
false, // Start session for user.
this);
// Update user's displayed email.
if (!display_email_.empty()) {
user_manager::UserManager::Get()->SaveUserDisplayEmail(
user_context.GetUserID(), display_email_);
display_email_.clear();
}
}
void ExistingUserController::OnProfilePrepared(Profile* profile,
bool browser_launched) {
// Reenable clicking on other windows and status area.
login_display_->SetUIEnabled(true);
if (browser_launched)
host_ = NULL;
// Inform |auth_status_consumer_| about successful login.
// TODO(nkostylev): Pass UserContext back crbug.com/424550
if (auth_status_consumer_) {
auth_status_consumer_->
OnAuthSuccess(UserContext(last_login_attempt_username_));
}
}
void ExistingUserController::OnOffTheRecordAuthSuccess() {
is_login_in_progress_ = false;
offline_failed_ = false;
// Mark the device as registered., i.e. the second part of OOBE as completed.
if (!StartupUtils::IsDeviceRegistered())
StartupUtils::MarkDeviceRegistered(base::Closure());
UserSessionManager::GetInstance()->CompleteGuestSessionLogin(guest_mode_url_);
if (auth_status_consumer_)
auth_status_consumer_->OnOffTheRecordAuthSuccess();
}
void ExistingUserController::OnPasswordChangeDetected() {
is_login_in_progress_ = false;
offline_failed_ = false;
// Must not proceed without signature verification.
if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues(
base::Bind(&ExistingUserController::OnPasswordChangeDetected,
weak_factory_.GetWeakPtr()))) {
// Value of owner email is still not verified.
// Another attempt will be invoked after verification completion.
return;
}
if (ChromeUserManager::Get()
->GetUserFlow(last_login_attempt_username_)
->HandlePasswordChangeDetected()) {
return;
}
// True if user has already made an attempt to enter old password and failed.
bool show_invalid_old_password_error =
login_performer_->password_changed_callback_count() > 1;
// Note: We allow owner using "full sync" mode which will recreate
// cryptohome and deal with owner private key being lost. This also allows
// us to recover from a lost owner password/homedir.
// TODO(gspencer): We shouldn't have to erase stateful data when
// doing this. See http://crosbug.com/9115 http://crosbug.com/7792
login_display_->ShowPasswordChangedDialog(show_invalid_old_password_error);
if (auth_status_consumer_)
auth_status_consumer_->OnPasswordChangeDetected();
display_email_.clear();
}
void ExistingUserController::WhiteListCheckFailed(const std::string& email) {
PerformLoginFinishedActions(true /* start public session timer */);
offline_failed_ = false;
if (g_browser_process->platform_part()
->browser_policy_connector_chromeos()
->IsEnterpriseManaged()) {
ShowError(IDS_ENTERPRISE_LOGIN_ERROR_WHITELIST, email);
} else {
ShowError(IDS_LOGIN_ERROR_WHITELIST, email);
}
login_display_->ShowSigninUI(email);
if (auth_status_consumer_) {
auth_status_consumer_->OnAuthFailure(
AuthFailure(AuthFailure::WHITELIST_CHECK_FAILED));
}
display_email_.clear();
}
void ExistingUserController::PolicyLoadFailed() {
ShowError(IDS_LOGIN_ERROR_OWNER_KEY_LOST, "");
PerformLoginFinishedActions(false /* don't start public session timer */);
offline_failed_ = false;
display_email_.clear();
}
void ExistingUserController::OnOnlineChecked(const std::string& username,
bool success) {
if (success && last_login_attempt_username_ == username) {
online_succeeded_for_ = username;
// Wait for login attempt to end, if it hasn't yet.
if (offline_failed_ && !is_login_in_progress_)
ShowGaiaPasswordChanged(username);
}
}
////////////////////////////////////////////////////////////////////////////////
// ExistingUserController, private:
void ExistingUserController::DeviceSettingsChanged() {
// If login was already completed, we should avoid any signin screen
// transitions, see http://crbug.com/461604 for example.
if (host_ != NULL && !login_display_->is_signin_completed()) {
// Signed settings or user list changed. Notify views and update them.
UpdateLoginDisplay(user_manager::UserManager::Get()->GetUsers());
ConfigurePublicSessionAutoLogin();
}
}
LoginPerformer::AuthorizationMode ExistingUserController::auth_mode() const {
if (login_performer_)
return login_performer_->auth_mode();
return auth_mode_;
}
bool ExistingUserController::password_changed() const {
if (login_performer_)
return login_performer_->password_changed();
return password_changed_;
}
void ExistingUserController::LoginAsGuest() {
PerformPreLoginActions(UserContext(user_manager::USER_TYPE_GUEST,
chromeos::login::kGuestUserName));
bool allow_guest;
cros_settings_->GetBoolean(kAccountsPrefAllowGuest, &allow_guest);
if (!allow_guest) {
// Disallowed. The UI should normally not show the guest pod but if for some
// reason this has been made available to the user here is the time to tell
// this nicely.
if (g_browser_process->platform_part()
->browser_policy_connector_chromeos()
->IsEnterpriseManaged()) {
login_display_->ShowError(IDS_ENTERPRISE_LOGIN_ERROR_WHITELIST, 1,
HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
} else {
login_display_->ShowError(IDS_LOGIN_ERROR_WHITELIST, 1,
HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
}
PerformLoginFinishedActions(true /* start public session timer */);
display_email_.clear();
return;
}
// Only one instance of LoginPerformer should exist at a time.
login_performer_.reset(NULL);
login_performer_.reset(new ChromeLoginPerformer(this));
login_performer_->LoginOffTheRecord();
SendAccessibilityAlert(
l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_LOGIN_SIGNIN_OFFRECORD));
}
void ExistingUserController::LoginAsPublicSession(
const UserContext& user_context) {
PerformPreLoginActions(user_context);
// If there is no public account with the given user ID, logging in is not
// possible.
const user_manager::User* user =
user_manager::UserManager::Get()->FindUser(user_context.GetUserID());
if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) {
PerformLoginFinishedActions(true /* start public session timer */);
return;
}
UserContext new_user_context = user_context;
std::string locale = user_context.GetPublicSessionLocale();
if (locale.empty()) {
// When performing auto-login, no locale is chosen by the user. Check
// whether a list of recommended locales was set by policy. If so, use its
// first entry. Otherwise, |locale| will remain blank, indicating that the
// public session should use the current UI locale.
const policy::PolicyMap::Entry* entry = g_browser_process->platform_part()->
browser_policy_connector_chromeos()->
GetDeviceLocalAccountPolicyService()->
GetBrokerForUser(user_context.GetUserID())->core()->store()->
policy_map().Get(policy::key::kSessionLocales);
base::ListValue const* list = NULL;
if (entry &&
entry->level == policy::POLICY_LEVEL_RECOMMENDED &&
entry->value &&
entry->value->GetAsList(&list)) {
if (list->GetString(0, &locale))
new_user_context.SetPublicSessionLocale(locale);
}
}
if (!locale.empty() &&
new_user_context.GetPublicSessionInputMethod().empty()) {
// When |locale| is set, a suitable keyboard layout should be chosen. In
// most cases, this will already be the case because the UI shows a list of
// keyboard layouts suitable for the |locale| and ensures that one of them
// us selected. However, it is still possible that |locale| is set but no
// keyboard layout was chosen:
// * The list of keyboard layouts is updated asynchronously. If the user
// enters the public session before the list of keyboard layouts for the
// |locale| has been retrieved, the UI will indicate that no keyboard
// layout was chosen.
// * During auto-login, the |locale| is set in this method and a suitable
// keyboard layout must be chosen next.
//
// The list of suitable keyboard layouts is constructed asynchronously. Once
// it has been retrieved, |SetPublicSessionKeyboardLayoutAndLogin| will
// select the first layout from the list and continue login.
GetKeyboardLayoutsForLocale(
base::Bind(
&ExistingUserController::SetPublicSessionKeyboardLayoutAndLogin,
weak_factory_.GetWeakPtr(),
new_user_context),
locale);
return;
}
// The user chose a locale and a suitable keyboard layout or left both unset.
// Login can continue immediately.
LoginAsPublicSessionInternal(new_user_context);
}
void ExistingUserController::LoginAsKioskApp(const std::string& app_id,
bool diagnostic_mode) {
const bool auto_start = false;
host_->StartAppLaunch(app_id, diagnostic_mode, auto_start);
}
void ExistingUserController::ConfigurePublicSessionAutoLogin() {
std::string auto_login_account_id;
cros_settings_->GetString(kAccountsPrefDeviceLocalAccountAutoLoginId,
&auto_login_account_id);
const std::vector<policy::DeviceLocalAccount> device_local_accounts =
policy::GetDeviceLocalAccounts(cros_settings_);
public_session_auto_login_username_.clear();
for (std::vector<policy::DeviceLocalAccount>::const_iterator
it = device_local_accounts.begin();
it != device_local_accounts.end(); ++it) {
if (it->account_id == auto_login_account_id) {
public_session_auto_login_username_ = it->user_id;
break;
}
}
const user_manager::User* user = user_manager::UserManager::Get()->FindUser(
public_session_auto_login_username_);
if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT)
public_session_auto_login_username_.clear();
if (!cros_settings_->GetInteger(
kAccountsPrefDeviceLocalAccountAutoLoginDelay,
&public_session_auto_login_delay_)) {
public_session_auto_login_delay_ = 0;
}
if (!public_session_auto_login_username_.empty())
StartPublicSessionAutoLoginTimer();
else
StopPublicSessionAutoLoginTimer();
}
void ExistingUserController::ResetPublicSessionAutoLoginTimer() {
// Only restart the auto-login timer if it's already running.
if (auto_login_timer_ && auto_login_timer_->IsRunning()) {
StopPublicSessionAutoLoginTimer();
StartPublicSessionAutoLoginTimer();
}
}
void ExistingUserController::OnPublicSessionAutoLoginTimerFire() {
CHECK(signin_screen_ready_ && !public_session_auto_login_username_.empty());
Login(UserContext(user_manager::USER_TYPE_PUBLIC_ACCOUNT,
public_session_auto_login_username_),
SigninSpecifics());
}
void ExistingUserController::StopPublicSessionAutoLoginTimer() {
if (auto_login_timer_)
auto_login_timer_->Stop();
}
void ExistingUserController::StartPublicSessionAutoLoginTimer() {
if (!signin_screen_ready_ ||
is_login_in_progress_ ||
public_session_auto_login_username_.empty()) {
return;
}
// Start the auto-login timer.
if (!auto_login_timer_)
auto_login_timer_.reset(new base::OneShotTimer<ExistingUserController>);
auto_login_timer_->Start(
FROM_HERE,
base::TimeDelta::FromMilliseconds(
public_session_auto_login_delay_),
base::Bind(
&ExistingUserController::OnPublicSessionAutoLoginTimerFire,
weak_factory_.GetWeakPtr()));
}
gfx::NativeWindow ExistingUserController::GetNativeWindow() const {
return host_->GetNativeWindow();
}
void ExistingUserController::ShowError(int error_id,
const std::string& details) {
// TODO(dpolukhin): show detailed error info. |details| string contains
// low level error info that is not localized and even is not user friendly.
// For now just ignore it because error_text contains all required information
// for end users, developers can see details string in Chrome logs.
VLOG(1) << details;
HelpAppLauncher::HelpTopic help_topic_id;
bool is_offline = !network_state_helper_->IsConnected();
switch (login_performer_->error().state()) {
case GoogleServiceAuthError::CONNECTION_FAILED:
help_topic_id = HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT_OFFLINE;
break;
case GoogleServiceAuthError::ACCOUNT_DISABLED:
help_topic_id = HelpAppLauncher::HELP_ACCOUNT_DISABLED;
break;
case GoogleServiceAuthError::HOSTED_NOT_ALLOWED:
help_topic_id = HelpAppLauncher::HELP_HOSTED_ACCOUNT;
break;
default:
help_topic_id = is_offline ?
HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT_OFFLINE :
HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT;
break;
}
if (error_id == IDS_LOGIN_ERROR_AUTHENTICATING) {
if (num_login_attempts_ > 1) {
const user_manager::User* user =
user_manager::UserManager::Get()->FindUser(
last_login_attempt_username_);
if (user && (user->GetType() == user_manager::USER_TYPE_SUPERVISED))
error_id = IDS_LOGIN_ERROR_AUTHENTICATING_2ND_TIME_SUPERVISED;
}
}
login_display_->ShowError(error_id, num_login_attempts_, help_topic_id);
}
void ExistingUserController::ShowGaiaPasswordChanged(
const std::string& username) {
// Invalidate OAuth token, since it can't be correct after password is
// changed.
user_manager::UserManager::Get()->SaveUserOAuthStatus(
username, user_manager::User::OAUTH2_TOKEN_STATUS_INVALID);
login_display_->SetUIEnabled(true);
login_display_->ShowGaiaPasswordChanged(username);
}
void ExistingUserController::SendAccessibilityAlert(
const std::string& alert_text) {
AutomationManagerAsh::GetInstance()->HandleAlert(
ProfileHelper::GetSigninProfile(), alert_text);
}
void ExistingUserController::SetPublicSessionKeyboardLayoutAndLogin(
const UserContext& user_context,
scoped_ptr<base::ListValue> keyboard_layouts) {
UserContext new_user_context = user_context;
std::string keyboard_layout;
for (size_t i = 0; i < keyboard_layouts->GetSize(); ++i) {
base::DictionaryValue* entry = NULL;
keyboard_layouts->GetDictionary(i, &entry);
bool selected = false;
entry->GetBoolean("selected", &selected);
if (selected) {
entry->GetString("value", &keyboard_layout);
break;
}
}
DCHECK(!keyboard_layout.empty());
new_user_context.SetPublicSessionInputMethod(keyboard_layout);
LoginAsPublicSessionInternal(new_user_context);
}
void ExistingUserController::LoginAsPublicSessionInternal(
const UserContext& user_context) {
// Only one instance of LoginPerformer should exist at a time.
login_performer_.reset(NULL);
login_performer_.reset(new ChromeLoginPerformer(this));
login_performer_->LoginAsPublicSession(user_context);
SendAccessibilityAlert(
l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_LOGIN_SIGNIN_PUBLIC_ACCOUNT));
}
void ExistingUserController::PerformPreLoginActions(
const UserContext& user_context) {
// Disable clicking on other windows and status tray.
login_display_->SetUIEnabled(false);
if (last_login_attempt_username_ != user_context.GetUserID()) {
last_login_attempt_username_ = user_context.GetUserID();
num_login_attempts_ = 0;
// Also reset state variables, which are used to determine password change.
offline_failed_ = false;
online_succeeded_for_.clear();
}
// Guard in cases when we're called twice but login process is still active.
// This might happen when login process is paused till signed settings status
// is verified which results in Login* method called again as a callback.
if (!is_login_in_progress_)
num_login_attempts_++;
is_login_in_progress_ = true;
// Stop the auto-login timer when attempting login.
StopPublicSessionAutoLoginTimer();
}
void ExistingUserController::PerformLoginFinishedActions(
bool start_public_session_timer) {
is_login_in_progress_ = false;
// Reenable clicking on other windows and status area.
login_display_->SetUIEnabled(true);
if (start_public_session_timer)
StartPublicSessionAutoLoginTimer();
}
void ExistingUserController::ContinueLoginIfDeviceNotDisabled(
const base::Closure& continuation) {
// Disable clicking on other windows and status tray.
login_display_->SetUIEnabled(false);
// Stop the auto-login timer.
StopPublicSessionAutoLoginTimer();
// Wait for the |cros_settings_| to become either trusted or permanently
// untrusted.
const CrosSettingsProvider::TrustedStatus status =
cros_settings_->PrepareTrustedValues(base::Bind(
&ExistingUserController::ContinueLoginIfDeviceNotDisabled,
weak_factory_.GetWeakPtr(),
continuation));
if (status == CrosSettingsProvider::TEMPORARILY_UNTRUSTED)
return;
if (status == CrosSettingsProvider::PERMANENTLY_UNTRUSTED) {
// If the |cros_settings_| are permanently untrusted, show an error message
// and refuse to log in.
login_display_->ShowError(IDS_LOGIN_ERROR_OWNER_KEY_LOST,
1,
HelpAppLauncher::HELP_CANT_ACCESS_ACCOUNT);
// Re-enable clicking on other windows and the status area. Do not start the
// auto-login timer though. Without trusted |cros_settings_|, no auto-login
// can succeed.
login_display_->SetUIEnabled(true);
return;
}
bool device_disabled = false;
cros_settings_->GetBoolean(kDeviceDisabled, &device_disabled);
if (device_disabled && system::DeviceDisablingManager::
HonorDeviceDisablingDuringNormalOperation()) {
// If the device is disabled, bail out. A device disabled screen will be
// shown by the DeviceDisablingManager.
// Re-enable clicking on other windows and the status area. Do not start the
// auto-login timer though. On a disabled device, no auto-login can succeed.
login_display_->SetUIEnabled(true);
return;
}
continuation.Run();
}
void ExistingUserController::DoCompleteLogin(const UserContext& user_context) {
PerformPreLoginActions(user_context);
if (!time_init_.is_null()) {
base::TimeDelta delta = base::Time::Now() - time_init_;
UMA_HISTOGRAM_MEDIUM_TIMES("Login.PromptToCompleteLoginTime", delta);
time_init_ = base::Time(); // Reset to null.
}
host_->OnCompleteLogin();
PerformLogin(user_context, LoginPerformer::AUTH_MODE_EXTENSION);
}
void ExistingUserController::DoLogin(const UserContext& user_context,
const SigninSpecifics& specifics) {
if (is_login_in_progress_) {
// If there is another login in progress, bail out. Do not re-enable
// clicking on other windows and the status area. Do not start the
// auto-login timer.
return;
}
if (user_context.GetUserType() != user_manager::USER_TYPE_REGULAR &&
user_manager::UserManager::Get()->IsUserLoggedIn()) {
// Multi-login is only allowed for regular users. If we are attempting to
// do multi-login as another type of user somehow, bail out. Do not
// re-enable clicking on other windows and the status area. Do not start the
// auto-login timer.
return;
}
if (user_context.GetUserType() == user_manager::USER_TYPE_GUEST) {
if (!specifics.guest_mode_url.empty()) {
guest_mode_url_ = GURL(specifics.guest_mode_url);
if (specifics.guest_mode_url_append_locale)
guest_mode_url_ = google_util::AppendGoogleLocaleParam(
guest_mode_url_, g_browser_process->GetApplicationLocale());
}
LoginAsGuest();
return;
}
if (user_context.GetUserType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) {
LoginAsPublicSession(user_context);
return;
}
if (user_context.GetUserType() == user_manager::USER_TYPE_KIOSK_APP) {
LoginAsKioskApp(user_context.GetUserID(), specifics.kiosk_diagnostic_mode);
return;
}
// Regular user or supervised user login.
if (!user_context.HasCredentials()) {
// If credentials are missing, refuse to log in.
// Reenable clicking on other windows and status area.
login_display_->SetUIEnabled(true);
// Restart the auto-login timer.
StartPublicSessionAutoLoginTimer();
}
PerformPreLoginActions(user_context);
PerformLogin(user_context, LoginPerformer::AUTH_MODE_INTERNAL);
}
} // namespace chromeos
| 38.42735 | 80 | 0.730182 | [
"object",
"vector"
] |
337bf1944362c7494808d31aa965233ed3433c5b | 18,726 | cxx | C++ | src/runtime_src/tools/xclbinutil/SectionIPLayout.cxx | Ralender/XRT | ade04554314f6afe3aed99309bfd16868bfce506 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/tools/xclbinutil/SectionIPLayout.cxx | Ralender/XRT | ade04554314f6afe3aed99309bfd16868bfce506 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/tools/xclbinutil/SectionIPLayout.cxx | Ralender/XRT | ade04554314f6afe3aed99309bfd16868bfce506 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located at
*
* http://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 "SectionIPLayout.h"
#include "XclBinUtilities.h"
namespace XUtil = XclBinUtilities;
#include <iostream>
// Static Variables / Classes
SectionIPLayout::_init SectionIPLayout::_initializer;
SectionIPLayout::SectionIPLayout() {
// Empty
}
SectionIPLayout::~SectionIPLayout() {
// Empty
}
const std::string
SectionIPLayout::getIPTypeStr(enum IP_TYPE _ipType) const {
switch (_ipType) {
case IP_MB:
return "IP_MB";
case IP_KERNEL:
return "IP_KERNEL";
case IP_DNASC:
return "IP_DNASC";
case IP_DDR4_CONTROLLER:
return "IP_DDR4_CONTROLLER";
case IP_MEM_DDR4:
return "IP_MEM_DDR4";
case IP_MEM_HBM:
return "IP_MEM_HBM";
}
return XUtil::format("UNKNOWN (%d)", (unsigned int)_ipType);
}
enum IP_TYPE
SectionIPLayout::getIPType(std::string& _sIPType) const {
if (_sIPType == "IP_MB") return IP_MB;
if (_sIPType == "IP_KERNEL") return IP_KERNEL;
if (_sIPType == "IP_DNASC") return IP_DNASC;
if (_sIPType == "IP_DDR4_CONTROLLER") return IP_DDR4_CONTROLLER;
if (_sIPType == "IP_MEM_DDR4") return IP_MEM_DDR4;
if (_sIPType == "IP_MEM_HBM") return IP_MEM_HBM;
std::string errMsg = "ERROR: Unknown IP type: '" + _sIPType + "'";
throw std::runtime_error(errMsg);
}
const std::string
SectionIPLayout::getIPControlTypeStr(enum IP_CONTROL _ipControlType) const {
switch (_ipControlType) {
case AP_CTRL_HS:
return "AP_CTRL_HS";
case AP_CTRL_CHAIN:
return "AP_CTRL_CHAIN";
case AP_CTRL_ME:
return "AP_CTRL_ME";
case AP_CTRL_NONE:
return "AP_CTRL_NONE";
case ACCEL_ADAPTER:
return "ACCEL_ADAPTER";
case FAST_ADAPTER:
return "FAST_ADAPTER";
}
return XUtil::format("UNKNOWN (%d)", (unsigned int) _ipControlType);
}
enum IP_CONTROL
SectionIPLayout::getIPControlType(std::string& _sIPControlType) const {
if (_sIPControlType == "AP_CTRL_HS") return AP_CTRL_HS;
if (_sIPControlType == "AP_CTRL_CHAIN") return AP_CTRL_CHAIN;
if (_sIPControlType == "AP_CTRL_ME") return AP_CTRL_ME;
if (_sIPControlType == "AP_CTRL_NONE") return AP_CTRL_NONE;
if (_sIPControlType == "ACCEL_ADAPTER") return ACCEL_ADAPTER;
if (_sIPControlType == "FAST_ADAPTER") return FAST_ADAPTER;
std::string errMsg = "ERROR: Unknown IP Control type: '" + _sIPControlType + "'";
throw std::runtime_error(errMsg);
}
void
SectionIPLayout::marshalToJSON(char* _pDataSection,
unsigned int _sectionSize,
boost::property_tree::ptree& _ptree) const {
XUtil::TRACE("");
XUtil::TRACE("Extracting: IP_LAYOUT");
XUtil::TRACE_BUF("Section Buffer", reinterpret_cast<const char*>(_pDataSection), _sectionSize);
// Do we have enough room to overlay the header structure
if (_sectionSize < sizeof(ip_layout)) {
throw std::runtime_error(XUtil::format("ERROR: Section size (%d) is smaller than the size of the ip_layout structure (%d)",
_sectionSize, sizeof(ip_layout)));
}
ip_layout* pHdr = (ip_layout*)_pDataSection;
boost::property_tree::ptree ip_layout;
XUtil::TRACE(XUtil::format("m_count: %d", pHdr->m_count));
// Write out the entire structure except for the array structure
XUtil::TRACE_BUF("ip_layout", reinterpret_cast<const char*>(pHdr), ((uint64_t)&(pHdr->m_ip_data[0]) - (uint64_t)pHdr));
ip_layout.put("m_count", XUtil::format("%d", (unsigned int)pHdr->m_count).c_str());
uint64_t expectedSize = ((uint64_t)&(pHdr->m_ip_data[0]) - (uint64_t)pHdr) + (sizeof(ip_data) * pHdr->m_count);
if (_sectionSize != expectedSize) {
throw std::runtime_error(XUtil::format("ERROR: Section size (%d) does not match expected section size (%d).",
_sectionSize, expectedSize));
}
boost::property_tree::ptree m_ip_data;
for (int index = 0; index < pHdr->m_count; ++index) {
boost::property_tree::ptree ip_data;
if (((enum IP_TYPE)pHdr->m_ip_data[index].m_type == IP_MEM_DDR4) ||
((enum IP_TYPE)pHdr->m_ip_data[index].m_type == IP_MEM_HBM)) {
XUtil::TRACE(XUtil::format("[%d]: m_type: %s, m_index: %d, m_pc_index: %d, m_base_address: 0x%lx, m_name: '%s'",
index,
getIPTypeStr((enum IP_TYPE)pHdr->m_ip_data[index].m_type).c_str(),
pHdr->m_ip_data[index].indices.m_index,
pHdr->m_ip_data[index].indices.m_pc_index,
pHdr->m_ip_data[index].m_base_address,
pHdr->m_ip_data[index].m_name));
} else if ((enum IP_TYPE)pHdr->m_ip_data[index].m_type == IP_KERNEL) {
std::string sIPControlType = getIPControlTypeStr((enum IP_CONTROL) ((pHdr->m_ip_data[index].properties & ((uint32_t) IP_CONTROL_MASK)) >> IP_CONTROL_SHIFT));
XUtil::TRACE(XUtil::format("[%d]: m_type: %s, properties: 0x%x {m_ip_control: %s, m_interrupt_id: %d, m_int_enable: %d}, m_base_address: 0x%lx, m_name: '%s'",
index,
getIPTypeStr((enum IP_TYPE)pHdr->m_ip_data[index].m_type).c_str(),
pHdr->m_ip_data[index].properties,
sIPControlType.c_str(),
(pHdr->m_ip_data[index].properties & ((uint32_t) IP_INTERRUPT_ID_MASK)) >> IP_INTERRUPT_ID_SHIFT,
(pHdr->m_ip_data[index].properties & ((uint32_t) IP_INT_ENABLE_MASK)),
pHdr->m_ip_data[index].m_base_address,
pHdr->m_ip_data[index].m_name));
} else {
XUtil::TRACE(XUtil::format("[%d]: m_type: %s, properties: 0x%x, m_base_address: 0x%lx, m_name: '%s'",
index,
getIPTypeStr((enum IP_TYPE)pHdr->m_ip_data[index].m_type).c_str(),
pHdr->m_ip_data[index].properties,
pHdr->m_ip_data[index].m_base_address,
pHdr->m_ip_data[index].m_name));
}
// Write out the entire structure
XUtil::TRACE_BUF("ip_data", reinterpret_cast<const char*>(&(pHdr->m_ip_data[index])), sizeof(ip_data));
ip_data.put("m_type", getIPTypeStr((enum IP_TYPE)pHdr->m_ip_data[index].m_type).c_str());
if (((enum IP_TYPE)pHdr->m_ip_data[index].m_type == IP_MEM_DDR4) ||
((enum IP_TYPE)pHdr->m_ip_data[index].m_type == IP_MEM_HBM)) {
ip_data.put("m_index", XUtil::format("%d", (unsigned int)pHdr->m_ip_data[index].indices.m_index).c_str());
ip_data.put("m_pc_index", XUtil::format("%d", (unsigned int)pHdr->m_ip_data[index].indices.m_pc_index).c_str());
} else if ((enum IP_TYPE)pHdr->m_ip_data[index].m_type == IP_KERNEL) {
ip_data.put("m_int_enable", XUtil::format("%d", (pHdr->m_ip_data[index].properties & ((uint32_t) IP_INT_ENABLE_MASK))).c_str());
ip_data.put("m_interrupt_id", XUtil::format("%d", (pHdr->m_ip_data[index].properties & ((uint32_t) IP_INTERRUPT_ID_MASK)) >> IP_INTERRUPT_ID_SHIFT).c_str());
std::string sIPControlType = getIPControlTypeStr((enum IP_CONTROL) ((pHdr->m_ip_data[index].properties & ((uint32_t) IP_CONTROL_MASK)) >> IP_CONTROL_SHIFT));
ip_data.put("m_ip_control", sIPControlType.c_str());
} else {
ip_data.put("properties", XUtil::format("0x%x", pHdr->m_ip_data[index].properties).c_str());
}
if ( pHdr->m_ip_data[index].m_base_address != ((uint64_t) -1) ) {
ip_data.put("m_base_address", XUtil::format("0x%lx", pHdr->m_ip_data[index].m_base_address).c_str());
} else {
ip_data.put("m_base_address", "not_used");
}
ip_data.put("m_name", XUtil::format("%s", pHdr->m_ip_data[index].m_name).c_str());
m_ip_data.push_back(std::make_pair("", ip_data)); // Used to make an array of objects
}
ip_layout.add_child("m_ip_data", m_ip_data);
_ptree.add_child("ip_layout", ip_layout);
XUtil::TRACE("-----------------------------");
}
void
SectionIPLayout::marshalFromJSON(const boost::property_tree::ptree& _ptSection,
std::ostringstream& _buf) const {
const boost::property_tree::ptree& ptIPLayout = _ptSection.get_child("ip_layout");
// Initialize the memory to zero's
ip_layout ipLayoutHdr = ip_layout {0};
// Read, store, and report mem_topology data
ipLayoutHdr.m_count = ptIPLayout.get<uint32_t>("m_count");
if (ipLayoutHdr.m_count == 0) {
std::cout << "WARNING: Skipping IP_LAYOUT section for count size is zero." << std::endl;
return;
}
XUtil::TRACE("IP_LAYOUT");
XUtil::TRACE(XUtil::format("m_count: %d", ipLayoutHdr.m_count));
// Write out the entire structure except for the mem_data structure
XUtil::TRACE_BUF("ip_layout - minus ip_data", reinterpret_cast<const char*>(&ipLayoutHdr), (sizeof(ip_layout) - sizeof(ip_data)));
_buf.write(reinterpret_cast<const char*>(&ipLayoutHdr), sizeof(ip_layout) - sizeof(ip_data));
// Read, store, and report connection segments
unsigned int count = 0;
boost::property_tree::ptree ipDatas = ptIPLayout.get_child("m_ip_data");
for (const auto& kv : ipDatas) {
ip_data ipDataHdr = ip_data {0};
boost::property_tree::ptree ptIPData = kv.second;
std::string sm_type = ptIPData.get<std::string>("m_type");
ipDataHdr.m_type = getIPType(sm_type);
// For these IPs, the struct indices needs to be initialized
if ((ipDataHdr.m_type == IP_MEM_DDR4) ||
(ipDataHdr.m_type == IP_MEM_HBM))
{
ipDataHdr.indices.m_index = ptIPData.get<uint16_t>("m_index");
ipDataHdr.indices.m_pc_index = ptIPData.get<uint8_t>("m_pc_index", 0);
} else {
// Get the properties value (if one is defined)
std::string sProperties = ptIPData.get<std::string>("properties", "0");
ipDataHdr.properties = (uint32_t)XUtil::stringToUInt64(sProperties);
{ // m_int_enable
boost::optional<bool> bIntEnable;
bIntEnable = ptIPData.get_optional<bool>("m_int_enable");
if (bIntEnable.is_initialized()) {
ipDataHdr.properties = ipDataHdr.properties & (~(uint32_t) IP_INT_ENABLE_MASK); // Clear existing bit
if (bIntEnable.get()) {
ipDataHdr.properties = ipDataHdr.properties | ((uint32_t) IP_INT_ENABLE_MASK); // Set bit
}
}
}
{ // m_interrupt_id
std::string sInterruptID = ptIPData.get<std::string>("m_interrupt_id","");
if (!sInterruptID.empty()) {
unsigned int interruptID = std::stoul(sInterruptID);
unsigned int maxValue = ((unsigned int) IP_INTERRUPT_ID_MASK) >> IP_INTERRUPT_ID_SHIFT;
if (interruptID > maxValue) {
std::string errMsg = XUtil::format("ERROR: The m_interrupt_id (%d), exceeds maximum value (%d).",
interruptID, maxValue);
throw std::runtime_error(errMsg);
}
unsigned int shiftValue = (interruptID << IP_INTERRUPT_ID_SHIFT);
shiftValue = shiftValue & ((uint32_t) IP_INTERRUPT_ID_MASK);
ipDataHdr.properties = ipDataHdr.properties & (~(uint32_t) IP_INTERRUPT_ID_MASK); // Clear existing bits
ipDataHdr.properties = ipDataHdr.properties | shiftValue; // Set bits
}
}
{ // m_ip_control
boost::optional<std::string> bIPControl;
bIPControl = ptIPData.get_optional<std::string>("m_ip_control");
if (bIPControl.is_initialized()) {
unsigned int ipControl = (unsigned int) getIPControlType(bIPControl.get());
unsigned int maxValue = ((unsigned int) IP_CONTROL_MASK) >> IP_CONTROL_SHIFT;
if (ipControl > maxValue) {
std::string errMsg = XUtil::format("ERROR: The m_ip_control (%d), exceeds maximum value (%d).",
(unsigned int) ipControl, maxValue);
throw std::runtime_error(errMsg);
}
unsigned int shiftValue = ipControl << IP_CONTROL_SHIFT;
shiftValue = shiftValue & ((uint32_t) IP_CONTROL_MASK);
ipDataHdr.properties = ipDataHdr.properties & (~(uint32_t) IP_CONTROL_MASK); // Clear existing bits
ipDataHdr.properties = ipDataHdr.properties | shiftValue; // Set bits
}
}
}
std::string sBaseAddress = ptIPData.get<std::string>("m_base_address");
if ( sBaseAddress != "not_used" ) {
ipDataHdr.m_base_address = XUtil::stringToUInt64(sBaseAddress);
}
else {
ipDataHdr.m_base_address = (uint64_t) -1;
}
std::string sm_name = ptIPData.get<std::string>("m_name");
if (sm_name.length() >= sizeof(ip_data::m_name)) {
std::string errMsg = XUtil::format("ERROR: The m_name entry length (%d), exceeds the allocated space (%d). Name: '%s'",
(unsigned int)sm_name.length(), (unsigned int)sizeof(ip_data::m_name), sm_name.c_str());
throw std::runtime_error(errMsg);
}
// We already know that there is enough room for this string
memcpy(ipDataHdr.m_name, sm_name.c_str(), sm_name.length() + 1);
if ((ipDataHdr.m_type == IP_MEM_DDR4) ||
(ipDataHdr.m_type == IP_MEM_HBM)) {
XUtil::TRACE(XUtil::format("[%d]: m_type: %d, m_index: %d, m_pc_index: %d, m_base_address: 0x%lx, m_name: '%s'",
count,
(unsigned int)ipDataHdr.m_type,
(unsigned int)ipDataHdr.indices.m_index,
(unsigned int)ipDataHdr.indices.m_pc_index,
ipDataHdr.m_base_address,
ipDataHdr.m_name));
} else {
XUtil::TRACE(XUtil::format("[%d]: m_type: %d, properties: 0x%x, m_base_address: 0x%lx, m_name: '%s'",
count,
(unsigned int)ipDataHdr.m_type,
(unsigned int)ipDataHdr.properties,
ipDataHdr.m_base_address,
ipDataHdr.m_name));
}
// Write out the entire structure
XUtil::TRACE_BUF("ip_data", reinterpret_cast<const char*>(&ipDataHdr), sizeof(ip_data));
_buf.write(reinterpret_cast<const char*>(&ipDataHdr), sizeof(ip_data));
count++;
}
// -- The counts should match --
if (count != (unsigned int)ipLayoutHdr.m_count) {
std::string errMsg = XUtil::format("ERROR: Number of connection sections (%d) does not match expected encoded value: %d",
(unsigned int)count, (unsigned int)ipLayoutHdr.m_count);
throw std::runtime_error(errMsg);
}
// -- Buffer needs to be less than 64K--
unsigned int bufferSize = (unsigned int) _buf.str().size();
const unsigned int maxBufferSize = 64 * 1024;
if ( bufferSize > maxBufferSize ) {
std::string errMsg = XUtil::format("CRITICAL WARNING: The buffer size for the IP_LAYOUT section (%d) exceed the maximum size of %d.\nThis can result in lose of data in the driver.",
(unsigned int) bufferSize, (unsigned int) maxBufferSize);
std::cout << errMsg << std::endl;
// throw std::runtime_error(errMsg);
}
}
bool
SectionIPLayout::doesSupportAddFormatType(FormatType _eFormatType) const
{
if (_eFormatType == FT_JSON) {
return true;
}
return false;
}
bool
SectionIPLayout::doesSupportDumpFormatType(FormatType _eFormatType) const
{
if ((_eFormatType == FT_JSON) ||
(_eFormatType == FT_HTML) ||
(_eFormatType == FT_RAW))
{
return true;
}
return false;
}
template <typename T>
std::vector<T> as_vector(boost::property_tree::ptree const& pt,
boost::property_tree::ptree::key_type const& key)
{
std::vector<T> r;
for (auto& item : pt.get_child(key))
r.push_back(item.second);
return r;
}
void
SectionIPLayout::appendToSectionMetadata(const boost::property_tree::ptree& _ptAppendData,
boost::property_tree::ptree& _ptToAppendTo)
{
XUtil::TRACE_PrintTree("To Append To", _ptToAppendTo);
XUtil::TRACE_PrintTree("Append data", _ptAppendData);
std::vector<boost::property_tree::ptree> ip_datas = as_vector<boost::property_tree::ptree>(_ptAppendData, "m_ip_data");
unsigned int appendCount = _ptAppendData.get<unsigned int>("m_count");
if (appendCount != ip_datas.size()) {
std::string errMsg = XUtil::format("ERROR: IP layout section to append's count (%d) doesn't match the number of ip_data entries (%d).", appendCount, ip_datas.size());
throw std::runtime_error(errMsg);
}
if (appendCount == 0) {
std::string errMsg = "WARNING: IP layout section doesn't contain any data to append.";
std::cout << errMsg << std::endl;
return;
}
// Now copy the data
boost::property_tree::ptree& ptIPLayoutAppendTo = _ptToAppendTo.get_child("ip_layout");
boost::property_tree::ptree& ptDest_m_ip_data = ptIPLayoutAppendTo.get_child("m_ip_data");
for (auto ip_data : ip_datas) {
boost::property_tree::ptree new_ip_data;
std::string sm_type = ip_data.get<std::string>("m_type");
new_ip_data.put("m_type", sm_type);
if ((getIPType(sm_type) == IP_MEM_DDR4) ||
(getIPType(sm_type) == IP_MEM_HBM)) {
new_ip_data.put("m_index", ip_data.get<std::string>("m_index"));
new_ip_data.put("m_pc_index", ip_data.get<std::string>("m_pc_index", "0"));
} else {
new_ip_data.put("properties", ip_data.get<std::string>("properties"));
}
new_ip_data.put("m_base_address", ip_data.get<std::string>("m_base_address"));
new_ip_data.put("m_name", ip_data.get<std::string>("m_name"));
ptDest_m_ip_data.push_back(std::make_pair("", new_ip_data)); // Used to make an array of objects
}
// Update count
{
unsigned int count = ptIPLayoutAppendTo.get<unsigned int>("m_count");
count += appendCount;
ptIPLayoutAppendTo.put("m_count", count);
}
XUtil::TRACE_PrintTree("To Append To Done", _ptToAppendTo);
}
| 42.080899 | 185 | 0.633504 | [
"vector"
] |
337c4b24e7026878b4b04812ba55d2f64b61d249 | 12,796 | cpp | C++ | src/Image.cpp | VictorQueiroz/silver-engine | 057b5e03a74bbcbf3f7c6f2fd74c52e3a126eb09 | [
"MIT"
] | null | null | null | src/Image.cpp | VictorQueiroz/silver-engine | 057b5e03a74bbcbf3f7c6f2fd74c52e3a126eb09 | [
"MIT"
] | null | null | null | src/Image.cpp | VictorQueiroz/silver-engine | 057b5e03a74bbcbf3f7c6f2fd74c52e3a126eb09 | [
"MIT"
] | null | null | null | #include "Image.h"
#include "TypeConverter.h"
#include "Geometry.h"
#include "Color.h"
using Nan::Set;
using v8::FunctionTemplate;
using v8::Local;
using v8::Value;
Nan::Persistent<v8::Function> Image::constructor;
void Image::Init(v8::Local<v8::Object> exports) {
auto tpl = Nan::New<FunctionTemplate>(New);
tpl->SetClassName(Nan::New("Image").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl,"read",Read);
Nan::SetPrototypeMethod(tpl,"write",Write);
Nan::SetPrototypeMethod(tpl,"composite",Composite);
Nan::SetPrototypeMethod(tpl,"backgroundColor",BackgroundColor);
Nan::SetPrototypeMethod(tpl,"density",Density);
Nan::SetPrototypeMethod(tpl,"magick",Magick);
Nan::SetPrototypeMethod(tpl,"emboss",Emboss);
Nan::SetPrototypeMethod(tpl,"negate",Negate);
Nan::SetPrototypeMethod(tpl,"crop",Crop);
Nan::SetPrototypeMethod(tpl,"compare",Compare);
Nan::SetPrototypeMethod(tpl,"sample",Sample);
Nan::SetPrototypeMethod(tpl,"normalize",Normalize);
Nan::SetPrototypeMethod(tpl,"oilPaint",OilPaint);
Nan::SetPrototypeMethod(tpl,"size",Size);
Nan::SetPrototypeMethod(tpl,"motionBlur",MotionBlur);
Nan::SetPrototypeMethod(tpl,"resize",Resize);
Nan::SetPrototypeMethod(tpl,"shave",Shave);
Nan::SetPrototypeMethod(tpl,"scale",Scale);
Nan::SetPrototypeMethod(tpl,"rotate",Rotate);
Nan::SetPrototypeMethod(tpl,"sample",Sample);
Nan::SetPrototypeMethod(tpl,"scale",Scale);
constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
Set(exports,Nan::New("Image").ToLocalChecked(),Nan::GetFunction(tpl).ToLocalChecked());
}
NAN_METHOD(Image::New) {
auto* img = new Image();
img->Wrap(info.This());
info.GetReturnValue().Set(info.This());
}
NAN_METHOD(Image::Read) {
std::string file;
if(!TypeConverter::GetArgument(info[0],file)) {
Nan::ThrowError("First argument must be a string");
return;
}
auto* img = Unwrap<Image>(info.This());
if(!img) {
Nan::ThrowError("read() called under an invalid context");
return;
}
try {
img->value.read(file);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Write) {
std::string file;
if(!TypeConverter::GetArgument(info[0],file)) {
Nan::ThrowError("First argument must be a string");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("write() called under an invalid context");
return;
}
try {
img->value.write(file);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Crop) {
Geometry* g;
if(!TypeConverter::Unwrap(info[0], &g)) {
Nan::ThrowError("First argument must be a valid instance of the Geometry class");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("crop() called under invalid context");
return;
}
try {
img->value.crop(g->value);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Resize) {
Geometry* g;
if(!TypeConverter::Unwrap(info[0], &g)) {
Nan::ThrowError("First argument must be a valid instance of the Geometry class");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("crop() called under invalid context");
return;
}
try {
img->value.resize(g->value);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Shave) {
Geometry* g;
if(!TypeConverter::Unwrap(info[0], &g)) {
Nan::ThrowError("First argument must be a valid instance of the Geometry class");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.shave(g->value);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::BackgroundColor) {
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("backgroundColor() called under invalid context");
return;
}
Color* color;
if(TypeConverter::Unwrap(info[0],&color)) {
img->value.backgroundColor(color->value);
} else {
v8::Local<v8::Value> argv[] = {
Nan::New(std::string(img->value.backgroundColor())).ToLocalChecked()
};
info.GetReturnValue().Set(Nan::NewInstance(
Nan::New(Color::constructor),
1,
argv
).ToLocalChecked());
}
}
NAN_METHOD(Image::Roll) {
Geometry* g;
if(!TypeConverter::Unwrap(info[0], &g)) {
Nan::ThrowError("First argument must be a valid instance of the Geometry class");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.roll(g->value);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Composite) {
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("composite() called under invalid context");
return;
}
Image* compositeImage;
if(!TypeConverter::Unwrap(info[0],&compositeImage)) {
Nan::ThrowError("First argument must be a valid Image instance");
return;
}
Geometry* g;
if(!TypeConverter::Unwrap(info[1], &g)) {
Nan::ThrowError("Second argument must be a valid instance of the Geometry class");
return;
}
Magick::CompositeOperator compositeOp;
if(!TypeConverter::GetArgument(info[2], compositeOp)) {
compositeOp = Magick::CompositeOperator::InCompositeOp;
}
try {
img->value.composite(compositeImage->value, g->value, compositeOp);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Scale) {
Geometry* g;
if(!TypeConverter::Unwrap(info[0], &g)) {
Nan::ThrowError("First argument must be a valid instance of the Geometry class");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.scale(g->value);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Sample) {
Geometry* g;
if(!TypeConverter::Unwrap(info[0], &g)) {
Nan::ThrowError("First argument must be a valid instance of the Geometry class");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.sample(g->value);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::MotionBlur) {
double radius;
double sigma;
double angle;
if(!TypeConverter::GetArgument(info[0], radius)) {
Nan::ThrowError("First argument must be a valid double-precision integer");
return;
}
if(!TypeConverter::GetArgument(info[1], sigma)) {
Nan::ThrowError("Second argument must be a valid double-precision integer");
return;
}
if(!TypeConverter::GetArgument(info[2], angle)) {
Nan::ThrowError("Third argument must be a valid double-precision integer");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.motionBlur(radius,sigma,angle);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Normalize) {
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.normalize();
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Rotate) {
double degrees;
if(!TypeConverter::GetArgument(info[0], degrees)) {
Nan::ThrowError("First argument must be a valid double-precision integer");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.rotate(degrees);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::OilPaint) {
double radius;
if(!TypeConverter::GetArgument(info[0], radius)) {
Nan::ThrowError("First argument must be a valid double-precision integer");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.oilPaint(radius);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Emboss) {
double radius;
double sigma;
if(!TypeConverter::GetArgument(info[0], radius)) {
Nan::ThrowError("First argument must be a valid double-precision integer");
return;
}
if(!TypeConverter::GetArgument(info[1], sigma)) {
Nan::ThrowError("Second argument must be a valid double-precision integer");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.emboss(radius,sigma);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Negate) {
bool grayscale;
if(!TypeConverter::GetArgument(info[0], grayscale)) {
Nan::ThrowError("First argument must be a valid double-precision integer");
return;
}
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("resize() called under invalid context");
return;
}
try {
img->value.negate(grayscale);
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Compare) {
Image* img, *ref;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("compare() called under invalid context");
return;
}
if(!TypeConverter::Unwrap(info[0],&ref)) {
Nan::ThrowError("compare() called under invalid context");
return;
}
try {
info.GetReturnValue().Set(Nan::New(img->value.compare(ref->value)));
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Magick) {
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("magick() called under invalid context");
return;
}
try {
std::string format;
if(TypeConverter::GetArgument(info[0],format)) {
img->value.magick(format);
} else {
info.GetReturnValue().Set(Nan::New(img->value.magick()).ToLocalChecked());
}
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Density) {
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("density() called under invalid context");
return;
}
try {
Geometry* density;
if(TypeConverter::Unwrap(info[0],&density)) {
img->value.density(density->value);
return;
}
Local<v8::Value> argv[] {
Nan::New(std::string(img->value.density())).ToLocalChecked()
};
info.GetReturnValue().Set(Nan::NewInstance(
Nan::New(Geometry::constructor),
1,
argv
).ToLocalChecked());
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
NAN_METHOD(Image::Size) {
Image* img;
if(!TypeConverter::Unwrap(info.This(),&img)) {
Nan::ThrowError("density() called under invalid context");
return;
}
try {
Geometry* density;
if(TypeConverter::Unwrap(info[0],&density)) {
img->value.size(density->value);
return;
}
Local<v8::Value> argv[] {
Nan::New(std::string(img->value.size())).ToLocalChecked()
};
info.GetReturnValue().Set(Nan::NewInstance(
Nan::New(Geometry::constructor),
1,
argv
).ToLocalChecked());
} catch(std::exception& e) {
Nan::ThrowError(e.what());
}
}
| 28.755056 | 91 | 0.594717 | [
"geometry",
"object"
] |
337cad5bbb6d5f97321c539fbe96543d4ce8def9 | 1,177 | hpp | C++ | shared/include/volume_resource.hpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 13 | 2019-03-25T09:40:12.000Z | 2022-03-13T16:12:39.000Z | shared/include/volume_resource.hpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 110 | 2018-10-16T09:05:43.000Z | 2022-03-16T23:32:28.000Z | shared/include/volume_resource.hpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 1 | 2020-02-06T20:32:50.000Z | 2020-02-06T20:32:50.000Z | #pragma once
#include "magic_number.hpp"
#include "ucfb_writer.hpp"
#include <array>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <span>
#include <string_view>
#include <utility>
#include <vector>
namespace sp {
enum class Volume_resource_type : std::uint32_t {
material,
texture,
fx_config,
colorgrading_regions
};
extern const std::int32_t volume_resource_format;
struct Volume_resource_header {
const Magic_number mn = "spvr"_mn;
Volume_resource_type type;
std::uint32_t payload_size;
std::uint32_t _reserved{};
};
static_assert(sizeof(Volume_resource_header) == 16);
void write_volume_resource(ucfb::File_writer& writer, const std::string_view name,
const Volume_resource_type type,
std::span<const std::byte> data);
void save_volume_resource(const std::filesystem::path& output_path,
const std::string_view name, const Volume_resource_type type,
std::span<const std::byte> data);
auto load_volume_resource(const std::filesystem::path& path)
-> std::pair<Volume_resource_header, std::vector<std::byte>>;
}
| 25.586957 | 87 | 0.693288 | [
"vector"
] |
337d26f82418ffc73f6605aca825336944b8ef2a | 6,680 | inl | C++ | include/uidevice.inl | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 1 | 2021-02-08T20:31:46.000Z | 2021-02-08T20:31:46.000Z | include/uidevice.inl | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | null | null | null | include/uidevice.inl | markjulmar/tsplib3 | f58a281ce43f4d57ef10e24d306fd46e6febcc41 | [
"MIT"
] | 4 | 2019-11-14T03:47:33.000Z | 2021-03-08T01:18:05.000Z | /******************************************************************************/
//
// UIDEVICE.INL - TAPI Service Provider C++ Library header
//
// Copyright (C) 1994-1999 JulMar Entertainment Technology, Inc.
// All rights reserved
//
// The SPLIB classes provide a basis for developing MS-TAPI complient
// Service Providers. They provide basic handling for all of the TSPI
// APIs and a C-based handler which routes all requests through a set of C++
// classes.
//
// This source code is intended only as a supplement to the
// TSP++ Class Library product documentation. This source code cannot
// be used in part or whole in any form outside the TSP++ library.
//
// INLINE FUNCTIONS
//
/******************************************************************************/
#ifndef _UIDEVIC_INL_INC_
#define _UIDEVICE_INL_INC_
#ifndef _NOINLINES_
#define TSP_INLINE inline
#else
#define TSP_INLINE
#endif
///////////////////////////////////////////////////////////////////////////
// CServiceProviderUI::GetProviderInfo
//
// Returns the name of the registry key for storing information
//
TSP_INLINE LPCTSTR CServiceProviderUI::GetProviderInfo() const
{
return m_pszProviderInfo;
}// CServiceProviderUI::GetProviderInfo
///////////////////////////////////////////////////////////////////////////
// CServiceProviderUI::GetDeviceCount
//
// Returns the count of devices
//
TSP_INLINE unsigned int CServiceProviderUI::GetDeviceCount() const
{
return m_arrDevices.GetSize();
}// CServiceProviderUI::GetDeviceCount
///////////////////////////////////////////////////////////////////////////
// CServiceProviderUI::GetDeviceByIndex
//
// Returns a device based on the index
//
TSP_INLINE CTSPUIDevice* CServiceProviderUI::GetDeviceByIndex(unsigned int iPos) const
{
return (iPos < GetDeviceCount()) ?
m_arrDevices[iPos] : NULL;
}// CServiceProviderUI::GetDeviceByIndex
///////////////////////////////////////////////////////////////////////////
// CServiceProviderUI::GetDevice
//
// Returns a device based on the provider id
//
TSP_INLINE CTSPUIDevice* CServiceProviderUI::GetDevice(DWORD dwProviderID) const
{
for (unsigned int i = 0; i < GetDeviceCount(); i++)
{
CTSPUIDevice* pDevice = m_arrDevices[i];
if (pDevice->GetProviderID() == dwProviderID)
return pDevice;
}
return NULL;
}// CServiceProviderUI::GetDevice
///////////////////////////////////////////////////////////////////////////
// CServiceProviderUI::AddDevice
//
// Adds a new device to the provider
//
TSP_INLINE unsigned int CServiceProviderUI::AddDevice(DWORD dwPermProviderID)
{
CTSPUIDevice* pDevice = reinterpret_cast<CTSPUIDevice*>(m_pObjects[0]->CreateObject());
pDevice->m_dwPermProviderID = dwPermProviderID;
return AddDevice(pDevice);
}// CServiceProviderUI::AddDevice
///////////////////////////////////////////////////////////////////////////
// CServiceProviderUI::AddDevice
//
// Adds a new device to the provider
//
TSP_INLINE unsigned int CServiceProviderUI::AddDevice(CTSPUIDevice* pDevice)
{
return m_arrDevices.Add(pDevice);
}// CServiceProviderUI::AddDevice
/******************************************************************************/
//
// CTSPUIDevice class functions
//
/****************************************************************************/
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::CTSPUIDevice
//
// Constructor for the device object
//
TSP_INLINE CTSPUIDevice::CTSPUIDevice() : m_dwPermProviderID(0)
{
}// CTSPUIDevice::CTSPUIDevice
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::CTSPUIDevice
//
// Constructor for the device object
//
TSP_INLINE CTSPUIDevice::CTSPUIDevice(DWORD dwPermProvID) : m_dwPermProviderID(dwPermProvID)
{
}// CTSPUIDevice::CTSPUIDevice
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::GetProviderID
//
// Returns the permanent provider ID for this device
//
TSP_INLINE DWORD CTSPUIDevice::GetProviderID() const
{
return m_dwPermProviderID;
}// CTSPUIDevice::GetProviderID
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::GetLineCount
//
// Returns the number of lines stored in our internal array
//
TSP_INLINE unsigned int CTSPUIDevice::GetLineCount() const
{
return m_arrLines.GetSize();
}// CTSPUIDevice::GetLineCount
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::GetLineConnectionInfo
//
// Returns a specific line object by index
//
TSP_INLINE CTSPUILineConnection* CTSPUIDevice::GetLineConnectionInfo(unsigned int nIndex) const
{
return (nIndex < GetLineCount()) ?
m_arrLines[nIndex] : NULL;
}// CTSPUIDevice::GetLineConnectionInfo
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::AddLine
//
// Add a line to the service provider
//
TSP_INLINE unsigned int CTSPUIDevice::AddLine(CTSPUILineConnection* pLine)
{
pLine->m_pDevice = this;
return m_arrLines.Add(pLine);
}// CTSPUIDevice::AddLine
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::RemoveLine
//
// Remove a line from the service provider
//
TSP_INLINE void CTSPUIDevice::RemoveLine(unsigned int iLine)
{
if (iLine < GetLineCount())
m_arrLines.RemoveAt(iLine);
}// CTSPUIDevice::RemoveLine
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::RemoveLine
//
// Remove a line from the service provider
//
TSP_INLINE void CTSPUIDevice::RemoveLine(CTSPUILineConnection* pLine)
{
for (unsigned int i = 0; i < GetLineCount(); i++)
{
if (GetLineConnectionInfo(i) == pLine)
{
RemoveLine(i);
break;
}
}
}// CTSPUIDevice::RemoveLine
///////////////////////////////////////////////////////////////////////////
// CTSPUIDevice::FindLineConnectionByPermanentID
//
// Returns a specific line object by line id
//
TSP_INLINE CTSPUILineConnection* CTSPUIDevice::FindLineConnectionByPermanentID(DWORD dwPermID)
{
for (unsigned int i = 0; i < GetLineCount(); i++)
{
CTSPUILineConnection* pLine = GetLineConnectionInfo(i);
if (pLine->GetPermanentDeviceID() == dwPermID)
return pLine;
}
return NULL;
}// CTSPUIDevice::FindLineConnectionByPermanentID
#endif // _UIDEVICE_INL_INC_
| 29.955157 | 95 | 0.54985 | [
"object"
] |
3388e20fadfc2a26a4dcade0b30d79b0cc117120 | 3,793 | cc | C++ | CondTools/SiPixel/plugins/SiPixelLorentzAngleReader.cc | suhokimHEP/cmssw | 4102974e760db0f758efcb696b2d3e5c10d52058 | [
"Apache-2.0"
] | 1 | 2021-11-18T20:03:43.000Z | 2021-11-18T20:03:43.000Z | CondTools/SiPixel/plugins/SiPixelLorentzAngleReader.cc | suhokimHEP/cmssw | 4102974e760db0f758efcb696b2d3e5c10d52058 | [
"Apache-2.0"
] | 30 | 2015-11-04T11:42:27.000Z | 2021-12-01T07:56:34.000Z | CondTools/SiPixel/plugins/SiPixelLorentzAngleReader.cc | thomreis/cmssw | 220214e9b797d008e1ae31def5509825741a87fd | [
"Apache-2.0"
] | 1 | 2022-03-22T20:45:02.000Z | 2022-03-22T20:45:02.000Z | // system include files
#include <cstdio>
#include <iostream>
#include <sys/time.h>
// user include files
#include "CommonTools/UtilAlgos/interface/TFileService.h"
#include "CondFormats/DataRecord/interface/SiPixelLorentzAngleRcd.h"
#include "CondFormats/DataRecord/interface/SiPixelLorentzAngleSimRcd.h"
#include "CondFormats/SiPixelObjects/interface/SiPixelLorentzAngle.h"
#include "DataFormats/DetId/interface/DetId.h"
#include "DataFormats/SiPixelDetId/interface/PixelSubdetector.h"
#include "DataFormats/TrackerCommon/interface/PixelBarrelName.h"
#include "DataFormats/TrackerCommon/interface/PixelEndcapName.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "Geometry/CommonDetUnit/interface/PixelGeomDetUnit.h"
#include "Geometry/Records/interface/TrackerDigiGeometryRecord.h"
// ROOT includes
#include "TROOT.h"
#include "TFile.h"
#include "TH2F.h"
//
//
// class decleration
//
class SiPixelLorentzAngleReader : public edm::one::EDAnalyzer<edm::one::SharedResources> {
public:
explicit SiPixelLorentzAngleReader(const edm::ParameterSet&);
~SiPixelLorentzAngleReader() override;
void analyze(const edm::Event&, const edm::EventSetup&) override;
private:
const edm::ESGetToken<SiPixelLorentzAngle, SiPixelLorentzAngleRcd> siPixelLAToken_;
const edm::ESGetToken<SiPixelLorentzAngle, SiPixelLorentzAngleSimRcd> siPixelSimLAToken_;
const bool printdebug_;
const bool useSimRcd_;
TH1F* LorentzAngleBarrel_;
TH1F* LorentzAngleForward_;
};
using namespace cms;
SiPixelLorentzAngleReader::SiPixelLorentzAngleReader(const edm::ParameterSet& iConfig)
: siPixelLAToken_(esConsumes()),
siPixelSimLAToken_(esConsumes()),
printdebug_(iConfig.getUntrackedParameter<bool>("printDebug", false)),
useSimRcd_(iConfig.getParameter<bool>("useSimRcd")) {
usesResource(TFileService::kSharedResource);
}
SiPixelLorentzAngleReader::~SiPixelLorentzAngleReader() = default;
void SiPixelLorentzAngleReader::analyze(const edm::Event& e, const edm::EventSetup& iSetup) {
const SiPixelLorentzAngle* SiPixelLorentzAngle_;
if (useSimRcd_) {
SiPixelLorentzAngle_ = &iSetup.getData(siPixelSimLAToken_);
} else {
SiPixelLorentzAngle_ = &iSetup.getData(siPixelLAToken_);
}
edm::LogInfo("SiPixelLorentzAngleReader")
<< "[SiPixelLorentzAngleReader::analyze] End Reading SiPixelLorentzAngle" << std::endl;
edm::Service<TFileService> fs;
LorentzAngleBarrel_ = fs->make<TH1F>("LorentzAngleBarrelPixel", "LorentzAngleBarrelPixel", 150, 0, 0.15);
LorentzAngleForward_ = fs->make<TH1F>("LorentzAngleForwardPixel", "LorentzAngleForwardPixel", 150, 0, 0.15);
std::map<unsigned int, float> detid_la = SiPixelLorentzAngle_->getLorentzAngles();
std::map<unsigned int, float>::const_iterator it;
for (it = detid_la.begin(); it != detid_la.end(); it++) {
// edm::LogPrint("SiPixelLorentzAngleReader") << "detid " << it->first << " \t" << " Lorentz angle " << it->second << std::endl;
//edm::LogInfo("SiPixelLorentzAngleReader") << "detid " << it->first << " \t" << " Lorentz angle " << it->second;
unsigned int subdet = DetId(it->first).subdetId();
if (subdet == static_cast<int>(PixelSubdetector::PixelBarrel)) {
LorentzAngleBarrel_->Fill(it->second);
} else if (subdet == static_cast<int>(PixelSubdetector::PixelEndcap)) {
LorentzAngleForward_->Fill(it->second);
}
}
}
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/Frameworkfwd.h"
DEFINE_FWK_MODULE(SiPixelLorentzAngleReader);
| 41.228261 | 135 | 0.765094 | [
"geometry"
] |
338a141821dbe734f842b37c38ad2beece9a1a5c | 24,958 | cpp | C++ | Optimus/ThirdParty/VulkanSDK/Vulkan1/spirv-tools/source/opt/ir_context.cpp | Sparksidy/Optimus | 4ff26a2c21d61759b192f1b0afeff4f2c17aad9a | [
"Apache-2.0"
] | null | null | null | Optimus/ThirdParty/VulkanSDK/Vulkan1/spirv-tools/source/opt/ir_context.cpp | Sparksidy/Optimus | 4ff26a2c21d61759b192f1b0afeff4f2c17aad9a | [
"Apache-2.0"
] | null | null | null | Optimus/ThirdParty/VulkanSDK/Vulkan1/spirv-tools/source/opt/ir_context.cpp | Sparksidy/Optimus | 4ff26a2c21d61759b192f1b0afeff4f2c17aad9a | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ir_context.h"
#include "latest_version_glsl_std_450_header.h"
#include "log.h"
#include "mem_pass.h"
#include "reflect.h"
#include <cstring>
namespace spvtools {
namespace ir {
void IRContext::BuildInvalidAnalyses(IRContext::Analysis set) {
if (set & kAnalysisDefUse) {
BuildDefUseManager();
}
if (set & kAnalysisInstrToBlockMapping) {
BuildInstrToBlockMapping();
}
if (set & kAnalysisDecorations) {
BuildDecorationManager();
}
if (set & kAnalysisCFG) {
BuildCFG();
}
if (set & kAnalysisDominatorAnalysis) {
ResetDominatorAnalysis();
}
if (set & kAnalysisLoopAnalysis) {
ResetLoopAnalysis();
}
if (set & kAnalysisNameMap) {
BuildIdToNameMap();
}
if (set & kAnalysisScalarEvolution) {
BuildScalarEvolutionAnalysis();
}
if (set & kAnalysisRegisterPressure) {
BuildRegPressureAnalysis();
}
if (set & kAnalysisValueNumberTable) {
BuildValueNumberTable();
}
}
void IRContext::InvalidateAnalysesExceptFor(
IRContext::Analysis preserved_analyses) {
uint32_t analyses_to_invalidate = valid_analyses_ & (~preserved_analyses);
InvalidateAnalyses(static_cast<IRContext::Analysis>(analyses_to_invalidate));
}
void IRContext::InvalidateAnalyses(IRContext::Analysis analyses_to_invalidate) {
if (analyses_to_invalidate & kAnalysisDefUse) {
def_use_mgr_.reset(nullptr);
}
if (analyses_to_invalidate & kAnalysisInstrToBlockMapping) {
instr_to_block_.clear();
}
if (analyses_to_invalidate & kAnalysisDecorations) {
decoration_mgr_.reset(nullptr);
}
if (analyses_to_invalidate & kAnalysisCombinators) {
combinator_ops_.clear();
}
if (analyses_to_invalidate & kAnalysisCFG) {
cfg_.reset(nullptr);
}
if (analyses_to_invalidate & kAnalysisDominatorAnalysis) {
dominator_trees_.clear();
post_dominator_trees_.clear();
}
if (analyses_to_invalidate & kAnalysisNameMap) {
id_to_name_.reset(nullptr);
}
if (analyses_to_invalidate & kAnalysisValueNumberTable) {
vn_table_.reset(nullptr);
}
valid_analyses_ = Analysis(valid_analyses_ & ~analyses_to_invalidate);
}
Instruction* IRContext::KillInst(ir::Instruction* inst) {
if (!inst) {
return nullptr;
}
KillNamesAndDecorates(inst);
if (AreAnalysesValid(kAnalysisDefUse)) {
get_def_use_mgr()->ClearInst(inst);
}
if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
instr_to_block_.erase(inst);
}
if (AreAnalysesValid(kAnalysisDecorations)) {
if (inst->result_id() != 0) {
decoration_mgr_->RemoveDecorationsFrom(inst->result_id());
}
if (inst->IsDecoration()) {
decoration_mgr_->RemoveDecoration(inst);
}
}
if (type_mgr_ && ir::IsTypeInst(inst->opcode())) {
type_mgr_->RemoveId(inst->result_id());
}
if (constant_mgr_ && ir::IsConstantInst(inst->opcode())) {
constant_mgr_->RemoveId(inst->result_id());
}
RemoveFromIdToName(inst);
Instruction* next_instruction = nullptr;
if (inst->IsInAList()) {
next_instruction = inst->NextNode();
inst->RemoveFromList();
delete inst;
} else {
// Needed for instructions that are not part of a list like OpLabels,
// OpFunction, OpFunctionEnd, etc..
inst->ToNop();
}
return next_instruction;
}
bool IRContext::KillDef(uint32_t id) {
ir::Instruction* def = get_def_use_mgr()->GetDef(id);
if (def != nullptr) {
KillInst(def);
return true;
}
return false;
}
bool IRContext::ReplaceAllUsesWith(uint32_t before, uint32_t after) {
if (before == after) return false;
// Ensure that |after| has been registered as def.
assert(get_def_use_mgr()->GetDef(after) &&
"'after' is not a registered def.");
std::vector<std::pair<ir::Instruction*, uint32_t>> uses_to_update;
get_def_use_mgr()->ForEachUse(
before, [&uses_to_update](ir::Instruction* user, uint32_t index) {
uses_to_update.emplace_back(user, index);
});
ir::Instruction* prev = nullptr;
for (auto p : uses_to_update) {
ir::Instruction* user = p.first;
uint32_t index = p.second;
if (prev == nullptr || prev != user) {
ForgetUses(user);
prev = user;
}
const uint32_t type_result_id_count =
(user->result_id() != 0) + (user->type_id() != 0);
if (index < type_result_id_count) {
// Update the type_id. Note that result id is immutable so it should
// never be updated.
if (user->type_id() != 0 && index == 0) {
user->SetResultType(after);
} else if (user->type_id() == 0) {
SPIRV_ASSERT(consumer_, false,
"Result type id considered as use while the instruction "
"doesn't have a result type id.");
(void)consumer_; // Makes the compiler happy for release build.
} else {
SPIRV_ASSERT(consumer_, false,
"Trying setting the immutable result id.");
}
} else {
// Update an in-operand.
uint32_t in_operand_pos = index - type_result_id_count;
// Make the modification in the instruction.
user->SetInOperand(in_operand_pos, {after});
}
AnalyzeUses(user);
};
return true;
}
bool IRContext::IsConsistent() {
#ifndef SPIRV_CHECK_CONTEXT
return true;
#endif
if (AreAnalysesValid(kAnalysisDefUse)) {
opt::analysis::DefUseManager new_def_use(module());
if (*get_def_use_mgr() != new_def_use) {
return false;
}
}
if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
for (auto& func : *module()) {
for (auto& block : func) {
if (!block.WhileEachInst([this, &block](ir::Instruction* inst) {
if (get_instr_block(inst) != &block) {
return false;
}
return true;
}))
return false;
}
}
}
if (!CheckCFG()) {
return false;
}
return true;
}
void spvtools::ir::IRContext::ForgetUses(Instruction* inst) {
if (AreAnalysesValid(kAnalysisDefUse)) {
get_def_use_mgr()->EraseUseRecordsOfOperandIds(inst);
}
if (AreAnalysesValid(kAnalysisDecorations)) {
if (inst->IsDecoration()) {
get_decoration_mgr()->RemoveDecoration(inst);
}
}
RemoveFromIdToName(inst);
}
void IRContext::AnalyzeUses(Instruction* inst) {
if (AreAnalysesValid(kAnalysisDefUse)) {
get_def_use_mgr()->AnalyzeInstUse(inst);
}
if (AreAnalysesValid(kAnalysisDecorations)) {
if (inst->IsDecoration()) {
get_decoration_mgr()->AddDecoration(inst);
}
}
if (id_to_name_ &&
(inst->opcode() == SpvOpName || inst->opcode() == SpvOpMemberName)) {
id_to_name_->insert({inst->GetSingleWordInOperand(0), inst});
}
}
void IRContext::KillNamesAndDecorates(uint32_t id) {
std::vector<ir::Instruction*> decorations =
get_decoration_mgr()->GetDecorationsFor(id, true);
for (Instruction* inst : decorations) {
KillInst(inst);
}
std::vector<ir::Instruction*> name_to_kill;
for (auto name : GetNames(id)) {
name_to_kill.push_back(name.second);
}
for (ir::Instruction* name_inst : name_to_kill) {
KillInst(name_inst);
}
}
void IRContext::KillNamesAndDecorates(Instruction* inst) {
const uint32_t rId = inst->result_id();
if (rId == 0) return;
KillNamesAndDecorates(rId);
}
void IRContext::AddCombinatorsForCapability(uint32_t capability) {
if (capability == SpvCapabilityShader) {
combinator_ops_[0].insert({SpvOpNop,
SpvOpUndef,
SpvOpConstant,
SpvOpConstantTrue,
SpvOpConstantFalse,
SpvOpConstantComposite,
SpvOpConstantSampler,
SpvOpConstantNull,
SpvOpTypeVoid,
SpvOpTypeBool,
SpvOpTypeInt,
SpvOpTypeFloat,
SpvOpTypeVector,
SpvOpTypeMatrix,
SpvOpTypeImage,
SpvOpTypeSampler,
SpvOpTypeSampledImage,
SpvOpTypeArray,
SpvOpTypeRuntimeArray,
SpvOpTypeStruct,
SpvOpTypeOpaque,
SpvOpTypePointer,
SpvOpTypeFunction,
SpvOpTypeEvent,
SpvOpTypeDeviceEvent,
SpvOpTypeReserveId,
SpvOpTypeQueue,
SpvOpTypePipe,
SpvOpTypeForwardPointer,
SpvOpVariable,
SpvOpImageTexelPointer,
SpvOpLoad,
SpvOpAccessChain,
SpvOpInBoundsAccessChain,
SpvOpArrayLength,
SpvOpVectorExtractDynamic,
SpvOpVectorInsertDynamic,
SpvOpVectorShuffle,
SpvOpCompositeConstruct,
SpvOpCompositeExtract,
SpvOpCompositeInsert,
SpvOpCopyObject,
SpvOpTranspose,
SpvOpSampledImage,
SpvOpImageSampleImplicitLod,
SpvOpImageSampleExplicitLod,
SpvOpImageSampleDrefImplicitLod,
SpvOpImageSampleDrefExplicitLod,
SpvOpImageSampleProjImplicitLod,
SpvOpImageSampleProjExplicitLod,
SpvOpImageSampleProjDrefImplicitLod,
SpvOpImageSampleProjDrefExplicitLod,
SpvOpImageFetch,
SpvOpImageGather,
SpvOpImageDrefGather,
SpvOpImageRead,
SpvOpImage,
SpvOpImageQueryFormat,
SpvOpImageQueryOrder,
SpvOpImageQuerySizeLod,
SpvOpImageQuerySize,
SpvOpImageQueryLevels,
SpvOpImageQuerySamples,
SpvOpConvertFToU,
SpvOpConvertFToS,
SpvOpConvertSToF,
SpvOpConvertUToF,
SpvOpUConvert,
SpvOpSConvert,
SpvOpFConvert,
SpvOpQuantizeToF16,
SpvOpBitcast,
SpvOpSNegate,
SpvOpFNegate,
SpvOpIAdd,
SpvOpFAdd,
SpvOpISub,
SpvOpFSub,
SpvOpIMul,
SpvOpFMul,
SpvOpUDiv,
SpvOpSDiv,
SpvOpFDiv,
SpvOpUMod,
SpvOpSRem,
SpvOpSMod,
SpvOpFRem,
SpvOpFMod,
SpvOpVectorTimesScalar,
SpvOpMatrixTimesScalar,
SpvOpVectorTimesMatrix,
SpvOpMatrixTimesVector,
SpvOpMatrixTimesMatrix,
SpvOpOuterProduct,
SpvOpDot,
SpvOpIAddCarry,
SpvOpISubBorrow,
SpvOpUMulExtended,
SpvOpSMulExtended,
SpvOpAny,
SpvOpAll,
SpvOpIsNan,
SpvOpIsInf,
SpvOpLogicalEqual,
SpvOpLogicalNotEqual,
SpvOpLogicalOr,
SpvOpLogicalAnd,
SpvOpLogicalNot,
SpvOpSelect,
SpvOpIEqual,
SpvOpINotEqual,
SpvOpUGreaterThan,
SpvOpSGreaterThan,
SpvOpUGreaterThanEqual,
SpvOpSGreaterThanEqual,
SpvOpULessThan,
SpvOpSLessThan,
SpvOpULessThanEqual,
SpvOpSLessThanEqual,
SpvOpFOrdEqual,
SpvOpFUnordEqual,
SpvOpFOrdNotEqual,
SpvOpFUnordNotEqual,
SpvOpFOrdLessThan,
SpvOpFUnordLessThan,
SpvOpFOrdGreaterThan,
SpvOpFUnordGreaterThan,
SpvOpFOrdLessThanEqual,
SpvOpFUnordLessThanEqual,
SpvOpFOrdGreaterThanEqual,
SpvOpFUnordGreaterThanEqual,
SpvOpShiftRightLogical,
SpvOpShiftRightArithmetic,
SpvOpShiftLeftLogical,
SpvOpBitwiseOr,
SpvOpBitwiseXor,
SpvOpBitwiseAnd,
SpvOpNot,
SpvOpBitFieldInsert,
SpvOpBitFieldSExtract,
SpvOpBitFieldUExtract,
SpvOpBitReverse,
SpvOpBitCount,
SpvOpPhi,
SpvOpImageSparseSampleImplicitLod,
SpvOpImageSparseSampleExplicitLod,
SpvOpImageSparseSampleDrefImplicitLod,
SpvOpImageSparseSampleDrefExplicitLod,
SpvOpImageSparseSampleProjImplicitLod,
SpvOpImageSparseSampleProjExplicitLod,
SpvOpImageSparseSampleProjDrefImplicitLod,
SpvOpImageSparseSampleProjDrefExplicitLod,
SpvOpImageSparseFetch,
SpvOpImageSparseGather,
SpvOpImageSparseDrefGather,
SpvOpImageSparseTexelsResident,
SpvOpImageSparseRead,
SpvOpSizeOf});
}
}
void IRContext::AddCombinatorsForExtension(ir::Instruction* extension) {
assert(extension->opcode() == SpvOpExtInstImport &&
"Expecting an import of an extension's instruction set.");
const char* extension_name =
reinterpret_cast<const char*>(&extension->GetInOperand(0).words[0]);
if (!strcmp(extension_name, "GLSL.std.450")) {
combinator_ops_[extension->result_id()] = {GLSLstd450Round,
GLSLstd450RoundEven,
GLSLstd450Trunc,
GLSLstd450FAbs,
GLSLstd450SAbs,
GLSLstd450FSign,
GLSLstd450SSign,
GLSLstd450Floor,
GLSLstd450Ceil,
GLSLstd450Fract,
GLSLstd450Radians,
GLSLstd450Degrees,
GLSLstd450Sin,
GLSLstd450Cos,
GLSLstd450Tan,
GLSLstd450Asin,
GLSLstd450Acos,
GLSLstd450Atan,
GLSLstd450Sinh,
GLSLstd450Cosh,
GLSLstd450Tanh,
GLSLstd450Asinh,
GLSLstd450Acosh,
GLSLstd450Atanh,
GLSLstd450Atan2,
GLSLstd450Pow,
GLSLstd450Exp,
GLSLstd450Log,
GLSLstd450Exp2,
GLSLstd450Log2,
GLSLstd450Sqrt,
GLSLstd450InverseSqrt,
GLSLstd450Determinant,
GLSLstd450MatrixInverse,
GLSLstd450ModfStruct,
GLSLstd450FMin,
GLSLstd450UMin,
GLSLstd450SMin,
GLSLstd450FMax,
GLSLstd450UMax,
GLSLstd450SMax,
GLSLstd450FClamp,
GLSLstd450UClamp,
GLSLstd450SClamp,
GLSLstd450FMix,
GLSLstd450IMix,
GLSLstd450Step,
GLSLstd450SmoothStep,
GLSLstd450Fma,
GLSLstd450FrexpStruct,
GLSLstd450Ldexp,
GLSLstd450PackSnorm4x8,
GLSLstd450PackUnorm4x8,
GLSLstd450PackSnorm2x16,
GLSLstd450PackUnorm2x16,
GLSLstd450PackHalf2x16,
GLSLstd450PackDouble2x32,
GLSLstd450UnpackSnorm2x16,
GLSLstd450UnpackUnorm2x16,
GLSLstd450UnpackHalf2x16,
GLSLstd450UnpackSnorm4x8,
GLSLstd450UnpackUnorm4x8,
GLSLstd450UnpackDouble2x32,
GLSLstd450Length,
GLSLstd450Distance,
GLSLstd450Cross,
GLSLstd450Normalize,
GLSLstd450FaceForward,
GLSLstd450Reflect,
GLSLstd450Refract,
GLSLstd450FindILsb,
GLSLstd450FindSMsb,
GLSLstd450FindUMsb,
GLSLstd450InterpolateAtCentroid,
GLSLstd450InterpolateAtSample,
GLSLstd450InterpolateAtOffset,
GLSLstd450NMin,
GLSLstd450NMax,
GLSLstd450NClamp};
} else {
// Map the result id to the empty set.
combinator_ops_[extension->result_id()];
}
}
void IRContext::InitializeCombinators() {
get_feature_mgr()->GetCapabilities()->ForEach(
[this](SpvCapability cap) { AddCombinatorsForCapability(cap); });
for (auto& extension : module()->ext_inst_imports()) {
AddCombinatorsForExtension(&extension);
}
valid_analyses_ |= kAnalysisCombinators;
}
void IRContext::RemoveFromIdToName(const Instruction* inst) {
if (id_to_name_ &&
(inst->opcode() == SpvOpName || inst->opcode() == SpvOpMemberName)) {
auto range = id_to_name_->equal_range(inst->GetSingleWordInOperand(0));
for (auto it = range.first; it != range.second; ++it) {
if (it->second == inst) {
id_to_name_->erase(it);
break;
}
}
}
}
ir::LoopDescriptor* IRContext::GetLoopDescriptor(const ir::Function* f) {
if (!AreAnalysesValid(kAnalysisLoopAnalysis)) {
ResetLoopAnalysis();
}
std::unordered_map<const ir::Function*, ir::LoopDescriptor>::iterator it =
loop_descriptors_.find(f);
if (it == loop_descriptors_.end()) {
return &loop_descriptors_.emplace(std::make_pair(f, ir::LoopDescriptor(f)))
.first->second;
}
return &it->second;
}
// Gets the dominator analysis for function |f|.
opt::DominatorAnalysis* IRContext::GetDominatorAnalysis(const ir::Function* f) {
if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
ResetDominatorAnalysis();
}
if (dominator_trees_.find(f) == dominator_trees_.end()) {
dominator_trees_[f].InitializeTree(f);
}
return &dominator_trees_[f];
}
// Gets the postdominator analysis for function |f|.
opt::PostDominatorAnalysis* IRContext::GetPostDominatorAnalysis(
const ir::Function* f) {
if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
ResetDominatorAnalysis();
}
if (post_dominator_trees_.find(f) == post_dominator_trees_.end()) {
post_dominator_trees_[f].InitializeTree(f);
}
return &post_dominator_trees_[f];
}
bool ir::IRContext::CheckCFG() {
std::unordered_map<uint32_t, std::vector<uint32_t>> real_preds;
if (!AreAnalysesValid(kAnalysisCFG)) {
return true;
}
for (ir::Function& function : *module()) {
for (const auto& bb : function) {
bb.ForEachSuccessorLabel([&bb, &real_preds](const uint32_t lab_id) {
real_preds[lab_id].push_back(bb.id());
});
}
for (auto& bb : function) {
std::vector<uint32_t> preds = cfg()->preds(bb.id());
std::vector<uint32_t> real = real_preds[bb.id()];
std::sort(preds.begin(), preds.end());
std::sort(real.begin(), real.end());
bool same = true;
if (preds.size() != real.size()) {
same = false;
}
for (size_t i = 0; i < real.size() && same; i++) {
if (preds[i] != real[i]) {
same = false;
}
}
if (!same) {
std::cerr << "Predecessors for " << bb.id() << " are different:\n";
std::cerr << "Real:";
for (uint32_t i : real) {
std::cerr << ' ' << i;
}
std::cerr << std::endl;
std::cerr << "Recorded:";
for (uint32_t i : preds) {
std::cerr << ' ' << i;
}
std::cerr << std::endl;
}
if (!same) return false;
}
}
return true;
}
} // namespace ir
} // namespace spvtools
| 38.103817 | 80 | 0.478043 | [
"vector"
] |
338c579d8f6701dbcfbe4856570c4ff4f04c6461 | 10,901 | cpp | C++ | src/sphere_detector.cpp | ravijo/multiple_kinect_baxter_calibration | c7f4fb18ef9d7a88b15a9a7398b1ce524a7c7565 | [
"MIT"
] | 5 | 2019-02-07T23:55:55.000Z | 2020-10-19T10:07:50.000Z | src/sphere_detector.cpp | ravijo/multiple_kinect_baxter_calibration | c7f4fb18ef9d7a88b15a9a7398b1ce524a7c7565 | [
"MIT"
] | null | null | null | src/sphere_detector.cpp | ravijo/multiple_kinect_baxter_calibration | c7f4fb18ef9d7a88b15a9a7398b1ce524a7c7565 | [
"MIT"
] | 1 | 2020-01-09T07:51:17.000Z | 2020-01-09T07:51:17.000Z | /**
* sphere_detector.cpp: class file for detecting sphere
* Author: Ravi Joshi
* Date: 2018/02/20
*/
#include <utility.h>
#include <sphere_detector.h>
namespace pcl_utility
{
SphereDetector::SphereDetector(float sphere_radius, std::vector<int>* min_hsv,
std::vector<int>* max_hsv,
RansacParams* ransac_params,
int overflow_offset)
{
radius = sphere_radius;
min_hsv_ptr =
new cv::Scalar(min_hsv->at(0), min_hsv->at(1), min_hsv->at(2));
max_hsv_ptr =
new cv::Scalar(max_hsv->at(0), max_hsv->at(1), max_hsv->at(2));
prob = ransac_params->prob;
weight = ransac_params->weight;
epsilon = ransac_params->epsilon;
max_itr = ransac_params->max_itr;
d_thresh = ransac_params->d_thresh;
tolerance = ransac_params->tolerance;
k_neighbors = ransac_params->k_neighbors;
offset = overflow_offset;
initSphereDetector();
}
void SphereDetector::initSphereDetector()
{
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(
new pcl::search::KdTree<pcl::PointXYZ>());
ne.setSearchMethod(tree);
ne.setKSearch(k_neighbors);
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_NORMAL_SPHERE);
seg.setNormalDistanceWeight(weight);
seg.setMethodType(pcl::SAC_RANSAC);
seg.setMaxIterations(max_itr);
seg.setDistanceThreshold(d_thresh);
seg.setProbability(prob);
seg.setRadiusLimits(radius - tolerance, radius + tolerance);
seg.setEpsAngle(pcl::deg2rad(epsilon));
}
bool SphereDetector::getBoundingRect(cv::Mat image, cv::Rect& bound_rect)
{
// smooth image
cv::GaussianBlur(image, image, cv::Size(5, 5), 0, 0);
cv::Mat hsv_image, binary_image;
cv::cvtColor(image, hsv_image, cv::COLOR_BGR2HSV); // convert to hsv
// remove pixels outside given range
cv::inRange(hsv_image, *min_hsv_ptr, *max_hsv_ptr, binary_image);
// cv::imwrite( "binary_image.jpg", binary_image); //just for checking
hsv_image.release(); // remove hsv_image from memory
cv::Vec2d largest_contour(0, 0); // index, area
// cv::imwrite( "binary_image.jpg", binary_image);
// find contours from binary image
std::vector<std::vector<cv::Point> > contours;
findContours(binary_image, contours, CV_RETR_EXTERNAL,
CV_CHAIN_APPROX_SIMPLE); // find contours
binary_image.release(); // remove binary_image from memory
// find largest contour
for (int i = 0; i < contours.size(); i++)
{
double area = contourArea(cv::Mat(contours[i]));
if (area > largest_contour[1])
{
largest_contour[1] = area;
largest_contour[0] = i;
}
}
double largest_contour_area = largest_contour[1];
/*
* calculate bouding rectangle only if
* area associated with largest contour is more than zero
*/
if (largest_contour[1] > 0)
{
bound_rect = boundingRect(cv::Mat(contours[largest_contour[0]]));
/*
rectangle( binary_image, bound_rect.tl(), bound_rect.br(), cv::Scalar(255,
255, 255), 2, 8,
0 );
cv::imwrite( "rect_binary_image.jpg", binary_image);
*/
return true;
}
else
return false;
}
bool SphereDetector::convertMouseCoordsTo3DPC(vtkRenderWindowInteractor* iren,
vtkPointPicker* point_picker,
int mouse_x, int mouse_y,
Eigen::Vector3f& point)
{
vtkRenderer* ren = iren->FindPokedRenderer(mouse_x, mouse_y);
point_picker->Pick(mouse_x, mouse_y, 0.0, ren);
int id = static_cast<int>(point_picker->GetPointId());
if (id != -1 && point_picker->GetDataSet() != NULL)
{
double p[3];
point_picker->GetDataSet()->GetPoint(id, p);
for (size_t i = 0; i < 3; i++)
point(i) = p[i];
return true;
}
else
return false;
}
void SphereDetector::get2DPoints(std::vector<cv::Point>& points)
{
int x_a = points[0].x, y_a = points[0].y;
int x_c = points[1].x, y_c = points[1].y;
int x_b = x_c, y_b = y_a;
int x_d = x_a, y_d = y_c;
int x_q = mid(x_a, x_c), y_q = mid(y_a, y_c);
int x_e = mid(x_a, x_d), y_e = mid(y_a, y_d);
int x_f = mid(x_a, x_b), y_f = mid(y_a, y_b);
int x_g = mid(x_b, x_c), y_g = mid(y_b, y_c);
int x_h = mid(x_d, x_c), y_h = mid(y_d, y_c);
int x_i = mid(x_h, x_e), y_i = mid(y_h, y_e);
int x_j = mid(x_e, x_f), y_j = mid(y_e, y_f);
int x_k = mid(x_f, x_g), y_k = mid(y_f, y_g);
int x_l = mid(x_g, x_h), y_l = mid(y_g, y_h);
int x_m = mid(x_i, x_l), y_m = mid(y_i, y_l);
int x_n = mid(x_i, x_j), y_n = mid(y_i, y_j);
int x_o = mid(x_j, x_k), y_o = mid(y_j, y_k);
int x_p = mid(x_k, x_l), y_p = mid(y_k, y_l);
points.push_back(cv::Point(x_a, y_a));
points.push_back(cv::Point(x_b, y_b));
points.push_back(cv::Point(x_c, y_c));
points.push_back(cv::Point(x_d, y_d));
points.push_back(cv::Point(x_e, y_e));
points.push_back(cv::Point(x_f, y_f));
points.push_back(cv::Point(x_g, y_g));
points.push_back(cv::Point(x_h, y_h));
points.push_back(cv::Point(x_i, y_i));
points.push_back(cv::Point(x_j, y_j));
points.push_back(cv::Point(x_k, y_k));
points.push_back(cv::Point(x_l, y_l));
points.push_back(cv::Point(x_m, y_m));
points.push_back(cv::Point(x_n, y_n));
points.push_back(cv::Point(x_o, y_o));
points.push_back(cv::Point(x_p, y_p));
}
void SphereDetector::get3DMinMaxRange(
pcl::visualization::PCLVisualizer* viewer, cv::Size img, cv::Rect rect,
Eigen::Vector4f& min_3d, Eigen::Vector4f& max_3d)
{
vtkRenderWindowInteractor* iren =
viewer->getRenderWindow()->GetInteractor();
vtkPointPicker* point_picker =
vtkPointPicker::SafeDownCast(iren->GetPicker());
// check if given bounding box is outside the window
int start_x = rect.x < 0 ? offset : rect.x;
int start_y = rect.y < 0 ? img.height - offset : img.height - rect.y;
int end_x = rect.x + rect.width > img.width ? img.width - offset :
rect.x + rect.width;
int end_y = rect.y + rect.height > img.height ?
offset :
img.height - (rect.y + rect.height);
std::vector<cv::Point> points_2d;
points_2d.push_back(cv::Point(start_x, start_y));
points_2d.push_back(cv::Point(end_x, end_y));
get2DPoints(points_2d);
pcl::PointCloud<pcl::PointXYZ> points_3d;
points_3d.height = 1;
points_3d.is_dense = false;
for (size_t i = 0; i < points_2d.size(); i++)
{
Eigen::Vector3f p;
if (convertMouseCoordsTo3DPC(iren, point_picker, points_2d[i].x,
points_2d[i].y, p))
{
pcl::PointXYZ point(p(0), p(1), p(2));
points_3d.points.push_back(point);
}
}
// make sure to set the width
points_3d.width = points_3d.points.size();
pcl::PointXYZ min_pt, max_pt;
pcl::getMinMax3D(points_3d, min_pt, max_pt);
// just to be on safe side lets define some offset
min_3d(0) = min_pt.x - radius;
max_3d(0) = max_pt.x + radius;
min_3d(1) = min_pt.y - radius;
max_3d(1) = max_pt.y + radius;
min_3d(2) = min_pt.z - radius;
max_3d(2) = max_pt.z + radius;
min_3d(3) = 1;
max_3d(3) = 1;
}
void SphereDetector::crop(pcl::PointCloud<pcl::PointXYZRGB>::Ptr in,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr out,
Eigen::Vector4f& min, Eigen::Vector4f& max)
{
box_filter.setMin(min);
box_filter.setMax(max);
box_filter.setInputCloud(in);
box_filter.filter(*out);
}
bool SphereDetector::validateDetection(
pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud)
{
// calculate average RGB values of the input cloud
int avg_r = 0, avg_g = 0, avg_b = 0;
for (size_t i = 0; i < cloud->points.size(); i++)
{
avg_r += (int)cloud->points[i].r;
avg_g += (int)cloud->points[i].g;
avg_b += (int)cloud->points[i].b;
}
avg_r = avg_r / cloud->points.size();
avg_g = avg_g / cloud->points.size();
avg_b = avg_b / cloud->points.size();
cv::Vec3b avg_hsv = utility::rgb_to_hsv_pixel(avg_r, avg_g, avg_b);
bool all_channel_in_between = true;
for (size_t i = 0; i < 3; i++)
all_channel_in_between =
all_channel_in_between &&
between(avg_hsv.val[i], min_hsv_ptr->val[i], max_hsv_ptr->val[i]);
return all_channel_in_between;
}
bool SphereDetector::segmentSphere(
pcl::visualization::PCLVisualizer* viewer,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr raw_cloud,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr filtered_cloud,
pcl::ModelCoefficients& coefficients)
{
cv::Mat image = utility::getImageFromPCLViewer(viewer);
// src: https://stackoverflow.com/a/14028277
cv::Size image_size = image.size();
// cv::imwrite( "image.jpg", image); //just for checking
cv::Rect boundary;
bool status = getBoundingRect(image, boundary);
image.release(); // remove image from memory
if (!status)
return false;
Eigen::Vector4f min_3d, max_3d;
get3DMinMaxRange(viewer, image_size, boundary, min_3d, max_3d);
crop(raw_cloud, filtered_cloud, min_3d, max_3d);
if (filtered_cloud->points.empty())
return false;
pcl::PointCloud<pcl::PointXYZ>::Ptr xyz_cloud(
new pcl::PointCloud<pcl::PointXYZ>);
pcl::copyPointCloud(*filtered_cloud, *xyz_cloud);
pcl::PointIndices::Ptr inliers(new pcl::PointIndices());
pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(
new pcl::PointCloud<pcl::Normal>);
ne.setInputCloud(xyz_cloud);
ne.compute(*cloud_normals);
seg.setInputCloud(xyz_cloud);
seg.setInputNormals(cloud_normals);
seg.segment(*inliers, coefficients);
// we have detected a sphere
if (inliers->indices.size() > 0)
{
// extract the sphere inliers from the input cloud
pcl::ExtractIndices<pcl::PointXYZRGB> extract;
extract.setInputCloud(filtered_cloud);
extract.setIndices(inliers);
extract.setNegative(false);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr sphere_cloud(
new pcl::PointCloud<pcl::PointXYZRGB>);
// get the points associated with sphere
extract.filter(*sphere_cloud);
// pcl::io::savePCDFileASCII("sphere_cloud.pcd", *sphere_cloud);
bool color_comp = validateDetection(sphere_cloud);
// make sure that sphere radius is in range
bool radius_range = between(coefficients.values[3], radius - tolerance,
radius + tolerance);
return (color_comp && radius_range);
}
else
return false;
}
}
| 32.834337 | 80 | 0.6182 | [
"vector"
] |
338cc0af6197378772d693b3a02ca949c167d575 | 17,558 | cc | C++ | runtime/vm/class_table.cc | Dart-NX/dartnx | 275f4c917965cde83f5ee5e1a8ba591175511cbe | [
"BSD-3-Clause"
] | 3 | 2020-04-20T00:11:34.000Z | 2022-01-24T20:43:43.000Z | runtime/vm/class_table.cc | Dart-NX/dartnx | 275f4c917965cde83f5ee5e1a8ba591175511cbe | [
"BSD-3-Clause"
] | 4 | 2020-04-20T11:16:42.000Z | 2020-04-20T11:18:30.000Z | runtime/vm/class_table.cc | Dart-NX/dartnx | 275f4c917965cde83f5ee5e1a8ba591175511cbe | [
"BSD-3-Clause"
] | 1 | 2020-04-20T00:11:43.000Z | 2020-04-20T00:11:43.000Z | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/class_table.h"
#include <memory>
#include "platform/atomic.h"
#include "vm/flags.h"
#include "vm/growable_array.h"
#include "vm/heap/heap.h"
#include "vm/object.h"
#include "vm/object_graph.h"
#include "vm/raw_object.h"
#include "vm/visitor.h"
namespace dart {
DEFINE_FLAG(bool, print_class_table, false, "Print initial class table.");
SharedClassTable::SharedClassTable()
: top_(kNumPredefinedCids),
capacity_(0),
old_tables_(new MallocGrowableArray<void*>()) {
if (Dart::vm_isolate() == NULL) {
ASSERT(kInitialCapacity >= kNumPredefinedCids);
capacity_ = kInitialCapacity;
// Note that [calloc] will zero-initialize the memory.
table_.store(reinterpret_cast<RelaxedAtomic<intptr_t>*>(
calloc(capacity_, sizeof(RelaxedAtomic<intptr_t>))));
} else {
// Duplicate the class table from the VM isolate.
auto vm_shared_class_table =
Dart::vm_isolate()->group()->shared_class_table();
capacity_ = vm_shared_class_table->capacity_;
// Note that [calloc] will zero-initialize the memory.
RelaxedAtomic<intptr_t>* table = reinterpret_cast<RelaxedAtomic<intptr_t>*>(
calloc(capacity_, sizeof(RelaxedAtomic<intptr_t>)));
// The following cids don't have a corresponding class object in Dart code.
// We therefore need to initialize them eagerly.
for (intptr_t i = kObjectCid; i < kInstanceCid; i++) {
table[i] = vm_shared_class_table->SizeAt(i);
}
table[kTypeArgumentsCid] = vm_shared_class_table->SizeAt(kTypeArgumentsCid);
table[kFreeListElement] = vm_shared_class_table->SizeAt(kFreeListElement);
table[kForwardingCorpse] = vm_shared_class_table->SizeAt(kForwardingCorpse);
table[kDynamicCid] = vm_shared_class_table->SizeAt(kDynamicCid);
table[kVoidCid] = vm_shared_class_table->SizeAt(kVoidCid);
table[kNeverCid] = vm_shared_class_table->SizeAt(kNeverCid);
table_.store(table);
}
#if defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
// Note that [calloc] will zero-initialize the memory.
unboxed_fields_map_ = static_cast<UnboxedFieldBitmap*>(
calloc(capacity_, sizeof(UnboxedFieldBitmap)));
#endif // defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
#ifndef PRODUCT
// Note that [calloc] will zero-initialize the memory.
trace_allocation_table_.store(
static_cast<uint8_t*>(calloc(capacity_, sizeof(uint8_t))));
#endif // !PRODUCT
}
SharedClassTable::~SharedClassTable() {
if (old_tables_ != NULL) {
FreeOldTables();
delete old_tables_;
}
free(table_.load());
free(unboxed_fields_map_);
NOT_IN_PRODUCT(free(trace_allocation_table_.load()));
}
void ClassTable::set_table(RawClass** table) {
Isolate* isolate = Isolate::Current();
ASSERT(isolate != nullptr);
table_.store(table);
isolate->set_cached_class_table_table(table);
}
ClassTable::ClassTable(SharedClassTable* shared_class_table)
: top_(kNumPredefinedCids),
capacity_(0),
table_(NULL),
old_class_tables_(new MallocGrowableArray<RawClass**>()),
shared_class_table_(shared_class_table) {
if (Dart::vm_isolate() == NULL) {
ASSERT(kInitialCapacity >= kNumPredefinedCids);
capacity_ = kInitialCapacity;
// Note that [calloc] will zero-initialize the memory.
// Don't use set_table because caller is supposed to set up isolates
// cached copy when constructing ClassTable. Isolate::Current might not
// be available at this point yet.
table_.store(static_cast<RawClass**>(calloc(capacity_, sizeof(RawClass*))));
} else {
// Duplicate the class table from the VM isolate.
ClassTable* vm_class_table = Dart::vm_isolate()->class_table();
capacity_ = vm_class_table->capacity_;
// Note that [calloc] will zero-initialize the memory.
RawClass** table =
static_cast<RawClass**>(calloc(capacity_, sizeof(RawClass*)));
// The following cids don't have a corresponding class object in Dart code.
// We therefore need to initialize them eagerly.
for (intptr_t i = kObjectCid; i < kInstanceCid; i++) {
table[i] = vm_class_table->At(i);
}
table[kTypeArgumentsCid] = vm_class_table->At(kTypeArgumentsCid);
table[kFreeListElement] = vm_class_table->At(kFreeListElement);
table[kForwardingCorpse] = vm_class_table->At(kForwardingCorpse);
table[kDynamicCid] = vm_class_table->At(kDynamicCid);
table[kVoidCid] = vm_class_table->At(kVoidCid);
table[kNeverCid] = vm_class_table->At(kNeverCid);
// Don't use set_table because caller is supposed to set up isolates
// cached copy when constructing ClassTable. Isolate::Current might not
// be available at this point yet.
table_.store(table);
}
}
ClassTable::~ClassTable() {
if (old_class_tables_ != nullptr) {
FreeOldTables();
delete old_class_tables_;
}
free(table_.load());
}
void ClassTable::AddOldTable(RawClass** old_class_table) {
ASSERT(Thread::Current()->IsMutatorThread());
old_class_tables_->Add(old_class_table);
}
void ClassTable::FreeOldTables() {
while (old_class_tables_->length() > 0) {
free(old_class_tables_->RemoveLast());
}
}
void SharedClassTable::AddOldTable(intptr_t* old_table) {
ASSERT(Thread::Current()->IsMutatorThread());
old_tables_->Add(old_table);
}
void SharedClassTable::FreeOldTables() {
while (old_tables_->length() > 0) {
free(old_tables_->RemoveLast());
}
}
void ClassTable::Register(const Class& cls) {
ASSERT(Thread::Current()->IsMutatorThread());
const intptr_t index = cls.id();
// During the transition period we would like [SharedClassTable] to operate in
// parallel to [ClassTable].
const intptr_t instance_size =
cls.is_abstract() ? 0 : Class::host_instance_size(cls.raw());
const intptr_t expected_cid =
shared_class_table_->Register(index, instance_size);
if (index != kIllegalCid) {
ASSERT(index > 0 && index < kNumPredefinedCids && index < top_);
ASSERT(table_.load()[index] == nullptr);
table_.load()[index] = cls.raw();
} else {
if (top_ == capacity_) {
const intptr_t new_capacity = capacity_ + kCapacityIncrement;
Grow(new_capacity);
}
ASSERT(top_ < capacity_);
cls.set_id(top_);
table_.load()[top_] = cls.raw();
top_++; // Increment next index.
}
ASSERT(expected_cid == cls.id());
}
intptr_t SharedClassTable::Register(intptr_t index, intptr_t size) {
if (!Class::is_valid_id(top_)) {
FATAL1("Fatal error in SharedClassTable::Register: invalid index %" Pd "\n",
top_);
}
ASSERT(Thread::Current()->IsMutatorThread());
if (index != kIllegalCid) {
// We are registring the size of a predefined class.
ASSERT(index > 0 && index < kNumPredefinedCids);
SetSizeAt(index, size);
return index;
} else {
ASSERT(size == 0);
if (top_ == capacity_) {
const intptr_t new_capacity = capacity_ + kCapacityIncrement;
Grow(new_capacity);
}
ASSERT(top_ < capacity_);
table_.load()[top_] = size;
return top_++; // Increment next index.
}
}
void ClassTable::AllocateIndex(intptr_t index) {
// This is called by a snapshot reader.
shared_class_table_->AllocateIndex(index);
ASSERT(Class::is_valid_id(index));
if (index >= capacity_) {
const intptr_t new_capacity = index + kCapacityIncrement;
Grow(new_capacity);
}
ASSERT(table_.load()[index] == nullptr);
if (index >= top_) {
top_ = index + 1;
}
ASSERT(top_ == shared_class_table_->top_);
ASSERT(capacity_ == shared_class_table_->capacity_);
}
void ClassTable::Grow(intptr_t new_capacity) {
ASSERT(new_capacity > capacity_);
auto old_table = table_.load();
auto new_table = static_cast<RawClass**>(
malloc(new_capacity * sizeof(RawClass*))); // NOLINT
intptr_t i;
for (i = 0; i < capacity_; i++) {
// Don't use memmove, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_table[i] = old_table[i];
}
for (; i < new_capacity; i++) {
// Don't use memset, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_table[i] = 0;
}
old_class_tables_->Add(old_table);
set_table(new_table);
capacity_ = new_capacity;
}
void SharedClassTable::AllocateIndex(intptr_t index) {
// This is called by a snapshot reader.
ASSERT(Class::is_valid_id(index));
if (index >= capacity_) {
const intptr_t new_capacity = index + kCapacityIncrement;
Grow(new_capacity);
}
ASSERT(table_.load()[index] == 0);
if (index >= top_) {
top_ = index + 1;
}
}
void SharedClassTable::Grow(intptr_t new_capacity) {
ASSERT(new_capacity >= capacity_);
RelaxedAtomic<intptr_t>* old_table = table_.load();
RelaxedAtomic<intptr_t>* new_table =
reinterpret_cast<RelaxedAtomic<intptr_t>*>(
malloc(new_capacity * sizeof(RelaxedAtomic<intptr_t>))); // NOLINT
intptr_t i;
for (i = 0; i < capacity_; i++) {
// Don't use memmove, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_table[i] = old_table[i];
}
for (; i < new_capacity; i++) {
// Don't use memset, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_table[i] = 0;
}
#if !defined(PRODUCT)
auto old_trace_table = trace_allocation_table_.load();
auto new_trace_table =
static_cast<uint8_t*>(malloc(new_capacity * sizeof(uint8_t))); // NOLINT
for (i = 0; i < capacity_; i++) {
// Don't use memmove, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_trace_table[i] = old_trace_table[i];
}
for (; i < new_capacity; i++) {
// Don't use memset, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_trace_table[i] = 0;
}
#endif
old_tables_->Add(old_table);
table_.store(new_table);
NOT_IN_PRODUCT(old_tables_->Add(old_trace_table));
NOT_IN_PRODUCT(trace_allocation_table_.store(new_trace_table));
#if defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
auto old_unboxed_fields_map = unboxed_fields_map_;
auto new_unboxed_fields_map = static_cast<UnboxedFieldBitmap*>(
malloc(new_capacity * sizeof(UnboxedFieldBitmap)));
for (i = 0; i < capacity_; i++) {
// Don't use memmove, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_unboxed_fields_map[i] = old_unboxed_fields_map[i];
}
for (; i < new_capacity; i++) {
// Don't use memset, which changes this from a relaxed atomic operation
// to a non-atomic operation.
new_unboxed_fields_map[i] = UnboxedFieldBitmap(0);
}
old_tables_->Add(old_unboxed_fields_map);
unboxed_fields_map_ = new_unboxed_fields_map;
#endif // defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
capacity_ = new_capacity;
}
void ClassTable::Unregister(intptr_t index) {
shared_class_table_->Unregister(index);
table_.load()[index] = nullptr;
}
void SharedClassTable::Unregister(intptr_t index) {
table_.load()[index] = 0;
#if defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
unboxed_fields_map_[index].Reset();
#endif // defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
}
void ClassTable::Remap(intptr_t* old_to_new_cid) {
ASSERT(Thread::Current()->IsAtSafepoint());
const intptr_t num_cids = NumCids();
std::unique_ptr<RawClass*[]> cls_by_old_cid(new RawClass*[num_cids]);
auto* table = table_.load();
memmove(cls_by_old_cid.get(), table, sizeof(RawClass*) * num_cids);
for (intptr_t i = 0; i < num_cids; i++) {
table[old_to_new_cid[i]] = cls_by_old_cid[i];
}
}
void SharedClassTable::Remap(intptr_t* old_to_new_cid) {
ASSERT(Thread::Current()->IsAtSafepoint());
const intptr_t num_cids = NumCids();
std::unique_ptr<intptr_t[]> size_by_old_cid(new intptr_t[num_cids]);
auto* table = table_.load();
for (intptr_t i = 0; i < num_cids; i++) {
size_by_old_cid[i] = table[i];
}
for (intptr_t i = 0; i < num_cids; i++) {
table[old_to_new_cid[i]] = size_by_old_cid[i];
}
#if defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
std::unique_ptr<UnboxedFieldBitmap[]> unboxed_fields_by_old_cid(
new UnboxedFieldBitmap[num_cids]);
for (intptr_t i = 0; i < num_cids; i++) {
unboxed_fields_by_old_cid[i] = unboxed_fields_map_[i];
}
for (intptr_t i = 0; i < num_cids; i++) {
unboxed_fields_map_[old_to_new_cid[i]] = unboxed_fields_by_old_cid[i];
}
#endif // defined(SUPPORT_UNBOXED_INSTANCE_FIELDS)
}
void ClassTable::VisitObjectPointers(ObjectPointerVisitor* visitor) {
ASSERT(visitor != NULL);
visitor->set_gc_root_type("class table");
if (top_ != 0) {
auto* table = table_.load();
RawObject** from = reinterpret_cast<RawObject**>(&table[0]);
RawObject** to = reinterpret_cast<RawObject**>(&table[top_ - 1]);
visitor->VisitPointers(from, to);
}
visitor->clear_gc_root_type();
}
void ClassTable::CopySizesFromClassObjects() {
ASSERT(kIllegalCid == 0);
for (intptr_t i = 1; i < top_; i++) {
SetAt(i, At(i));
}
}
void ClassTable::Validate() {
Class& cls = Class::Handle();
for (intptr_t cid = kNumPredefinedCids; cid < top_; cid++) {
// Some of the class table entries maybe NULL as we create some
// top level classes but do not add them to the list of anonymous
// classes in a library if there are no top level fields or functions.
// Since there are no references to these top level classes they are
// not written into a full snapshot and will not be recreated when
// we read back the full snapshot. These class slots end up with NULL
// entries.
if (HasValidClassAt(cid)) {
cls = At(cid);
ASSERT(cls.IsClass());
ASSERT(cls.id() == cid);
}
}
}
void ClassTable::Print() {
Class& cls = Class::Handle();
String& name = String::Handle();
for (intptr_t i = 1; i < top_; i++) {
if (!HasValidClassAt(i)) {
continue;
}
cls = At(i);
if (cls.raw() != reinterpret_cast<RawClass*>(0)) {
name = cls.Name();
OS::PrintErr("%" Pd ": %s\n", i, name.ToCString());
}
}
}
void ClassTable::SetAt(intptr_t index, RawClass* raw_cls) {
// This is called by snapshot reader and class finalizer.
ASSERT(index < capacity_);
const intptr_t size =
raw_cls == nullptr ? 0 : Class::host_instance_size(raw_cls);
shared_class_table_->SetSizeAt(index, size);
table_.load()[index] = raw_cls;
}
#ifndef PRODUCT
void ClassTable::PrintToJSONObject(JSONObject* object) {
Class& cls = Class::Handle();
object->AddProperty("type", "ClassList");
{
JSONArray members(object, "classes");
for (intptr_t i = 1; i < top_; i++) {
if (HasValidClassAt(i)) {
cls = At(i);
members.AddValue(cls);
}
}
}
}
bool SharedClassTable::ShouldUpdateSizeForClassId(intptr_t cid) {
return !RawObject::IsVariableSizeClassId(cid);
}
intptr_t SharedClassTable::ClassOffsetFor(intptr_t cid) {
return cid * sizeof(uint8_t); // NOLINT
}
void ClassTable::AllocationProfilePrintJSON(JSONStream* stream, bool internal) {
Isolate* isolate = Isolate::Current();
ASSERT(isolate != NULL);
auto isolate_group = isolate->group();
Heap* heap = isolate_group->heap();
ASSERT(heap != NULL);
JSONObject obj(stream);
obj.AddProperty("type", "AllocationProfile");
if (isolate_group->last_allocationprofile_accumulator_reset_timestamp() !=
0) {
obj.AddPropertyF(
"dateLastAccumulatorReset", "%" Pd64 "",
isolate_group->last_allocationprofile_accumulator_reset_timestamp());
}
if (isolate_group->last_allocationprofile_gc_timestamp() != 0) {
obj.AddPropertyF("dateLastServiceGC", "%" Pd64 "",
isolate_group->last_allocationprofile_gc_timestamp());
}
if (internal) {
JSONObject heaps(&obj, "_heaps");
{ heap->PrintToJSONObject(Heap::kNew, &heaps); }
{ heap->PrintToJSONObject(Heap::kOld, &heaps); }
}
{
JSONObject memory(&obj, "memoryUsage");
{ heap->PrintMemoryUsageJSON(&memory); }
}
Thread* thread = Thread::Current();
CountObjectsVisitor visitor(thread, NumCids());
{
HeapIterationScope iter(thread);
iter.IterateObjects(&visitor);
isolate->group()->VisitWeakPersistentHandles(&visitor);
}
{
JSONArray arr(&obj, "members");
Class& cls = Class::Handle();
for (intptr_t i = 3; i < top_; i++) {
if (!HasValidClassAt(i)) continue;
cls = At(i);
if (cls.IsNull()) continue;
JSONObject obj(&arr);
obj.AddProperty("type", "ClassHeapStats");
obj.AddProperty("class", cls);
intptr_t count = visitor.new_count_[i] + visitor.old_count_[i];
intptr_t size = visitor.new_size_[i] + visitor.old_size_[i];
obj.AddProperty64("instancesAccumulated", count);
obj.AddProperty64("accumulatedSize", size);
obj.AddProperty64("instancesCurrent", count);
obj.AddProperty64("bytesCurrent", size);
if (internal) {
{
JSONArray new_stats(&obj, "_new");
new_stats.AddValue(visitor.new_count_[i]);
new_stats.AddValue(visitor.new_size_[i]);
new_stats.AddValue(visitor.new_external_size_[i]);
}
{
JSONArray old_stats(&obj, "_old");
old_stats.AddValue(visitor.old_count_[i]);
old_stats.AddValue(visitor.old_size_[i]);
old_stats.AddValue(visitor.old_external_size_[i]);
}
}
}
}
}
#endif // !PRODUCT
} // namespace dart
| 32.818692 | 80 | 0.685499 | [
"object"
] |
338d23f339da474349c89def83af7a35417cf071 | 30,311 | cpp | C++ | boost/libs/concept_check/stl_concept_covering.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 11 | 2015-01-08T08:33:44.000Z | 2019-07-12T06:14:54.000Z | boost/libs/concept_check/stl_concept_covering.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 61 | 2015-05-27T11:20:11.000Z | 2019-12-20T15:06:21.000Z | boost/libs/concept_check/stl_concept_covering.cpp | randolphwong/mcsema | eb5b376736e7f57ff0a61f7e4e5a436bbb874720 | [
"BSD-3-Clause"
] | 9 | 2015-09-09T02:38:32.000Z | 2021-01-30T00:24:24.000Z | // (C) Copyright Jeremy Siek 2000-2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <algorithm>
#include <numeric>
#include <boost/config.hpp>
#include <boost/concept_check.hpp>
#include <boost/concept_archetype.hpp>
/*
This file uses the archetype classes to find out which concepts
actually *cover* the STL algorithms true requirements. The
archetypes/concepts chosen do not necessarily match the C++ standard
or the SGI STL documentation, but instead were chosen based on the
minimal concepts that current STL implementations require, which in
many cases is less stringent than the standard. In some places there
was significant differences in the implementations' requirements and
in those places macros were used to select different requirements,
the purpose being to document what the requirements of various
implementations are. It is an open issue as to whether the C++
standard should be changed to reflect these weaker requirements.
*/
boost::detail::dummy_constructor dummy_cons;
// This is a special concept needed for std::swap_ranges.
// It is mutually convertible, and also SGIAssignable
template <class T>
class mutually_convertible_archetype
{
private:
mutually_convertible_archetype() { }
public:
mutually_convertible_archetype(const mutually_convertible_archetype&) { }
mutually_convertible_archetype&
operator=(const mutually_convertible_archetype&)
{ return *this; }
mutually_convertible_archetype(boost::detail::dummy_constructor) { }
template <class U>
mutually_convertible_archetype&
operator=(const mutually_convertible_archetype<U>&)
{ return *this; }
};
// for std::accumulate
namespace accum
{
typedef boost::sgi_assignable_archetype<> Ret;
struct T {
T(const Ret&) { }
T(boost::detail::dummy_constructor x) { }
};
typedef boost::null_archetype<> Tin;
Ret operator+(const T&, const Tin&) {
return Ret(dummy_cons);
}
}
// for std::inner_product
namespace inner_prod
{
typedef boost::sgi_assignable_archetype<> RetAdd;
typedef boost::sgi_assignable_archetype<> RetMult;
struct T {
T(const RetAdd&) { }
T(boost::detail::dummy_constructor x) { }
};
typedef boost::null_archetype<int> Tin1;
typedef boost::null_archetype<char> Tin2;
}
namespace boost { // so Koenig lookup will find
inner_prod::RetMult
operator*(const inner_prod::Tin1&, const inner_prod::Tin2&) {
return inner_prod::RetMult(dummy_cons);
}
inner_prod::RetAdd
operator+(const inner_prod::T&,
const inner_prod::RetMult&) {
return inner_prod::RetAdd(dummy_cons);
}
}
// for std::partial_sum and adj_diff
namespace part_sum
{
class T {
public:
typedef boost::sgi_assignable_archetype<> Ret;
T(const Ret&) { }
T(boost::detail::dummy_constructor x) { }
private:
T() { }
};
T::Ret operator+(const T&, const T&) {
return T::Ret(dummy_cons);
}
T::Ret operator-(const T&, const T&) {
return T::Ret(dummy_cons);
}
}
// for std::power
namespace power_stuff {
struct monoid_archetype {
monoid_archetype(boost::detail::dummy_constructor x) { }
};
boost::multipliable_archetype<monoid_archetype>
identity_element
(std::multiplies< boost::multipliable_archetype<monoid_archetype> >)
{
return boost::multipliable_archetype<monoid_archetype>(dummy_cons);
}
}
struct tag1 { };
struct tag2 { };
int
main()
{
using namespace boost;
//===========================================================================
// Non-mutating Algorithms
{
input_iterator_archetype< null_archetype<> > in;
unary_function_archetype< null_archetype<> , null_archetype<> >
f(dummy_cons);
std::for_each(in, in, f);
}
// gcc bug
{
typedef equality_comparable2_first_archetype<> Left;
input_iterator_archetype< Left > in;
equality_comparable2_second_archetype<> value(dummy_cons);
in = std::find(in, in, value);
}
{
typedef null_archetype<> T;
input_iterator_archetype<T> in;
unary_predicate_archetype<T> pred(dummy_cons);
in = std::find_if(in, in, pred);
}
{
forward_iterator_archetype< equality_comparable_archetype<> > fo;
fo = std::adjacent_find(fo, fo);
}
{
forward_iterator_archetype<
convertible_to_archetype< null_archetype<> > > fo;
binary_predicate_archetype<null_archetype<> , null_archetype<> >
pred(dummy_cons);
fo = std::adjacent_find(fo, fo, pred);
}
// gcc bug
{
typedef equal_op_first_archetype<> Left;
input_iterator_archetype<Left> in;
typedef equal_op_second_archetype<> Right;
forward_iterator_archetype<Right> fo;
in = std::find_first_of(in, in, fo, fo);
}
{
typedef equal_op_first_archetype<> Left;
typedef input_iterator_archetype<Left> InIter;
InIter in;
function_requires< InputIterator<InIter> >();
equal_op_second_archetype<> value(dummy_cons);
std::iterator_traits<InIter>::difference_type
n = std::count(in, in, value);
ignore_unused_variable_warning(n);
}
{
typedef input_iterator_archetype< null_archetype<> > InIter;
InIter in;
unary_predicate_archetype<null_archetype<> > pred(dummy_cons);
std::iterator_traits<InIter>::difference_type
n = std::count_if(in, in, pred);
ignore_unused_variable_warning(n);
}
// gcc bug
{
typedef equal_op_first_archetype<> Left;
typedef input_iterator_archetype<Left> InIter1;
InIter1 in1;
typedef equal_op_second_archetype<> Right;
typedef input_iterator_archetype<Right> InIter2;
InIter2 in2;
std::pair<InIter1, InIter2> p = std::mismatch(in1, in1, in2);
ignore_unused_variable_warning(p);
}
{
typedef input_iterator_archetype<null_archetype<> > InIter;
InIter in1, in2;
binary_predicate_archetype<null_archetype<> , null_archetype<> >
pred(dummy_cons);
std::pair<InIter, InIter> p = std::mismatch(in1, in1, in2, pred);
ignore_unused_variable_warning(p);
}
// gcc bug
{
typedef equality_comparable2_first_archetype<> Left;
input_iterator_archetype<Left> in1;
typedef equality_comparable2_second_archetype<> Right;
input_iterator_archetype<Right> in2;
bool b = std::equal(in1, in1, in2);
ignore_unused_variable_warning(b);
}
{
input_iterator_archetype< null_archetype<> >
in1, in2;
binary_predicate_archetype<null_archetype<> , null_archetype<> >
pred(dummy_cons);
bool b = std::equal(in1, in1, in2, pred);
ignore_unused_variable_warning(b);
}
{
typedef equality_comparable2_first_archetype<> Left;
forward_iterator_archetype<Left> fo1;
typedef equality_comparable2_second_archetype<> Right;
forward_iterator_archetype<Right> fo2;
fo1 = std::search(fo1, fo1, fo2, fo2);
}
{
typedef equality_comparable2_first_archetype<
convertible_to_archetype<null_archetype<> > > Left;
forward_iterator_archetype<Left> fo1;
typedef equality_comparable2_second_archetype<
convertible_to_archetype<null_archetype<> > > Right;
forward_iterator_archetype<Right> fo2;
binary_predicate_archetype<null_archetype<> , null_archetype<> >
pred(dummy_cons);
fo1 = std::search(fo1, fo1, fo2, fo2, pred);
}
{
typedef equality_comparable2_first_archetype<> Left;
forward_iterator_archetype<Left> fo;
equality_comparable2_second_archetype<> value(dummy_cons);
int n = 1;
fo = std::search_n(fo, fo, n, value);
}
{
forward_iterator_archetype<
convertible_to_archetype<null_archetype<> > > fo;
convertible_to_archetype<null_archetype<> > value(dummy_cons);
binary_predicate_archetype<null_archetype<> , null_archetype<> >
pred(dummy_cons);
int n = 1;
fo = std::search_n(fo, fo, n, value, pred);
}
{
typedef equality_comparable2_first_archetype<> Left;
forward_iterator_archetype<Left> fo1;
typedef equality_comparable2_second_archetype<null_archetype<> > Right;
forward_iterator_archetype<Right> fo2;
fo1 = std::find_end(fo1, fo1, fo2, fo2);
}
{
// equality comparable required because find_end() calls search
typedef equality_comparable2_first_archetype<
convertible_to_archetype<null_archetype<> > > Left;
forward_iterator_archetype<Left> fo1;
typedef equality_comparable2_second_archetype<
convertible_to_archetype<null_archetype<> > > Right;
forward_iterator_archetype<Right> fo2;
binary_predicate_archetype<null_archetype<> , null_archetype<> >
pred(dummy_cons);
fo1 = std::find_end(fo1, fo1, fo2, fo2, pred);
}
//===========================================================================
// Mutating Algorithms
{
typedef null_archetype<> T;
input_iterator_archetype<T> in;
output_iterator_archetype<T> out(dummy_cons);
out = std::copy(in, in, out);
}
{
typedef assignable_archetype<> OutT;
typedef convertible_to_archetype<OutT> InT;
bidirectional_iterator_archetype<InT> bid_in;
mutable_bidirectional_iterator_archetype<OutT> bid_out;
bid_out = std::copy_backward(bid_in, bid_in, bid_out);
}
{
sgi_assignable_archetype<> a(dummy_cons), b(dummy_cons);
std::swap(a, b);
}
{
typedef sgi_assignable_archetype<> T;
mutable_forward_iterator_archetype<T> a, b;
std::iter_swap(a, b);
}
{
typedef mutually_convertible_archetype<int> Tin;
typedef mutually_convertible_archetype<char> Tout;
mutable_forward_iterator_archetype<Tin> fi1;
mutable_forward_iterator_archetype<Tout> fi2;
fi2 = std::swap_ranges(fi1, fi1, fi2);
}
{
typedef null_archetype<int> Tin;
typedef null_archetype<char> Tout;
input_iterator_archetype<Tin> in;
output_iterator_archetype<Tout> out(dummy_cons);
unary_function_archetype<null_archetype<> ,
convertible_to_archetype<Tout> > op(dummy_cons);
out = std::transform(in, in, out, op);
}
{
typedef null_archetype<int> Tin1;
typedef null_archetype<char> Tin2;
typedef null_archetype<double> Tout;
input_iterator_archetype<Tin1> in1;
input_iterator_archetype<Tin2> in2;
output_iterator_archetype<Tout> out(dummy_cons);
binary_function_archetype<Tin1, Tin2,
convertible_to_archetype<Tout> > op(dummy_cons);
out = std::transform(in1, in1, in2, out, op);
}
{
typedef equality_comparable2_first_archetype<
assignable_archetype<> > FT;
mutable_forward_iterator_archetype<FT> fi;
equality_comparable2_second_archetype<
convertible_to_archetype<FT> > value(dummy_cons);
std::replace(fi, fi, value, value);
}
{
typedef null_archetype<> PredArg;
typedef assignable_archetype<
convertible_to_archetype<PredArg> > FT;
mutable_forward_iterator_archetype<FT> fi;
unary_predicate_archetype<PredArg> pred(dummy_cons);
convertible_to_archetype<FT> value(dummy_cons);
std::replace_if(fi, fi, pred, value);
}
// gcc bug
{
// Issue, the use of ?: inside replace_copy() complicates things
typedef equal_op_first_archetype<> Tin;
typedef null_archetype<> Tout;
typedef equal_op_second_archetype< convertible_to_archetype<Tout> > T;
input_iterator_archetype<Tin> in;
output_iterator_archetype<Tout> out(dummy_cons);
T value(dummy_cons);
out = std::replace_copy(in, in, out, value, value);
}
{
// The issue of ?: also affects this function
typedef null_archetype<> Tout;
typedef assignable_archetype< convertible_to_archetype<Tout> > Tin;
input_iterator_archetype<Tin> in;
output_iterator_archetype<Tout> out(dummy_cons);
unary_predicate_archetype<Tin> pred(dummy_cons);
Tin value(dummy_cons);
out = std::replace_copy_if(in, in, out, pred, value);
}
{
typedef assignable_archetype<> FT;
mutable_forward_iterator_archetype<FT> fi;
typedef convertible_to_archetype<FT> T;
T value(dummy_cons);
std::fill(fi, fi, value);
}
{
typedef null_archetype<> Tout;
typedef convertible_to_archetype<Tout> T;
output_iterator_archetype<Tout> out(dummy_cons);
T value(dummy_cons);
int n = 1;
out = std::fill_n(out, n, value);
}
{
typedef assignable_archetype<> FT;
typedef convertible_to_archetype<FT> Ret;
mutable_forward_iterator_archetype<FT> fi;
generator_archetype<Ret> gen;
std::generate(fi, fi, gen);
}
{
typedef assignable_archetype<> FT;
typedef convertible_to_archetype<FT> Ret;
mutable_forward_iterator_archetype<FT> fi;
generator_archetype<Ret> gen;
int n = 1;
std::generate_n(fi, n, gen);
}
{
typedef assignable_archetype< equality_comparable2_first_archetype<> > FT;
typedef equality_comparable2_second_archetype<> T;
mutable_forward_iterator_archetype<FT> fi;
T value(dummy_cons);
fi = std::remove(fi, fi, value);
}
{
typedef assignable_archetype<> FT;
mutable_forward_iterator_archetype<FT> fi;
typedef null_archetype<> PredArg;
unary_predicate_archetype<PredArg> pred(dummy_cons);
fi = std::remove_if(fi, fi, pred);
}
// gcc bug
{
typedef null_archetype<> Tout;
typedef equality_comparable2_first_archetype<
convertible_to_archetype<Tout> > Tin;
typedef equality_comparable2_second_archetype<> T;
input_iterator_archetype<Tin> in;
output_iterator_archetype<Tout> out(dummy_cons);
T value(dummy_cons);
out = std::remove_copy(in, in, out, value);
}
{
typedef null_archetype<> T;
input_iterator_archetype<T> in;
output_iterator_archetype<T> out(dummy_cons);
unary_predicate_archetype<T> pred(dummy_cons);
out = std::remove_copy_if(in, in, out, pred);
}
{
typedef sgi_assignable_archetype< equality_comparable_archetype<> > T;
mutable_forward_iterator_archetype<T> fi;
fi = std::unique(fi, fi);
}
{
typedef null_archetype<int> Arg1;
typedef null_archetype<char> Arg2;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg1,
convertible_to_archetype<Arg2> > > FT;
mutable_forward_iterator_archetype<FT> fi;
binary_predicate_archetype<Arg1, Arg2> pred(dummy_cons);
fi = std::unique(fi, fi, pred);
}
// gcc bug
{
typedef equality_comparable_archetype< sgi_assignable_archetype<> > T;
input_iterator_archetype<T> in;
output_iterator_archetype<T> out(dummy_cons);
out = std::unique_copy(in, in, out);
}
{
typedef sgi_assignable_archetype<> T;
input_iterator_archetype<T> in;
output_iterator_archetype<T> out(dummy_cons);
binary_predicate_archetype<T, T> pred(dummy_cons);
out = std::unique_copy(in, in, out, pred);
}
{
typedef sgi_assignable_archetype<> T;
mutable_bidirectional_iterator_archetype<T> bi;
std::reverse(bi, bi);
}
{
typedef null_archetype<> Tout;
typedef convertible_to_archetype<Tout> Tin;
bidirectional_iterator_archetype<Tin> bi;
output_iterator_archetype<Tout> out(dummy_cons);
out = std::reverse_copy(bi, bi, out);
}
{
typedef sgi_assignable_archetype<> T;
mutable_forward_iterator_archetype<T> fi;
// Issue, SGI STL is not have void return type, C++ standard does
std::rotate(fi, fi, fi);
}
{
typedef null_archetype<> Tout;
typedef convertible_to_archetype<Tout> FT;
forward_iterator_archetype<FT> fi;
output_iterator_archetype<Tout> out(dummy_cons);
out = std::rotate_copy(fi, fi, fi, out);
}
{
typedef sgi_assignable_archetype<> T;
mutable_random_access_iterator_archetype<T> ri;
std::random_shuffle(ri, ri);
}
{
typedef sgi_assignable_archetype<> T;
mutable_random_access_iterator_archetype<T> ri;
unary_function_archetype<std::ptrdiff_t, std::ptrdiff_t> ran(dummy_cons);
std::random_shuffle(ri, ri, ran);
}
{
typedef null_archetype<> PredArg;
typedef sgi_assignable_archetype<convertible_to_archetype<PredArg> > FT;
mutable_bidirectional_iterator_archetype<FT> bi;
unary_predicate_archetype<PredArg> pred(dummy_cons);
bi = std::partition(bi, bi, pred);
}
{
typedef null_archetype<> PredArg;
typedef sgi_assignable_archetype<convertible_to_archetype<PredArg> > FT;
mutable_forward_iterator_archetype<FT> fi;
unary_predicate_archetype<PredArg> pred(dummy_cons);
fi = std::stable_partition(fi, fi, pred);
}
//===========================================================================
// Sorting Algorithms
{
typedef sgi_assignable_archetype<
less_than_comparable_archetype<> > T;
mutable_random_access_iterator_archetype<T> ri;
std::sort(ri, ri);
}
{
typedef null_archetype<> Arg;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg> > T;
mutable_random_access_iterator_archetype<T> ri;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
std::sort(ri, ri, comp);
}
{
typedef less_than_comparable_archetype<
sgi_assignable_archetype<> > ValueType;
mutable_random_access_iterator_archetype<ValueType> ri;
std::stable_sort(ri, ri);
}
{
typedef null_archetype<> Arg;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg> > ValueType;
mutable_random_access_iterator_archetype<ValueType> ri;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
std::stable_sort(ri, ri, comp);
}
{
typedef sgi_assignable_archetype<
less_than_comparable_archetype<> > T;
mutable_random_access_iterator_archetype<T> ri;
std::partial_sort(ri, ri, ri);
}
{
typedef null_archetype<> Arg;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg> > T;
mutable_random_access_iterator_archetype<T> ri;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
std::partial_sort(ri, ri, ri, comp);
}
// gcc bug
{
// This could be formulated so that the two iterators are not
// required to have the same value type, but it is messy.
typedef sgi_assignable_archetype<
less_than_comparable_archetype<> > T;
input_iterator_archetype<T> in;
mutable_random_access_iterator_archetype<T> ri_out;
ri_out = std::partial_sort_copy(in, in , ri_out, ri_out);
}
{
typedef sgi_assignable_archetype<> T;
input_iterator_archetype<T> in;
mutable_random_access_iterator_archetype<T> ri_out;
binary_predicate_archetype<T, T> comp(dummy_cons);
ri_out = std::partial_sort_copy(in, in , ri_out, ri_out, comp);
}
{
typedef sgi_assignable_archetype< less_than_comparable_archetype<> > T;
mutable_random_access_iterator_archetype<T> ri;
std::nth_element(ri, ri, ri);
}
{
typedef null_archetype<int> Arg1;
typedef null_archetype<char> Arg2;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg1,
convertible_to_archetype<Arg2> > > T;
mutable_random_access_iterator_archetype<T> ri;
binary_predicate_archetype<Arg1, Arg2> comp(dummy_cons);
std::nth_element(ri, ri, ri, comp);
}
{
#if defined(__GNUC__)
typedef less_than_op_first_archetype<> FT;
typedef less_than_op_second_archetype<> T;
#elif defined(__KCC)
// The KAI version of this uses a one-argument less-than function
// object.
typedef less_than_comparable_archetype<> T;
typedef convertible_to_archetype<T> FT;
#endif
forward_iterator_archetype<FT> fi;
T value(dummy_cons);
fi = std::lower_bound(fi, fi, value);
}
{
typedef null_archetype<int> Arg1;
typedef null_archetype<char> Arg2;
typedef convertible_to_archetype<Arg1> FT;
typedef convertible_to_archetype<Arg2> T;
forward_iterator_archetype<FT> fi;
T value(dummy_cons);
binary_predicate_archetype<Arg1, Arg2> comp(dummy_cons);
fi = std::lower_bound(fi, fi, value, comp);
}
{
#if defined(__GNUC__)
// Note, order of T,FT is flipped from lower_bound
typedef less_than_op_second_archetype<> FT;
typedef less_than_op_first_archetype<> T;
#elif defined(__KCC)
typedef less_than_comparable_archetype<> T;
typedef convertible_to_archetype<T> FT;
#endif
forward_iterator_archetype<FT> fi;
T value(dummy_cons);
fi = std::upper_bound(fi, fi, value);
}
{
typedef null_archetype<int> Arg1;
typedef null_archetype<char> Arg2;
// Note, order of T,FT is flipped from lower_bound
typedef convertible_to_archetype<Arg1> T;
typedef convertible_to_archetype<Arg2> FT;
forward_iterator_archetype<FT> fi;
T value(dummy_cons);
binary_predicate_archetype<Arg1, Arg2> comp(dummy_cons);
fi = std::upper_bound(fi, fi, value, comp);
}
{
#if defined(__GNUC__)
typedef less_than_op_first_archetype<
less_than_op_second_archetype< null_archetype<>, optag2>, optag1> FT;
typedef less_than_op_second_archetype<
less_than_op_first_archetype< null_archetype<>, optag2>, optag1> T;
#elif defined(__KCC)
typedef less_than_comparable_archetype<> T;
typedef convertible_to_archetype<T> FT;
#endif
typedef forward_iterator_archetype<FT> FIter;
FIter fi;
T value(dummy_cons);
std::pair<FIter,FIter> p = std::equal_range(fi, fi, value);
ignore_unused_variable_warning(p);
}
{
typedef null_archetype<int> Arg1;
typedef null_archetype<char> Arg2;
typedef convertible_to_archetype<Arg1,
convertible_to_archetype<Arg2> > FT;
typedef convertible_to_archetype<Arg2,
convertible_to_archetype<Arg1> > T;
typedef forward_iterator_archetype<FT> FIter;
FIter fi;
T value(dummy_cons);
binary_predicate_archetype<Arg1, Arg2> comp(dummy_cons);
std::pair<FIter,FIter> p = std::equal_range(fi, fi, value, comp);
ignore_unused_variable_warning(p);
}
{
#if defined(__GNUC__)
typedef less_than_op_first_archetype<
less_than_op_second_archetype<null_archetype<>, optag2>, optag1> FT;
typedef less_than_op_second_archetype<
less_than_op_first_archetype<null_archetype<>, optag2>, optag1> T;
#elif defined(__KCC)
typedef less_than_op_first_archetype< less_than_comparable_archetype<> > T;
typedef less_than_op_second_archetype< convertible_to_archetype<T> > FT;
#endif
forward_iterator_archetype<FT> fi;
T value(dummy_cons);
bool b = std::binary_search(fi, fi, value);
ignore_unused_variable_warning(b);
}
{
typedef null_archetype<int> Arg1;
typedef null_archetype<char> Arg2;
#if defined(__GNUC__) || defined(__KCC)
typedef convertible_to_archetype<Arg1,
convertible_to_archetype<Arg2> > FT;
typedef convertible_to_archetype<Arg2,
convertible_to_archetype<Arg1> > T;
#endif
typedef forward_iterator_archetype<FT> FIter;
FIter fi;
T value(dummy_cons);
binary_predicate_archetype<Arg1, Arg2> comp(dummy_cons);
bool b = std::binary_search(fi, fi, value, comp);
ignore_unused_variable_warning(b);
}
{
typedef null_archetype<> Tout;
#if defined(__GNUC__) || defined(__KCC)
typedef less_than_op_first_archetype<
less_than_op_second_archetype<
convertible_to_archetype<Tout>, optag2>, optag1 > Tin1;
typedef less_than_op_second_archetype<
less_than_op_first_archetype<
convertible_to_archetype<Tout>, optag2> ,optag1> Tin2;
#endif
// gcc bug
input_iterator_archetype<Tin1> in1;
input_iterator_archetype<Tin2> in2;
output_iterator_archetype<Tout> out(dummy_cons);
out = std::merge(in1, in1, in2, in2, out);
out = std::set_union(in1, in1, in2, in2, out);
out = std::set_intersection(in1, in1, in2, in2, out);
out = std::set_difference(in1, in1, in2, in2, out);
out = std::set_symmetric_difference(in1, in1, in2, in2, out);
}
{
typedef null_archetype<> T;
input_iterator_archetype<T> in1;
input_iterator_archetype<T,2> in2;
typedef convertible_from_archetype<T> Tout;
output_iterator_archetype<T> out(dummy_cons);
binary_predicate_archetype<T, T> comp(dummy_cons);
out = std::merge(in1, in1, in2, in2, out, comp);
out = std::set_union(in1, in1, in2, in2, out, comp);
out = std::set_intersection(in1, in1, in2, in2, out, comp);
out = std::set_difference(in1, in1, in2, in2, out, comp);
out = std::set_symmetric_difference(in1, in1, in2, in2, out, comp);
}
{
typedef sgi_assignable_archetype<
less_than_comparable_archetype<> > T;
mutable_bidirectional_iterator_archetype<T> bi;
std::inplace_merge(bi, bi, bi);
}
{
typedef null_archetype<> Arg;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg> > T;
mutable_bidirectional_iterator_archetype<T> bi;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
std::inplace_merge(bi, bi, bi, comp);
}
// gcc bug
{
typedef less_than_op_first_archetype<
less_than_op_second_archetype<null_archetype<>, optag1>, optag2> Tin1;
typedef less_than_op_second_archetype<
less_than_op_first_archetype<null_archetype<>, optag1>, optag2> Tin2;
input_iterator_archetype<Tin1> in1;
input_iterator_archetype<Tin2> in2;
bool b = std::includes(in1, in1, in2, in2);
b = std::lexicographical_compare(in1, in1, in2, in2);
ignore_unused_variable_warning(b);
}
{
typedef null_archetype<int> Tin;
input_iterator_archetype<Tin> in1;
input_iterator_archetype<Tin,1> in2;
binary_predicate_archetype<Tin, Tin> comp(dummy_cons);
bool b = std::includes(in1, in1, in2, in2, comp);
b = std::lexicographical_compare(in1, in1, in2, in2, comp);
ignore_unused_variable_warning(b);
}
{
typedef sgi_assignable_archetype<
less_than_comparable_archetype<> > T;
mutable_random_access_iterator_archetype<T> ri;
std::push_heap(ri, ri);
std::pop_heap(ri, ri);
std::make_heap(ri, ri);
std::sort_heap(ri, ri);
}
{
typedef null_archetype<> Arg;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg> > T;
mutable_random_access_iterator_archetype<T> ri;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
std::push_heap(ri, ri, comp);
std::pop_heap(ri, ri, comp);
std::make_heap(ri, ri, comp);
std::sort_heap(ri, ri, comp);
}
{
typedef less_than_comparable_archetype<> T;
T a(dummy_cons), b(dummy_cons);
BOOST_USING_STD_MIN();
BOOST_USING_STD_MAX();
const T& c = min BOOST_PREVENT_MACRO_SUBSTITUTION(a, b);
const T& d = max BOOST_PREVENT_MACRO_SUBSTITUTION(a, b);
ignore_unused_variable_warning(c);
ignore_unused_variable_warning(d);
}
{
typedef null_archetype<> Arg;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
typedef convertible_to_archetype<Arg> T;
T a(dummy_cons), b(dummy_cons);
BOOST_USING_STD_MIN();
BOOST_USING_STD_MAX();
const T& c = min BOOST_PREVENT_MACRO_SUBSTITUTION(a, b, comp);
const T& d = max BOOST_PREVENT_MACRO_SUBSTITUTION(a, b, comp);
ignore_unused_variable_warning(c);
ignore_unused_variable_warning(d);
}
{
typedef less_than_comparable_archetype<> T;
forward_iterator_archetype<T> fi;
fi = std::min_element(fi, fi);
fi = std::max_element(fi, fi);
}
{
typedef null_archetype<> Arg;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
typedef convertible_to_archetype<Arg> T;
forward_iterator_archetype<T> fi;
fi = std::min_element(fi, fi, comp);
fi = std::max_element(fi, fi, comp);
}
{
typedef sgi_assignable_archetype<
less_than_comparable_archetype<> > T;
mutable_bidirectional_iterator_archetype<T> bi;
bool b = std::next_permutation(bi, bi);
b = std::prev_permutation(bi, bi);
ignore_unused_variable_warning(b);
}
{
typedef null_archetype<> Arg;
binary_predicate_archetype<Arg, Arg> comp(dummy_cons);
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg> > T;
mutable_bidirectional_iterator_archetype<T> bi;
bool b = std::next_permutation(bi, bi, comp);
b = std::prev_permutation(bi, bi, comp);
ignore_unused_variable_warning(b);
}
//===========================================================================
// Generalized Numeric Algorithms
{
// Bummer, couldn't use plus_op because of a problem with
// mutually recursive types.
input_iterator_archetype<accum::Tin> in;
accum::T init(dummy_cons);
init = std::accumulate(in, in, init);
}
{
typedef null_archetype<int> Arg1;
typedef null_archetype<char> Arg2;
typedef sgi_assignable_archetype<
convertible_to_archetype<Arg1> > T;
typedef convertible_to_archetype<T> Ret;
input_iterator_archetype<Arg2> in;
T init(dummy_cons);
binary_function_archetype<Arg1, Arg2, Ret> op(dummy_cons);
init = std::accumulate(in, in, init, op);
}
{
input_iterator_archetype<inner_prod::Tin1> in1;
input_iterator_archetype<inner_prod::Tin2> in2;
inner_prod::T init(dummy_cons);
init = std::inner_product(in1, in1, in2, init);
}
{
typedef null_archetype<int> MultArg1;
typedef null_archetype<char> MultArg2;
typedef null_archetype<short> AddArg1;
typedef null_archetype<long> AddArg2;
typedef sgi_assignable_archetype<
convertible_to_archetype<AddArg1> > T;
typedef convertible_to_archetype<AddArg2> RetMult;
typedef convertible_to_archetype<T> RetAdd;
input_iterator_archetype<MultArg1> in1;
input_iterator_archetype<MultArg2> in2;
T init(dummy_cons);
binary_function_archetype<MultArg1, MultArg2, RetMult> mult_op(dummy_cons);
binary_function_archetype<AddArg1, AddArg2, RetAdd> add_op(dummy_cons);
init = std::inner_product(in1, in1, in2, init, add_op, mult_op);
}
{
input_iterator_archetype<part_sum::T> in;
output_iterator_archetype<part_sum::T> out(dummy_cons);
out = std::partial_sum(in, in, out);
}
{
typedef sgi_assignable_archetype<> T;
input_iterator_archetype<T> in;
output_iterator_archetype<T> out(dummy_cons);
binary_function_archetype<T, T, T> add_op(dummy_cons);
out = std::partial_sum(in, in, out, add_op);
binary_function_archetype<T, T, T> subtract_op(dummy_cons);
out = std::adjacent_difference(in, in, out, subtract_op);
}
{
input_iterator_archetype<part_sum::T> in;
output_iterator_archetype<part_sum::T> out(dummy_cons);
out = std::adjacent_difference(in, in, out);
}
return 0;
}
| 33.382159 | 79 | 0.708951 | [
"object",
"transform"
] |
339076dbb4f21de9dbc21f45a4cdea63dd997d4c | 3,456 | cc | C++ | src/property.cc | TinkerEdgeR-Android/external_v8 | 7c9cad78aca05245a07529da3d689282cd554df9 | [
"BSD-3-Clause"
] | 27 | 2017-12-14T13:48:25.000Z | 2020-12-31T15:46:55.000Z | src/property.cc | TinkerEdgeR-Android/external_v8 | 7c9cad78aca05245a07529da3d689282cd554df9 | [
"BSD-3-Clause"
] | null | null | null | src/property.cc | TinkerEdgeR-Android/external_v8 | 7c9cad78aca05245a07529da3d689282cd554df9 | [
"BSD-3-Clause"
] | 3 | 2019-01-14T12:12:27.000Z | 2019-06-07T09:47:00.000Z | // Copyright 2014 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/property.h"
#include "src/field-type.h"
#include "src/handles-inl.h"
#include "src/objects-inl.h"
#include "src/ostreams.h"
namespace v8 {
namespace internal {
std::ostream& operator<<(std::ostream& os,
const PropertyAttributes& attributes) {
os << "[";
os << (((attributes & READ_ONLY) == 0) ? "W" : "_"); // writable
os << (((attributes & DONT_ENUM) == 0) ? "E" : "_"); // enumerable
os << (((attributes & DONT_DELETE) == 0) ? "C" : "_"); // configurable
os << "]";
return os;
}
Descriptor Descriptor::DataField(Handle<Name> key, int field_index,
PropertyAttributes attributes,
Representation representation) {
return DataField(key, field_index, attributes, kMutable, representation,
FieldType::Any(key->GetIsolate()));
}
Descriptor Descriptor::DataField(Handle<Name> key, int field_index,
PropertyAttributes attributes,
PropertyConstness constness,
Representation representation,
Handle<Object> wrapped_field_type) {
DCHECK(wrapped_field_type->IsSmi() || wrapped_field_type->IsWeakCell());
PropertyDetails details(kData, attributes, kField, constness, representation,
field_index);
return Descriptor(key, wrapped_field_type, details);
}
Descriptor Descriptor::DataConstant(Handle<Name> key, int field_index,
Handle<Object> value,
PropertyAttributes attributes) {
if (FLAG_track_constant_fields) {
Handle<Object> any_type(FieldType::Any(), key->GetIsolate());
return DataField(key, field_index, attributes, kConst,
Representation::Tagged(), any_type);
} else {
return Descriptor(key, value, kData, attributes, kDescriptor, kConst,
value->OptimalRepresentation(), field_index);
}
}
// Outputs PropertyDetails as a dictionary details.
void PropertyDetails::PrintAsSlowTo(std::ostream& os) {
os << "(";
if (constness() == kConst) os << "const ";
os << (kind() == kData ? "data" : "accessor");
os << ", dictionary_index: " << dictionary_index();
os << ", attrs: " << attributes() << ")";
}
// Outputs PropertyDetails as a descriptor array details.
void PropertyDetails::PrintAsFastTo(std::ostream& os, PrintMode mode) {
os << "(";
if (constness() == kConst) os << "const ";
os << (kind() == kData ? "data" : "accessor");
if (location() == kField) {
os << " field";
if (mode & kPrintFieldIndex) {
os << " " << field_index();
}
if (mode & kPrintRepresentation) {
os << ":" << representation().Mnemonic();
}
} else {
os << " descriptor";
}
if (mode & kPrintPointer) {
os << ", p: " << pointer();
}
if (mode & kPrintAttributes) {
os << ", attrs: " << attributes();
}
os << ")";
}
#ifdef OBJECT_PRINT
void PropertyDetails::Print(bool dictionary_mode) {
OFStream os(stdout);
if (dictionary_mode) {
PrintAsSlowTo(os);
} else {
PrintAsFastTo(os, PrintMode::kPrintFull);
}
os << "\n" << std::flush;
}
#endif
} // namespace internal
} // namespace v8
| 32.914286 | 79 | 0.592303 | [
"object"
] |
33962d993a5521d68f051e11f3bef39232ffdf6d | 6,123 | cpp | C++ | servers/physics/area_sw.cpp | Lacrymology/godot | 1a2cb755e2d8b9d59178f36702f6dff7235b9088 | [
"MIT"
] | 3 | 2022-02-04T10:28:29.000Z | 2022-02-24T18:38:09.000Z | servers/physics/area_sw.cpp | bshawk/godot | c12a8e922ff724d7fe9909c16f9a1b5aec7f010b | [
"MIT"
] | 2 | 2021-08-18T15:38:29.000Z | 2021-08-31T08:06:16.000Z | servers/physics/area_sw.cpp | bshawk/godot | c12a8e922ff724d7fe9909c16f9a1b5aec7f010b | [
"MIT"
] | null | null | null | /*************************************************************************/
/* area_sw.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "area_sw.h"
#include "space_sw.h"
#include "body_sw.h"
AreaSW::BodyKey::BodyKey(BodySW *p_body, uint32_t p_body_shape,uint32_t p_area_shape) { rid=p_body->get_self(); instance_id=p_body->get_instance_id(); body_shape=p_body_shape; area_shape=p_area_shape; }
void AreaSW::_shapes_changed() {
}
void AreaSW::set_transform(const Transform& p_transform) {
if (!moved_list.in_list() && get_space())
get_space()->area_add_to_moved_list(&moved_list);
_set_transform(p_transform);
}
void AreaSW::set_space(SpaceSW *p_space) {
if (get_space()) {
if (monitor_query_list.in_list())
get_space()->area_remove_from_monitor_query_list(&monitor_query_list);
if (moved_list.in_list())
get_space()->area_remove_from_moved_list(&moved_list);
}
monitored_bodies.clear();
_set_space(p_space);
}
void AreaSW::set_monitor_callback(ObjectID p_id, const StringName& p_method) {
if (p_id==monitor_callback_id) {
monitor_callback_method=p_method;
return;
}
_unregister_shapes();
monitor_callback_id=p_id;
monitor_callback_method=p_method;
monitored_bodies.clear();
_shape_changed();
}
void AreaSW::set_space_override_mode(PhysicsServer::AreaSpaceOverrideMode p_mode) {
bool do_override=p_mode!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED;
if (do_override==(space_override_mode!=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED))
return;
_unregister_shapes();
space_override_mode=p_mode;
_shape_changed();
}
void AreaSW::set_param(PhysicsServer::AreaParameter p_param, const Variant& p_value) {
switch(p_param) {
case PhysicsServer::AREA_PARAM_GRAVITY: gravity=p_value; ; break;
case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: gravity_vector=p_value; ; break;
case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: gravity_is_point=p_value; ; break;
case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: point_attenuation=p_value; ; break;
case PhysicsServer::AREA_PARAM_DENSITY: density=p_value; ; break;
case PhysicsServer::AREA_PARAM_PRIORITY: priority=p_value; ; break;
}
}
Variant AreaSW::get_param(PhysicsServer::AreaParameter p_param) const {
switch(p_param) {
case PhysicsServer::AREA_PARAM_GRAVITY: return gravity;
case PhysicsServer::AREA_PARAM_GRAVITY_VECTOR: return gravity_vector;
case PhysicsServer::AREA_PARAM_GRAVITY_IS_POINT: return gravity_is_point;
case PhysicsServer::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return point_attenuation;
case PhysicsServer::AREA_PARAM_DENSITY: return density;
case PhysicsServer::AREA_PARAM_PRIORITY: return priority;
}
return Variant();
}
void AreaSW::_queue_monitor_update() {
ERR_FAIL_COND(!get_space());
if (!monitor_query_list.in_list())
get_space()->area_add_to_monitor_query_list(&monitor_query_list);
}
void AreaSW::call_queries() {
if (monitor_callback_id && !monitored_bodies.empty()) {
Variant res[5];
Variant *resptr[5];
for(int i=0;i<5;i++)
resptr[i]=&res[i];
Object *obj = ObjectDB::get_instance(monitor_callback_id);
if (!obj) {
monitored_bodies.clear();
monitor_callback_id=0;
return;
}
for (Map<BodyKey,BodyState>::Element *E=monitored_bodies.front();E;E=E->next()) {
if (E->get().state==0)
continue; //nothing happened
res[0]=E->get().state>0 ? PhysicsServer::AREA_BODY_ADDED : PhysicsServer::AREA_BODY_REMOVED;
res[1]=E->key().rid;
res[2]=E->key().instance_id;
res[3]=E->key().body_shape;
res[4]=E->key().area_shape;
Variant::CallError ce;
obj->call(monitor_callback_method,(const Variant**)resptr,5,ce);
}
}
monitored_bodies.clear();
//get_space()->area_remove_from_monitor_query_list(&monitor_query_list);
}
AreaSW::AreaSW() : CollisionObjectSW(TYPE_AREA), monitor_query_list(this), moved_list(this) {
_set_static(true); //areas are never active
space_override_mode=PhysicsServer::AREA_SPACE_OVERRIDE_DISABLED;
gravity=9.80665;
gravity_vector=Vector3(0,-1,0);
gravity_is_point=false;
point_attenuation=1;
density=0.1;
priority=0;
}
AreaSW::~AreaSW() {
}
| 31.725389 | 202 | 0.646089 | [
"object",
"transform"
] |
339936d0fbbebaf86ccdc54533552305fb0e82dd | 8,347 | cpp | C++ | src/scp/SCP.cpp | HashCash-Consultants/HCNet-Core-CentOS | 2489d262be5cf1d3d226ce673d6f054a362f2a50 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/scp/SCP.cpp | HashCash-Consultants/HCNet-Core-CentOS | 2489d262be5cf1d3d226ce673d6f054a362f2a50 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | src/scp/SCP.cpp | HashCash-Consultants/HCNet-Core-CentOS | 2489d262be5cf1d3d226ce673d6f054a362f2a50 | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 HcNet Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "scp/SCP.h"
#include "crypto/Hex.h"
#include "crypto/SHA.h"
#include "scp/LocalNode.h"
#include "scp/Slot.h"
#include "util/GlobalChecks.h"
#include "util/Logging.h"
#include "util/XDROperators.h"
#include "xdrpp/marshal.h"
#include <algorithm>
#include <lib/json/json.h>
namespace HcNet
{
SCP::SCP(SCPDriver& driver, NodeID const& nodeID, bool isValidator,
SCPQuorumSet const& qSetLocal)
: mDriver(driver)
{
mLocalNode =
std::make_shared<LocalNode>(nodeID, isValidator, qSetLocal, this);
}
SCP::EnvelopeState
SCP::receiveEnvelope(SCPEnvelope const& envelope)
{
// If the envelope is not correctly signed, we ignore it.
if (!mDriver.verifyEnvelope(envelope))
{
CLOG(DEBUG, "SCP") << "SCP::receiveEnvelope invalid";
return SCP::EnvelopeState::INVALID;
}
uint64 slotIndex = envelope.statement.slotIndex;
return getSlot(slotIndex, true)->processEnvelope(envelope, false);
}
bool
SCP::nominate(uint64 slotIndex, Value const& value, Value const& previousValue)
{
dbgAssert(isValidator());
return getSlot(slotIndex, true)->nominate(value, previousValue, false);
}
void
SCP::stopNomination(uint64 slotIndex)
{
auto s = getSlot(slotIndex, false);
if (s)
{
s->stopNomination();
}
}
void
SCP::updateLocalQuorumSet(SCPQuorumSet const& qSet)
{
mLocalNode->updateQuorumSet(qSet);
}
SCPQuorumSet const&
SCP::getLocalQuorumSet()
{
return mLocalNode->getQuorumSet();
}
NodeID const&
SCP::getLocalNodeID()
{
return mLocalNode->getNodeID();
}
void
SCP::purgeSlots(uint64 maxSlotIndex)
{
auto it = mKnownSlots.begin();
while (it != mKnownSlots.end())
{
if (it->first < maxSlotIndex)
{
it = mKnownSlots.erase(it);
}
else
{
++it;
}
}
}
std::shared_ptr<LocalNode>
SCP::getLocalNode()
{
return mLocalNode;
}
std::shared_ptr<Slot>
SCP::getSlot(uint64 slotIndex, bool create)
{
std::shared_ptr<Slot> res;
auto it = mKnownSlots.find(slotIndex);
if (it == mKnownSlots.end())
{
if (create)
{
res = std::make_shared<Slot>(slotIndex, *this);
mKnownSlots[slotIndex] = res;
}
}
else
{
res = it->second;
}
return res;
}
Json::Value
SCP::getJsonInfo(size_t limit)
{
Json::Value ret;
auto it = mKnownSlots.rbegin();
while (it != mKnownSlots.rend() && limit-- != 0)
{
auto& slot = *(it->second);
ret[std::to_string(slot.getSlotIndex())] = slot.getJsonInfo();
it++;
}
return ret;
}
Json::Value
SCP::getJsonQuorumInfo(NodeID const& id, bool summary, uint64 index)
{
Json::Value ret;
if (index == 0)
{
for (auto& item : mKnownSlots)
{
auto& slot = *item.second;
ret[std::to_string(slot.getSlotIndex())] =
slot.getJsonQuorumInfo(id, summary);
}
}
else
{
auto s = getSlot(index, false);
if (s)
{
ret[std::to_string(index)] = s->getJsonQuorumInfo(id, summary);
}
}
return ret;
}
bool
SCP::isValidator()
{
return mLocalNode->isValidator();
}
bool
SCP::isSlotFullyValidated(uint64 slotIndex)
{
auto slot = getSlot(slotIndex, false);
if (slot)
{
return slot->isFullyValidated();
}
else
{
return false;
}
}
size_t
SCP::getKnownSlotsCount() const
{
return mKnownSlots.size();
}
size_t
SCP::getCumulativeStatemtCount() const
{
size_t c = 0;
for (auto const& s : mKnownSlots)
{
c += s.second->getStatementCount();
}
return c;
}
std::vector<SCPEnvelope>
SCP::getLatestMessagesSend(uint64 slotIndex)
{
auto slot = getSlot(slotIndex, false);
if (slot)
{
return slot->getLatestMessagesSend();
}
else
{
return std::vector<SCPEnvelope>();
}
}
void
SCP::setStateFromEnvelope(uint64 slotIndex, SCPEnvelope const& e)
{
if (mDriver.verifyEnvelope(e))
{
auto slot = getSlot(slotIndex, true);
slot->setStateFromEnvelope(e);
}
}
bool
SCP::empty() const
{
return mKnownSlots.empty();
}
uint64
SCP::getLowSlotIndex() const
{
assert(!empty());
return mKnownSlots.begin()->first;
}
uint64
SCP::getHighSlotIndex() const
{
assert(!empty());
auto it = mKnownSlots.end();
it--;
return it->first;
}
std::vector<SCPEnvelope>
SCP::getCurrentState(uint64 slotIndex)
{
auto slot = getSlot(slotIndex, false);
if (slot)
{
return slot->getCurrentState();
}
else
{
return std::vector<SCPEnvelope>();
}
}
std::vector<SCPEnvelope>
SCP::getExternalizingState(uint64 slotIndex)
{
auto slot = getSlot(slotIndex, false);
if (slot)
{
return slot->getExternalizingState();
}
else
{
return std::vector<SCPEnvelope>();
}
}
SCP::TriBool
SCP::isNodeInQuorum(NodeID const& node)
{
TriBool res = TB_MAYBE;
// iterate in reverse order as the most recent slots are authoritative over
// older ones
for (auto it = mKnownSlots.rbegin(); it != mKnownSlots.rend(); it++)
{
auto slot = it->second;
res = slot->isNodeInQuorum(node);
if (res == TB_TRUE || res == TB_FALSE)
{
break;
}
}
return res;
}
std::string
SCP::getValueString(Value const& v) const
{
return mDriver.getValueString(v);
}
std::string
SCP::ballotToStr(SCPBallot const& ballot) const
{
std::ostringstream oss;
oss << "(" << ballot.counter << "," << getValueString(ballot.value) << ")";
return oss.str();
}
std::string
SCP::ballotToStr(std::unique_ptr<SCPBallot> const& ballot) const
{
std::string res;
if (ballot)
{
res = ballotToStr(*ballot);
}
else
{
res = "(<null_ballot>)";
}
return res;
}
std::string
SCP::envToStr(SCPEnvelope const& envelope) const
{
return envToStr(envelope.statement);
}
std::string
SCP::envToStr(SCPStatement const& st) const
{
std::ostringstream oss;
Hash const& qSetHash = Slot::getCompanionQuorumSetHashFromStatement(st);
oss << "{ENV@" << mDriver.toShortString(st.nodeID) << " | "
<< " i: " << st.slotIndex;
switch (st.pledges.type())
{
case SCPStatementType::SCP_ST_PREPARE:
{
auto const& p = st.pledges.prepare();
oss << " | PREPARE"
<< " | D: " << hexAbbrev(qSetHash)
<< " | b: " << ballotToStr(p.ballot)
<< " | p: " << ballotToStr(p.prepared)
<< " | p': " << ballotToStr(p.preparedPrime) << " | c.n: " << p.nC
<< " | h.n: " << p.nH;
}
break;
case SCPStatementType::SCP_ST_CONFIRM:
{
auto const& c = st.pledges.confirm();
oss << " | CONFIRM"
<< " | D: " << hexAbbrev(qSetHash)
<< " | b: " << ballotToStr(c.ballot) << " | p.n: " << c.nPrepared
<< " | c.n: " << c.nCommit << " | h.n: " << c.nH;
}
break;
case SCPStatementType::SCP_ST_EXTERNALIZE:
{
auto const& ex = st.pledges.externalize();
oss << " | EXTERNALIZE"
<< " | c: " << ballotToStr(ex.commit) << " | h.n: " << ex.nH
<< " | (lastD): " << hexAbbrev(qSetHash);
}
break;
case SCPStatementType::SCP_ST_NOMINATE:
{
auto const& nom = st.pledges.nominate();
oss << " | NOMINATE"
<< " | D: " << hexAbbrev(qSetHash) << " | X: {";
bool first = true;
for (auto const& v : nom.votes)
{
if (!first)
{
oss << " ,";
}
oss << "'" << getValueString(v) << "'";
first = false;
}
oss << "}"
<< " | Y: {";
first = true;
for (auto const& a : nom.accepted)
{
if (!first)
{
oss << " ,";
}
oss << "'" << getValueString(a) << "'";
first = false;
}
oss << "}";
}
break;
}
oss << " }";
return oss.str();
}
}
| 20.8675 | 79 | 0.566072 | [
"vector"
] |
3399419f6b880b21b8a05e9a7b09975b525e0c8b | 1,212 | cpp | C++ | src/planner/plannodes/set_op_plan_node.cpp | weijietong/noisepage | f3da5498b4c47f4a1b468655f1e2432cd33f177e | [
"MIT"
] | 971 | 2020-09-13T10:24:02.000Z | 2022-03-31T07:02:51.000Z | src/planner/plannodes/set_op_plan_node.cpp | weijietong/noisepage | f3da5498b4c47f4a1b468655f1e2432cd33f177e | [
"MIT"
] | 1,019 | 2018-07-20T23:11:10.000Z | 2020-09-10T06:41:42.000Z | src/planner/plannodes/set_op_plan_node.cpp | weijietong/noisepage | f3da5498b4c47f4a1b468655f1e2432cd33f177e | [
"MIT"
] | 318 | 2018-07-23T16:48:16.000Z | 2020-09-07T09:46:31.000Z | #include "planner/plannodes/set_op_plan_node.h"
#include <memory>
#include <utility>
#include <vector>
#include "common/json.h"
namespace noisepage::planner {
common::hash_t SetOpPlanNode::Hash() const {
common::hash_t hash = AbstractPlanNode::Hash();
// Hash set_op
hash = common::HashUtil::CombineHashes(hash, common::HashUtil::Hash(set_op_));
return hash;
}
bool SetOpPlanNode::operator==(const AbstractPlanNode &rhs) const {
if (!AbstractPlanNode::operator==(rhs)) return false;
auto &other = dynamic_cast<const SetOpPlanNode &>(rhs);
// Set op
return (set_op_ == other.set_op_);
}
nlohmann::json SetOpPlanNode::ToJson() const {
nlohmann::json j = AbstractPlanNode::ToJson();
j["set_op"] = set_op_;
return j;
}
std::vector<std::unique_ptr<parser::AbstractExpression>> SetOpPlanNode::FromJson(const nlohmann::json &j) {
std::vector<std::unique_ptr<parser::AbstractExpression>> exprs;
auto e1 = AbstractPlanNode::FromJson(j);
exprs.insert(exprs.end(), std::make_move_iterator(e1.begin()), std::make_move_iterator(e1.end()));
set_op_ = j.at("set_op").get<SetOpType>();
return exprs;
}
DEFINE_JSON_BODY_DECLARATIONS(SetOpPlanNode);
} // namespace noisepage::planner
| 26.347826 | 107 | 0.723597 | [
"vector"
] |
33998ad7ce4672c488a8bfdd6179c4a0e303eb36 | 28,461 | cpp | C++ | sources/compiler/codegen.cpp | covscript/covscript-runtime | e52ce004de789b6ffde4655492ea6b3bbff3fb7b | [
"Apache-2.0"
] | null | null | null | sources/compiler/codegen.cpp | covscript/covscript-runtime | e52ce004de789b6ffde4655492ea6b3bbff3fb7b | [
"Apache-2.0"
] | null | null | null | sources/compiler/codegen.cpp | covscript/covscript-runtime | e52ce004de789b6ffde4655492ea6b3bbff3fb7b | [
"Apache-2.0"
] | null | null | null | /*
* Covariant Script Code Generating
*
* 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.
*
* Copyright (C) 2017-2022 Michael Lee(李登淳)
*
* This software is registered with the National Copyright Administration
* of the People's Republic of China(Registration Number: 2020SR0408026)
* and is protected by the Copyright Law of the People's Republic of China.
*
* Email: lee@covariant.cn, mikecovlee@163.com
* Github: https://github.com/mikecovlee
* Website: http://covscript.org.cn
*/
#include <covscript/impl/codegen.hpp>
namespace cs {
statement_base *
method_expression::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().front())->get_tree();
if (context->compiler->fold_expr && tree.root().usable() &&
tree.root().data()->get_type() == token_types::value)
return nullptr;
else
return new statement_expression(tree, context, raw.front().back());
}
void method_import::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (tree.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
std::vector<std::pair<std::string, var>> var_list;
auto process = [&context, &var_list](tree_type<token_base *> &t) {
token_base *token = t.root().data();
if (token == nullptr || token->get_type() != token_types::id)
throw compile_error("Wrong grammar for import statement, expect <package name>");
const var_id &package_name = static_cast<token_id *>(token)->get_id();
const var &ext = make_namespace(context->instance->import(current_process->import_path, package_name));
context->compiler->add_constant(ext);
context->instance->storage.add_var(package_name, ext);
var_list.emplace_back(package_name, ext);
};
if (tree.root().data()->get_type() == token_types::parallel) {
auto ¶llel_list = static_cast<token_parallel *>(tree.root().data())->get_parallel();
for (auto &t:parallel_list)
process(t);
}
else
process(tree);
mResult.emplace_back(new statement_import(var_list, context, raw.front().back()));
}
statement_base *
method_import::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
statement_base *ptr = mResult.front();
mResult.pop_front();
return ptr;
}
var method_import_as::get_namespace(const context_t &context, tree_type<token_base *>::iterator it)
{
token_base *token = it.data();
if (token == nullptr)
return var();
if (token->get_type() == token_types::id) {
const var_id &package_name = static_cast<token_id *>(token)->get_id();
return make_namespace(context->instance->import(current_process->import_path, package_name));
}
else if (token->get_type() == token_types::signal &&
static_cast<token_signal *>(token)->get_signal() == signal_types::dot_) {
const var &ext = get_namespace(context, it.left());
token_base *id = it.right().data();
if (id == nullptr || id->get_type() != token_types::id)
throw compile_error(
"Wrong grammar for import-as statement, expect <package name> or <package name>.<namespace id>...");
if (ext.type() == typeid(namespace_t))
return ext.const_val<namespace_t>()->get_var(static_cast<token_id *>(id)->get_id());
else
throw compile_error("Access non-namespace object.");
}
else
throw compile_error(
"Wrong grammar for import-as statement, expect <package name> or <package name>.<namespace id>...");
}
void method_import_as::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree_package = static_cast<token_expr *>(raw.front().at(1))->get_tree();
tree_type<token_base *> &tree_alias = static_cast<token_expr *>(raw.front().at(3))->get_tree();
if (tree_package.root().data() == nullptr || tree_alias.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
token_base *token_alias = tree_alias.root().data();
if (token_alias->get_type() != token_types::id)
throw compile_error("Wrong grammar for import-as statement, expect <id> in alias.");
const string &alias_name = static_cast<token_id *>(token_alias)->get_id().get_id();
var ext = get_namespace(context, tree_package.root());
context->compiler->add_constant(ext);
context->instance->storage.add_var(alias_name, ext);
mResult.emplace_back(new statement_import({{alias_name, ext}}, context, raw.front().back()));
}
statement_base *
method_import_as::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
statement_base *ptr = mResult.front();
mResult.pop_front();
return ptr;
}
statement_base *
method_package::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
if (!context->package_name.empty())
throw compile_error(std::string("Redefinition of package: ") + context->package_name);
context->package_name = static_cast<token_id *>(static_cast<token_expr *>(raw.front().at(
1))->get_tree().root().data())->get_id();
return nullptr;
}
void method_involve::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
token_value *vptr = dynamic_cast<token_value *>(tree.root().data());
if (vptr != nullptr) {
var ns = vptr->get_value();
if (ns.type() == typeid(namespace_t)) {
auto &domain = ns.const_val<namespace_t>()->get_domain();
for (auto &it:domain) {
if (domain.get_var_by_id(it.second).is_protect())
context->instance->storage.add_record(it.first);
}
context->instance->storage.involve_domain(domain);
}
else
throw compile_error("Only support involve namespace.");
mResult.emplace_back(new statement_involve(tree, true, context, raw.front().back()));
}
else
mResult.emplace_back(new statement_involve(tree, false, context, raw.front().back()));
}
statement_base *
method_involve::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
statement_base *ptr = mResult.front();
mResult.pop_front();
return ptr;
}
void method_var::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
context->instance->check_define_var(static_cast<token_expr *>(raw.front().at(1))->get_tree().root());
}
statement_base *method_var::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
return new statement_var(static_cast<token_expr *>(raw.front().at(1))->get_tree(), context, false,
raw.front().back());
}
void method_link::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
context->instance->check_define_var(static_cast<token_expr *>(raw.front().at(1))->get_tree().root());
}
statement_base *method_link::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
return new statement_var(static_cast<token_expr *>(raw.front().at(1))->get_tree(), context, true,
raw.front().back());
}
void method_constant::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
context->instance->check_define_var(tree.root(), false, true);
context->instance->parse_define_var(tree.root(), true);
}
statement_base *
method_constant::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
return new statement_constant(tree, context, raw.front().back());
}
statement_base *method_block::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
return new statement_block(body, context, raw.front().back());
}
void method_namespace::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::string name = static_cast<token_id *>(static_cast<token_expr *>(raw.front().at(
1))->get_tree().root().data())->get_id();
context->instance->storage.add_var("__PRAGMA_CS_NAMESPACE_DEFINITION__", name);
}
statement_base *
method_namespace::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
for (auto &ptr:body)
if (ptr->get_type() != statement_types::import_ && ptr->get_type() != statement_types::involve_ &&
ptr->get_type() != statement_types::var_ && ptr->get_type() != statement_types::function_ &&
ptr->get_type() != statement_types::namespace_ && ptr->get_type() != statement_types::struct_)
throw compile_error("Unexpected statement in namespace definition.");
return new statement_namespace(static_cast<token_expr *>(raw.front().at(1))->get_tree().root().data(), body,
context, raw.front().back());
}
void method_namespace::postprocess(const context_t &context, const domain_type &domain)
{
context->instance->storage.add_var(domain.get_var("__PRAGMA_CS_NAMESPACE_DEFINITION__").const_val<string>(),
make_namespace(make_shared_namespace<name_space>(domain)));
}
statement_base *method_if::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
bool have_else = false;
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
for (auto &ptr:body) {
if (ptr->get_type() == statement_types::else_) {
if (!have_else)
have_else = true;
else
throw compile_error("Multi Else Grammar.");
}
}
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
token_base *ptr = tree.root().data();
if (have_else) {
std::deque<statement_base *> body_true;
std::deque<statement_base *> body_false;
bool now_place = true;
for (auto &ptr:body) {
if (ptr->get_type() == statement_types::else_) {
now_place = false;
continue;
}
if (now_place)
body_true.push_back(ptr);
else
body_false.push_back(ptr);
}
if (ptr != nullptr && ptr->get_type() == token_types::value) {
if (static_cast<token_value *>(ptr)->get_value().const_val<bool>())
return new statement_block(body_true, context, raw.front().back());
else
return new statement_block(body_false, context, raw.front().back());
}
else
return new statement_ifelse(tree, body_true, body_false, context, raw.front().back());
}
else if (ptr != nullptr && ptr->get_type() == token_types::value) {
if (static_cast<token_value *>(ptr)->get_value().const_val<bool>())
return new statement_block(body, context, raw.front().back());
else
return nullptr;
}
else
return new statement_if(tree, body, context, raw.front().back());
}
void method_else::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &)
{
context->instance->storage.clear_domain();
context->instance->storage.clear_set();
}
statement_base *method_else::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
return new statement_else;
}
statement_base *
method_switch::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
statement_block *dptr = nullptr;
map_t<var, statement_block *> cases;
for (auto &it:body) {
try {
if (it->get_type() == statement_types::case_) {
auto *scptr = static_cast<statement_case *>(it);
if (cases.count(scptr->get_tag()) > 0)
throw compile_error("Redefinition of case.");
cases.emplace(scptr->get_tag(), scptr->get_block());
}
else if (it->get_type() == statement_types::default_) {
auto *sdptr = static_cast<statement_default *>(it);
if (dptr != nullptr)
throw compile_error("Redefinition of default case.");
dptr = sdptr->get_block();
}
else
throw compile_error("Unexpected statement in switch definition.");
}
catch (const cs::exception &e) {
throw e;
}
catch (const std::exception &e) {
throw exception(it->get_line_num(), it->get_file_path(), it->get_raw_code(), e.what());
}
}
return new statement_switch(static_cast<token_expr *>(raw.front().at(1))->get_tree(), cases, dptr, context,
raw.front().back());
}
statement_base *method_case::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (tree.root().data()->get_type() != token_types::value) {
std::size_t line_num = static_cast<token_endline *>(raw.front().back())->get_line_num();
const char *what = "Case Tag must be a constant value.";
throw exception(line_num, context->file_path, context->file_buff.at(line_num - 1), what);
}
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
return new statement_case(static_cast<token_value *>(tree.root().data())->get_value(), body, context,
raw.front().back());
}
statement_base *
method_default::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
return new statement_default(body, context, raw.front().back());
}
statement_base *method_while::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
token_base *ptr = tree.root().data();
if (ptr != nullptr && ptr->get_type() == token_types::value) {
if (static_cast<token_value *>(ptr)->get_value().const_val<bool>())
return new statement_loop(body, context, raw.front().back());
else
return nullptr;
}
else
return new statement_while(static_cast<token_expr *>(raw.front().at(1))->get_tree(), body, context,
raw.front().back());
}
statement_base *method_until::translate_end(method_base *method, const context_t &context,
std::deque<std::deque<token_base *>> &raw,
std::deque<token_base *> &code)
{
if (method != nullptr && method->get_target_type() == statement_types::loop_)
return static_cast<method_loop *>(method)->translate(context, raw,
static_cast<token_expr *>(code.at(1))->get_tree());
else
throw compile_error("Use until in non-loop statement.");
}
statement_base *method_loop::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
return new statement_loop(body, context, raw.front().back());
}
statement_base *method_loop::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw,
const tree_type<token_base *> &cond)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
token_base *ptr = cond.root().data();
if (ptr != nullptr && ptr->get_type() == token_types::value) {
if (static_cast<token_value *>(ptr)->get_value().const_val<bool>())
return new statement_block(body, context, raw.front().back());
else
return new statement_loop(body, context, raw.front().back());
}
else
return new statement_loop_until(cond, body, context, raw.front().back());
}
void method_for::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (tree.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (tree.root().data()->get_type() != token_types::parallel)
throw compile_error("Wrong grammar in for statement, expect <id> = <expression>, <condition>, <process>");
auto ¶llel_list = static_cast<token_parallel *>(tree.root().data())->get_parallel();
if (parallel_list.size() != 3)
throw compile_error("Wrong grammar in for statement, expect <id> = <expression>, <condition>, <process>");
context->instance->check_define_var(parallel_list[0].root(), true);
}
statement_base *method_for::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
auto ¶llel_list = static_cast<token_parallel *>(tree.root().data())->get_parallel();
return new statement_for(parallel_list, body, context, raw.front().back());
}
statement_base *
method_for_do::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &tree = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (tree.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (tree.root().data()->get_type() != token_types::parallel)
throw compile_error("Wrong grammar in for statement, expect <id> = <expression>, <condition>, <process>");
auto ¶llel_list = static_cast<token_parallel *>(tree.root().data())->get_parallel();
if (parallel_list.size() != 3)
throw compile_error("Wrong grammar in for statement, expect <id> = <expression>, <condition>, <process>");
context->instance->check_define_var(parallel_list[0].root());
return new statement_for(parallel_list, {
new statement_expression(static_cast<token_expr *>(raw.front().at(3))->get_tree(),
context, raw.front().back())
}, context, raw.front().back());
}
void method_foreach::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &t = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (t.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (t.root().data()->get_type() != token_types::id)
throw compile_error("Wrong grammar in foreach statement, expect <id>");
context->instance->storage.add_record(static_cast<token_id *>(t.root().data())->get_id());
}
statement_base *
method_foreach::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &t = static_cast<token_expr *>(raw.front().at(1))->get_tree();
const std::string &it = static_cast<token_id *>(t.root().data())->get_id();
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
return new statement_foreach(it, static_cast<token_expr *>(raw.front().at(3))->get_tree(), body, context,
raw.front().back());
}
statement_base *
method_foreach_do::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &t = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (t.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (t.root().data()->get_type() != token_types::id)
throw compile_error("Wrong grammar in foreach statement, expect <id>");
const std::string &it = static_cast<token_id *>(t.root().data())->get_id();
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
return new statement_foreach(it, static_cast<token_expr *>(raw.front().at(3))->get_tree(), {
new statement_expression(static_cast<token_expr *>(raw.front().at(5))->get_tree(),
context, raw.front().back())
}, context,
raw.front().back());
}
statement_base *method_break::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
return new statement_break(context, raw.front().back());
}
statement_base *
method_continue::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
return new statement_continue(context, raw.front().back());
}
void method_function::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &t = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (t.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (t.root().data()->get_type() != token_types::signal ||
static_cast<token_signal *>(t.root().data())->get_signal() != signal_types::fcall_)
throw compile_error("Wrong grammar for function definition.");
if (t.root().left().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (t.root().left().data()->get_type() != token_types::id)
throw compile_error("Wrong grammar for function definition, expect function name.");
if (t.root().right().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (t.root().right().data()->get_type() != token_types::arglist)
throw compile_error("Wrong grammar for function definition, expect argument list.");
std::vector<std::string> args;
for (auto &it:static_cast<token_arglist *>(t.root().right().data())->get_arglist()) {
if (it.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
context->compiler->try_fix_this_deduction(it.root());
if (it.root().data()->get_type() == token_types::id) {
const std::string &str = static_cast<token_id *>(it.root().data())->get_id();
for (auto &it:args)
if (it == str)
throw compile_error("Redefinition of function argument.");
context->instance->storage.add_record(str);
args.push_back(str);
}
else if (it.root().data()->get_type() == token_types::vargs) {
const std::string &str = static_cast<token_vargs *>(it.root().data())->get_id();
if (!args.empty())
throw compile_error("Redefinition of function argument(Multi-define of vargs).");
context->instance->storage.add_record(str);
args.push_back(str);
}
else
throw compile_error("Unexpected element in function argument list.");
}
}
statement_base *
method_function::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &t = static_cast<token_expr *>(raw.front().at(1))->get_tree();
std::string name = static_cast<token_id *>(t.root().left().data())->get_id();
std::vector<std::string> args;
bool is_vargs = false;
for (auto &it:static_cast<token_arglist *>(t.root().right().data())->get_arglist()) {
if (it.root().data()->get_type() == token_types::id)
args.push_back(static_cast<token_id *>(it.root().data())->get_id());
else if (it.root().data()->get_type() == token_types::vargs) {
args.push_back(static_cast<token_vargs *>(it.root().data())->get_id());
is_vargs = true;
}
}
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
#ifdef CS_DEBUGGER
std::string decl="function "+name+"(";
if(args.size()!=0) {
for(auto& it:args)
decl+=it+", ";
decl.pop_back();
decl[decl.size()-1]=')';
}
else
decl+=")";
if(raw.front().size() == 4)
decl+=" override";
return new statement_function(name, decl, args, body, raw.front().size() == 4, is_vargs, context, raw.front().back());
#else
return new statement_function(name, args, body, raw.front().size() == 4, is_vargs, context, raw.front().back());
#endif
}
statement_base *
method_return::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
return new statement_return(static_cast<token_expr *>(raw.front().at(1))->get_tree(), context,
raw.front().back());
}
statement_base *
method_return_no_value::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> tree;
tree.emplace_root_left(tree.root(), new token_value(null_pointer));
return new statement_return(tree, context, raw.front().back());
}
void method_struct::preprocess(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
context->instance->storage.mark_set_as_struct(raw.front().size() == 5);
}
statement_base *
method_struct::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &t = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (t.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (t.root().data()->get_type() != token_types::id)
throw compile_error("Wrong grammar for struct definition, expect <id>");
std::string name = static_cast<token_id *>(t.root().data())->get_id();
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
for (auto &ptr:body) {
try {
switch (ptr->get_type()) {
default:
throw compile_error("Unexpected statement in structure definition.");
case statement_types::var_:
break;
case statement_types::function_:
static_cast<statement_function *>(ptr)->set_mem_fn();
break;
}
}
catch (const cs::exception &e) {
throw e;
}
catch (const std::exception &e) {
throw exception(ptr->get_line_num(), ptr->get_file_path(), ptr->get_raw_code(), e.what());
}
}
if (raw.front().size() == 5)
return new statement_struct(name, static_cast<token_expr *>(raw.front().at(3))->get_tree(), body, context,
raw.front().back());
else
return new statement_struct(name, tree_type<token_base *>(), body, context, raw.front().back());
}
statement_base *method_try::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
std::deque<statement_base *> body;
context->compiler->translate({raw.begin() + 1, raw.end()}, body);
std::string name;
std::deque<statement_base *> tbody, cbody;
bool founded = false;
for (auto &ptr:body) {
if (ptr->get_type() == statement_types::catch_) {
name = static_cast<statement_catch *>(ptr)->get_name();
founded = true;
continue;
}
if (founded)
cbody.push_back(ptr);
else
tbody.push_back(ptr);
}
if (!founded)
throw compile_error("Wrong grammar for try statement, expect catch statement.");
return new statement_try(name, tbody, cbody, context, raw.front().back());
}
statement_base *method_catch::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
tree_type<token_base *> &t = static_cast<token_expr *>(raw.front().at(1))->get_tree();
if (t.root().data() == nullptr)
throw internal_error("Null pointer accessed.");
if (t.root().data()->get_type() != token_types::id)
throw compile_error("Wrong grammar for catch statement, expect <id>");
return new statement_catch(static_cast<token_id *>(t.root().data())->get_id(), context, raw.front().back());
}
statement_base *method_throw::translate(const context_t &context, const std::deque<std::deque<token_base *>> &raw)
{
return new statement_throw(static_cast<token_expr *>(raw.front().at(1))->get_tree(), context,
raw.front().back());
}
} | 42.992447 | 120 | 0.677207 | [
"object",
"vector"
] |
339fe89a56e9b524520e4deb14addde8d7617baa | 18,788 | hh | C++ | src/c4/C4_Functions.hh | rspavel/Draco | b279b1afbfbb39f2d521579697172394c5efd81d | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/c4/C4_Functions.hh | rspavel/Draco | b279b1afbfbb39f2d521579697172394c5efd81d | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/c4/C4_Functions.hh | rspavel/Draco | b279b1afbfbb39f2d521579697172394c5efd81d | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | //----------------------------------*-C++-*----------------------------------//
/*!
* \file c4/C4_Functions.hh
* \author Thomas M. Evans
* \date Thu Mar 21 11:42:03 2002
* \brief C4 Communication Functions.
* \note Copyright (C) 2016-2019 Triad National Security, LLC.
* All rights reserved.
*
* This file contains the declarations for communication functions provided by
* C4. This file allows the client to include the message passing services
* provided by C4. The function declarations and class definitions are
* contained in the rtt_c4 namespace. For backwards compatibility, the
* old-style C4 functions and classes are declared in the C4 namespace.
*/
//---------------------------------------------------------------------------//
#ifndef c4_C4_Functions_hh
#define c4_C4_Functions_hh
#include "C4_Datatype.hh"
#include "C4_Status.hh"
#include "C4_Traits.hh"
#include "C4_sys_times.h"
namespace rtt_c4 {
//----------------------------------------------------------------------------//
/*! Forward declarations
*
* We postpone including C4_Req.hh until C4_MPI.i.hh is loaded. This allows the
* 'friend' declarations found in class C4_Req to be seen after the 'official'
* function declartions (with optional default arguments) are loaded.
*/
class C4_Req;
//---------------------------------------------------------------------------//
/*!
* C4 unit tests.
*/
/*! \example c4/test/tstAbort.cc
* Example of MPI abort functions.
*/
/*! \example c4/test/tstBroadcast.cc
* Example of MPI broadcast-like functions
*/
/*! \example c4/test/tstComm_Dup.cc
* Example
*/
/*! \example c4/test/tstPingPong.cc
* Example of point-to-point communications
*/
/*! \example c4/test/tstReduction.cc
* Example of many-to-one communications
*/
//---------------------------------------------------------------------------//
//---------------------------------------------------------------------------//
// GLOBAL CONSTANTS
//---------------------------------------------------------------------------//
//! Any source rank
DLL_PUBLIC_c4 extern const int any_source;
//! Null source/destination rank
DLL_PUBLIC_c4 extern const int proc_null;
//---------------------------------------------------------------------------//
// SETUP FUNCTIONS
//---------------------------------------------------------------------------//
/*!
* \brief Initialize a parallel job.
*/
DLL_PUBLIC_c4 int initialize(int &argc, char **&argv,
int required = DRACO_MPI_THREAD_SINGLE);
//---------------------------------------------------------------------------//
/*!
* \brief Finish a parallel job.
*/
DLL_PUBLIC_c4 void finalize();
//---------------------------------------------------------------------------//
/*!
* \brief Inherit a communicator from another application.
*/
template <typename Comm> void inherit(const Comm &);
//---------------------------------------------------------------------------//
/*!
* \brief Free an inherited communicator from another application.
*/
DLL_PUBLIC_c4 void free_inherited_comm();
//---------------------------------------------------------------------------//
/*!
* \brief Create up a new vector type.
*
* \param count Number of blocks in the data type
* \param blocklength Length of each block (in units of base type)
* \param stride Spacing between start of each block (in units of base type)
* \param new_type On return, contains the new type descriptor.
*/
template <class T>
int create_vector_type(unsigned count, unsigned blocklength, unsigned stride,
C4_Datatype &new_type);
//---------------------------------------------------------------------------//
//! Free a user defined type, such as a vector type.
DLL_PUBLIC_c4 void type_free(C4_Datatype &old_type);
//---------------------------------------------------------------------------//
// QUERY FUNCTIONS
//---------------------------------------------------------------------------//
/*!
* \brief Get the node (rank) of the current processor.
*
* The rank is determined by the current communicator.
*/
DLL_PUBLIC_c4 int node();
//---------------------------------------------------------------------------//
/*!
* \brief Get the number of processors used for this job.
*
* The number of nodes is determined by the current communicator.
*/
DLL_PUBLIC_c4 int nodes();
//---------------------------------------------------------------------------//
// BARRIER FUNCTIONS
//---------------------------------------------------------------------------//
/*!
* \brief Set a global barrier for the communicator.
*/
DLL_PUBLIC_c4 void global_barrier();
//---------------------------------------------------------------------------//
// BLOCKING SEND/RECEIVE OPERATIONS
//---------------------------------------------------------------------------//
//! Do a point-to-point, blocking send.
template <typename T>
DLL_PUBLIC_c4 int send(const T *buffer, int size, int destination,
int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
//! Do a point-to-point, blocking send.
template <typename T>
int send_custom(const T *buffer, int size, int destination, int tag);
//---------------------------------------------------------------------------//
//! Do a point-to-point, blocking receive.
template <typename T>
DLL_PUBLIC_c4 int receive(T *buffer, int size, int source,
int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
//! Do a point-to-point, blocking receive with a custom MPI type
template <typename T>
int receive_custom(T *buffer, int size, int source, int tag);
//---------------------------------------------------------------------------//
//! Do a point-to-point, blocking send of a user-defined type.
template <typename T>
DLL_PUBLIC_c4 int send_udt(const T *buffer, int size, int destination,
C4_Datatype &, int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
//! Do a point-to-point, blocking send-receive.
template <typename TS, typename TR>
DLL_PUBLIC_c4 int send_receive(TS *sendbuf, int sendcount, int destination,
TR *recvbuf, int recvcount, int source,
int sendtag = C4_Traits<TS *>::tag,
int recvtag = C4_Traits<TR *>::tag);
//---------------------------------------------------------------------------//
//! Do a point-to-point, blocking receive of a user-defined type.
template <typename T>
DLL_PUBLIC_c4 int receive_udt(T *buffer, int size, int source, C4_Datatype &,
int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
// NON-BLOCKING SEND/RECEIVE OPERATIONS
//---------------------------------------------------------------------------//
/*!
* \brief Do a point-to-point, non-blocking send.
*
* \return C4_Req object to handle communciation requests
*/
template <typename T>
DLL_PUBLIC_c4 C4_Req send_async(T const *buffer, int size, int destination,
int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
/*!
* \brief Do a point-to-point, non-blocking send.
*/
template <typename T>
DLL_PUBLIC_c4 void send_async(C4_Req &request, T const *buffer, int size,
int destination, int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
/*!
* \brief Do a point-to-point, non-blocking synchronous send.
*/
template <typename T>
DLL_PUBLIC_c4 void send_is(C4_Req &request, T const *buffer, int size,
int destination, int tag);
template <typename T>
void send_is(C4_Req &request, T const *buffer, int size, int destination) {
int tag = C4_Traits<T *>::tag;
send_is(request, buffer, size, destination, tag);
return;
}
//---------------------------------------------------------------------------//
/*!
* \brief Get the size of a message with custom types
*
* \param[in] status C4_Status object that will hold MPI request status
* \param[in] mpi_type The signature of the special type.
* \return number of type T objects in the completed message
*/
template <typename T>
int message_size_custom(C4_Status status, const T &mpi_type);
//---------------------------------------------------------------------------//
/*!
* \brief Do a point-to-point, non-blocking send with a MPI custom type
*
* \param[in,out] request C4_Req object that will hold MPI request
* \param[in,out] buffer array of data of type T that has an MPI type
* \param[in] size size of buffer
* \param[in] destination rank that will receive this message
* \param[in] tag message tag
*/
template <typename T>
void send_is_custom(C4_Req &request, const T *buffer, int size, int destination,
int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
/*!
* \brief Do a point-to-point, non-blocking receive.
*
* \return C4_Req object to handle communciation requests
*/
template <typename T>
DLL_PUBLIC_c4 C4_Req receive_async(T *buffer, int size, int source,
int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
/*!
* \brief Do a point-to-point, non-blocking receive.
*/
template <typename T>
DLL_PUBLIC_c4 void receive_async(C4_Req &request, T *buffer, int size,
int source, int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
/*!
* \brief Post a non-blocking receive for a message of custom MPI type data
*
* \param[in,out] request C4_Req object that will hold MPI request
* \param[in,out] buffer array of data of type T that has a registered MPI type
* \param[in] size size of buffer
* \param[in] source remote rank sending message to this rank
* \param[in] tag message tag
*/
template <typename T>
void receive_async_custom(C4_Req &request, T *buffer, int size, int source,
int tag = C4_Traits<T *>::tag);
//---------------------------------------------------------------------------//
// BROADCAST
//---------------------------------------------------------------------------//
/*---------------------------------------------------------------------------*/
/*
* \brief Send data from processor 0 to all other processors.
*
* These are declared and defined in C4_MPI.hh and in C4_Serial.hh. KT is
* having trouble with getting the DLL_PUBLIC_c4 to be correct, so delay
* declaration until the C4_MPI.hh or C4_Serial.hh files are included.
template <typename T>
DLL_PUBLIC_c4 int broadcast(T *buffer, int size, int root);
template <typename ForwardIterator, typename OutputIterator>
DLL_PUBLIC_c4 void broadcast(ForwardIterator first, ForwardIterator last,
OutputIterator result);
template <typename ForwardIterator, typename OutputIterator>
DLL_PUBLIC_c4 void broadcast(ForwardIterator first, ForwardIterator last,
OutputIterator result, OutputIterator result_end);
*/
//---------------------------------------------------------------------------//
// GATHER/SCATTER
//---------------------------------------------------------------------------//
template <typename T>
DLL_PUBLIC_c4 int gather(T *send_buffer, T *receive_buffer, int size);
template <typename T>
DLL_PUBLIC_c4 int allgather(T *send_buffer, T *receive_buffer, int size);
template <typename T>
int gatherv(T *send_buffer, int send_size, T *receive_buffer,
int *receive_sizes, int *receive_displs);
template <typename T>
DLL_PUBLIC_c4 int scatter(T *send_buffer, T *receive_buffer, int size);
template <typename T>
int scatterv(T *send_buffer, int *send_sizes, int *send_displs,
T *receive_buffer, int receive_size);
//---------------------------------------------------------------------------//
// GLOBAL REDUCTIONS
//---------------------------------------------------------------------------//
/*!
* \brief Do a global sum of a scalar variable.
*/
template <typename T> DLL_PUBLIC_c4 void global_sum(T &x);
//---------------------------------------------------------------------------//
/*!
* \brief Do a non-blocking global sum of a scalar variable.
*
* \param[in,out] send_buffer scalar value on this processing element
* \param[in,out] recv_buffer scalar value summed across all ranks
* \param[in,out] request C4_Requst handle for testing completed message
*/
template <typename T>
DLL_PUBLIC_c4 void global_isum(T &send_buffer, T &recv_buffer, C4_Req &request);
//---------------------------------------------------------------------------//
/*!
* \brief Do a global product of a scalar variable.
*/
template <typename T> DLL_PUBLIC_c4 void global_prod(T &x);
//---------------------------------------------------------------------------//
/*!
* \brief Do a global minimum of a scalar variable.
*/
template <typename T> DLL_PUBLIC_c4 void global_min(T &x);
//---------------------------------------------------------------------------//
/*!
* \brief Do a global maximum of a scalar variable.
*/
template <typename T> DLL_PUBLIC_c4 void global_max(T &x);
//---------------------------------------------------------------------------//
/*!
* \brief Do an element-wise, global sum of an array.
*/
template <typename T> DLL_PUBLIC_c4 void global_sum(T *x, int n);
//---------------------------------------------------------------------------//
/*!
* \brief Do an element-wise, global product of an array.
*/
template <typename T> DLL_PUBLIC_c4 void global_prod(T *x, int n);
//---------------------------------------------------------------------------//
/*!
* \brief Do an element-wise, global minimum of an array.
*/
template <typename T> DLL_PUBLIC_c4 void global_min(T *x, int n);
//---------------------------------------------------------------------------//
/*!
* \brief Do an element-wise, global maximum of an array.
*/
template <typename T> DLL_PUBLIC_c4 void global_max(T *x, int n);
//---------------------------------------------------------------------------//
// TIMING FUNCTIONS
//---------------------------------------------------------------------------//
/*!
* \brief Return the wall-clock time in seconds.
*/
DLL_PUBLIC_c4 double wall_clock_time();
DLL_PUBLIC_c4 double wall_clock_time(DRACO_TIME_TYPE &now);
//---------------------------------------------------------------------------//
/*!
* \brief Return the resolution of wall_clock_time.
*/
DLL_PUBLIC_c4 double wall_clock_resolution();
//---------------------------------------------------------------------------//
// PROBE/WAIT FUNCTIONS
//---------------------------------------------------------------------------//
/*!
* \brief See if a message is pending.
*
* \param source
* Processor from which a message may be pending.
* \param tag
* Tag for pending message.
* \param message_size
* On return, size of the pending message in bytes.
* \return \c true if a message from the specified processor with the
* specified tag is pending; \c false otherwise.
*/
DLL_PUBLIC_c4 bool probe(int source, int tag, int &message_size);
//---------------------------------------------------------------------------//
/*!
* \brief Wait until a message (of unknown size) is pending.
*
* \param source
* Processor from which a message of unknown size is expected.
* \param tag
* Tag for pending message.
* \param message_size
* On return, size of the pending message in bytes.
*/
DLL_PUBLIC_c4 void blocking_probe(int source, int tag, int &message_size);
//---------------------------------------------------------------------------//
/*!
* \brief Wait until every one of a set of posted sends/receives is complete.
*
* This version returns no status information.
*
* \param count
* Size of the set of requests to wait on.
* \param requests
* Set of requests to wait on.
*/
DLL_PUBLIC_c4 void wait_all(unsigned count, C4_Req *requests);
//---------------------------------------------------------------------------//
/*!
* \brief Wait until one of a set of posted sends/receives is complete.
*
* \param count
* Size of the set of requests to wait on.
* \param requests
* Set of requests to wait on.
* \return The request that completed.
*/
DLL_PUBLIC_c4 unsigned wait_any(unsigned count, C4_Req *requests);
//---------------------------------------------------------------------------//
// ABORT
//---------------------------------------------------------------------------//
/*!
* \brief Abort across all processors.
*
* \param error suggested return error, defaults to 1
*/
DLL_PUBLIC_c4 int abort(int error = 1);
//---------------------------------------------------------------------------//
// isScalar
//---------------------------------------------------------------------------//
/*!
* \brief Is C4 executing in scalar-only mode?
*/
DLL_PUBLIC_c4 bool isScalar();
//---------------------------------------------------------------------------//
// get_processor_name
//---------------------------------------------------------------------------//
//! Return the processor name for each rank.
DLL_PUBLIC_c4 std::string get_processor_name();
//---------------------------------------------------------------------------//
// prefix_sum
//---------------------------------------------------------------------------//
/*!
* \brief Return the value of the prefix sum at this processor.
*
* \param node_value Current node's value of variable to be prefix summed
* \return Sum of value over nodes up to and including this node.
*/
template <typename T> DLL_PUBLIC_c4 T prefix_sum(const T node_value);
/*!
* \brief Return the value of the prefix sum at this processor.
*
* \param buffer Current node's starting buffer address to be prefix summed
* \param n number of ojbects of type T in the buffer
*/
template <typename T> DLL_PUBLIC_c4 void prefix_sum(T *buffer, const int32_t n);
} // end namespace rtt_c4
//---------------------------------------------------------------------------//
// Include the appropriate header for an underlying message passing
// implementation.
#ifdef C4_SCALAR
#include "C4_Serial.hh"
#endif
#ifdef C4_MPI
#include "C4_MPI.hh"
#endif
#endif // c4_C4_Functions_hh
//---------------------------------------------------------------------------//
// end of c4/C4_Functions.hh
//---------------------------------------------------------------------------//
| 36.767123 | 80 | 0.493081 | [
"object",
"vector"
] |
339fed164087d178775d9399741be33edc3e84cb | 4,332 | cpp | C++ | infoarena.com/AGM2015/caroiaj.cpp | Duxar/problems-sources | b9445ade18b4740ef060b3c7e91cbb71eae1e767 | [
"MIT"
] | null | null | null | infoarena.com/AGM2015/caroiaj.cpp | Duxar/problems-sources | b9445ade18b4740ef060b3c7e91cbb71eae1e767 | [
"MIT"
] | null | null | null | infoarena.com/AGM2015/caroiaj.cpp | Duxar/problems-sources | b9445ade18b4740ef060b3c7e91cbb71eae1e767 | [
"MIT"
] | null | null | null | #ifdef ONLINE_JUDGE
#include <bits/stdc++.h>
#else
#include <algorithm>
#include <bitset>
#include <list>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <map>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <queue>
#endif
using namespace std;
// lambda : [] (int a, int b) -> bool { body return }
// string r_str = R"(raw string)"
#define mp make_pair
#define mt make_tuple
#define eb emplace_back
#define pb push_back
#define fi first
#define se second
#define LL long long
#define ULL unsigned long long
#define PI (atan(1) * 4)
#define BASE 73
#define NMAX 10000
#define NMAX2 20001
#define MOD1 1000000007
#define ALL(V) (V).begin(), (V).end()
#define ALLR(V) (V).rbegin(), (V).rend()
#define CRLINE Duxar(__LINE__);
#define SHOWME(x) cerr << __LINE__ << ": " << #x << " = " << (x) << endl;
#define ENTER putchar('\n');
int dx4[] = {-1, 0, 1, 0};
int dy4[] = {0, 1, 0, -1};
int dx8[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy8[] = {0, 1, 1, 1, 0, -1, -1, -1};
void Duxar(int _this_line) {
#ifndef ONLINE_JUDGE
printf("\n . . . . . . . . . . . . . Passed line - %d\n", _this_line);
#endif
}
bool AreEqual(double a, double b) {
return (fabs(a - b) < 1e-10);
}
template <class T>
bool GetNr(T &_value) {
T _sign = 1;
char ch;
_value = 0;
while(!isdigit(ch = getchar())) {
if (ch == -1) {
return false;
}
ch == '-' ? _sign = -1 : _sign = 1 ;
}
do {
_value = _value * 10 + (ch - '0');
} while(isdigit(ch = getchar()));
_value *= _sign;
return true;
}
template <class T>
void PutNr(T _value, char _ch = ' ') {
cout << _value << _ch;
}
int N;
vector <vector <int> > mat, graph;
vector <int> match_diagonal;
vector <bool> visited;
map <int, int> match_value;
bool FoundNewPath(int node) {
if (visited[node]) {
return false;
}
visited[node] = true;
for (auto to: graph[node]) {
if (match_value[to] == -1) {
match_value[to] = node;
match_diagonal[node] = to;
return true;
}
}
for (auto to: graph[node]) {
if (FoundNewPath(match_value[to])) {
match_value[to] = node;
match_diagonal[node] = to;
return true;
}
}
return false;
}
void Solve() {
int x, i, j, y;
match_diagonal.clear();
mat.clear();
graph.clear();
visited.clear();
GetNr(N);
match_diagonal.resize(2 * N - 1, -1);
mat.resize(N, vector <int> (N, 0));
graph.resize(2 * N - 1, vector <int> ());
visited.resize(2 * N - 1, 0);
for (i = 0; i < N; ++i) {
for (j = 0; j < N; ++j) {
GetNr(x);
match_value[x] = -1;
mat[i][j] = x;
}
}
int diag = 0;
for (j = N - 1; j >= 0; --j, ++diag) {
x = 0; y = j;
while (x < N && y < N) {
graph[diag].pb(mat[x][y]);
++x; ++y;
}
}
for (i = 1; i < N; ++i, ++diag) {
x = i; y = 0;
while (x < N && y < N) {
graph[diag].pb(mat[x][y]);
++x; ++y;
}
}
bool found = true;
while (found) {
found = false;
fill(ALL(visited), 0);
for (i = 0; i < 2 * N - 1; ++i) {
if (!visited[i] && match_diagonal[i] == -1) {
found = FoundNewPath(i) || found;
}
}
}
int cnt = 0;
for (i = 0; i < 2 * N - 1; ++i) {
cnt += match_diagonal[i] != -1;
}
if (cnt != 2 * N - 1) {
printf("Bunicul este dezamagit!\n");
return;
}
printf("DA");
for (i = 2 * N - 2; i >= 0; --i) {
printf(" %d", match_diagonal[i]);
}
putchar('\n');
}
int main(){
string fileInput = "caroiaj";
#ifdef INFOARENA
assert(freopen((fileInput + ".in").c_str(), "r", stdin));
assert(freopen((fileInput + ".out").c_str(), "w", stdout));
#else
#ifndef ONLINE_JUDGE
freopen("/Users/duxar/Workplace/Xcode Projects/Selectie/Selectie/input", "r", stdin);
// freopen("/Users/duxar/Workplace/Xcode Projects/Selectie/Selectie/result", "w", stdout);
#endif
#endif
int T;
GetNr(T);
while (T--) {
Solve();
}
return 0;
}
| 21.235294 | 99 | 0.505771 | [
"vector"
] |
33a0c006d20500b08a5d6b66b597d77ee3284e1a | 3,226 | cpp | C++ | src/SceneTest.cpp | raster77/boids | d219635704d74f9f9041812713285f2209bb46a9 | [
"MIT"
] | null | null | null | src/SceneTest.cpp | raster77/boids | d219635704d74f9f9041812713285f2209bb46a9 | [
"MIT"
] | null | null | null | src/SceneTest.cpp | raster77/boids | d219635704d74f9f9041812713285f2209bb46a9 | [
"MIT"
] | null | null | null | #include <SceneTest.hpp>
SceneTest::SceneTest()
: Scene()
{
}
SceneTest::SceneTest(sf::RenderWindow* window)
: Scene(window)
{
}
SceneTest::~SceneTest()
{
}
void SceneTest::load()
{
target.setRadius(25.f);
target.setOrigin(target.getRadius(), target.getRadius());
target.setFillColor(sf::Color::Transparent);
target.setOutlineColor(sf::Color::Green);
target.setOutlineThickness(1.f);
rnd::Random* rnd = rnd::Random::getInstance();
seekBehavior.setTarget(Vector2f(rnd->getInstance()->getUniformFloat(100.f, 1400.f), rnd->getInstance()->getUniformFloat(100.f, 800.f)));
for(std::size_t i = 0; i < 50; ++i)
{
Vector2f p(rnd->getInstance()->getUniformFloat(100.f, 1400.f), rnd->getInstance()->getUniformFloat(100.f, 800.f));
float r = rnd->getInstance()->getUniformFloat(5.f, 10.f);
obstacles.emplace_back(p, r);
sf::CircleShape c;
c.setRadius(r);
c.setOrigin(r, r);
c.setPosition(p.x, p.y);
c.setFillColor(sf::Color::Red);
obstacleShapes.emplace_back(c);
}
obstacleAvoidanceBehavior.setDistance(50.f);
target.setPosition(seekBehavior.getTarget().x, seekBehavior.getTarget().y);
wanderBehavior.setDistance(150.f);
wanderBehavior.setRadius(50.f);
wanderBehavior.setRandomRange(150.f);
boid.setPosition(rnd->getUniformFloat(100.f, 1500.f), rnd->getUniformFloat(100.f, 800.f));
boid.setRadius(6.f);
boid.setMass(5.f);
boid.setMaxForce(10.f);
boid.setMaxSpeed(250.f);
boid.addBehavior(&wanderBehavior);
//boid.addBehavior(&seekBehavior);
boid.addBehavior(&obstacleAvoidanceBehavior);
boidSprite.setBoid(&boid);
boidSprite.setColor(sf::Color(255, 0, 120));
}
void SceneTest::update(const float dt)
{
std::vector<Obstacle*> obstaclesPtr;
const float maxDist = obstacleAvoidanceBehavior.getDistance() + 10.f;
for(auto& o : obstacles)
{
if(boid.getPosition().distance(o.getPosition()) < maxDist)
{
obstaclesPtr.emplace_back(&o);
}
}
obstacleAvoidanceBehavior.setObstacles(obstaclesPtr);
boid.update(dt);
boidSprite.update();
checkBounds(boid);
}
void SceneTest::draw()
{
for(auto& c : obstacleShapes)
window->draw(c);
window->draw(target);
boidSprite.render(window);
}
void SceneTest::handleEvent(sf::Event& event)
{
if(event.type == sf::Event::KeyPressed) {
if(event.key.code == sf::Keyboard::Escape) {
window->close();
}
if(event.key.code == sf::Keyboard::T) {
boidSprite.showTrail(!boidSprite.isShowTrail());
}
}
if(event.type == sf::Event::MouseButtonPressed) {
if(event.mouseButton.button == sf::Mouse::Button::Left)
{
seekBehavior.setTarget(Vector2f(getMousePosition().x, getMousePosition().y));
target.setPosition(seekBehavior.getTarget().x, seekBehavior.getTarget().y);
}
}
}
void SceneTest::checkBounds(Boid& b)
{
const float x = b.getPosition().x < 0.f ? window->getSize().x : b.getPosition().x > window->getSize().x ? 0.f : b.getPosition().x;
const float y = b.getPosition().y < 0.f ? window->getSize().y : b.getPosition().y > window->getSize().y ? 0.f : b.getPosition().y;
b.setPosition(x, y);
}
| 28.298246 | 139 | 0.656541 | [
"render",
"vector"
] |
33a34349c0431b36e916d476ac1e89b1b53638db | 56,604 | cc | C++ | crawl-ref/source/timed_effects.cc | Hellmonk/posthellcrawl | 362cdb2e511a451683f4754f147d5e737658cc84 | [
"CC0-1.0"
] | null | null | null | crawl-ref/source/timed_effects.cc | Hellmonk/posthellcrawl | 362cdb2e511a451683f4754f147d5e737658cc84 | [
"CC0-1.0"
] | null | null | null | crawl-ref/source/timed_effects.cc | Hellmonk/posthellcrawl | 362cdb2e511a451683f4754f147d5e737658cc84 | [
"CC0-1.0"
] | null | null | null | /**
* @file
* @brief Gametime related functions.
**/
#include "AppHdr.h"
#include "timed_effects.h"
#include "abyss.h"
#include "act-iter.h"
#include "areas.h"
#include "beam.h"
#include "bloodspatter.h"
#include "branch.h"
#include "cloud.h"
#include "coordit.h"
#include "database.h"
#include "dgn-shoals.h"
#include "dgnevent.h"
#include "dungeon.h"
#include "env.h"
#include "exercise.h"
#include "externs.h"
#include "fprop.h"
#include "godpassive.h"
#include "items.h"
#include "libutil.h"
#include "mapmark.h"
#include "message.h"
#include "mgen_data.h"
#include "monster.h"
#include "mon-behv.h"
#include "mon-death.h"
#include "mon-pathfind.h"
#include "mon-pick.h"
#include "mon-place.h"
#include "mon-project.h"
#include "mutation.h"
#include "player.h"
#include "player-stats.h"
#include "random.h"
#include "rot.h"
#include "religion.h"
#include "skills.h"
#include "shout.h"
#include "state.h"
#include "spl-clouds.h"
#include "spl-miscast.h"
#include "stringutil.h"
#include "teleport.h"
#include "terrain.h"
#include "tileview.h"
#include "throw.h"
#include "traps.h"
#include "travel.h"
#include "viewchar.h"
#include "unwind.h"
/**
* Choose a random, spooky hell effect message, print it, and make a loud noise
* if appropriate. (1/6 chance of loud noise.)
*/
static void _hell_effect_noise()
{
const bool loud = one_chance_in(6) && !silenced(you.pos());
string msg = getMiscString(loud ? "hell_effect_noisy"
: "hell_effect_quiet");
if (msg.empty())
msg = "Something hellishly buggy happens.";
mprf(MSGCH_HELL_EFFECT, "%s", msg.c_str());
if (loud)
noisy(15, you.pos());
}
/**
* Choose a random miscast effect (from a weighted list) & apply it to the
* player.
*/
static void _random_hell_miscast()
{
const spschool_flag_type which_miscast
= random_choose_weighted(8, SPTYP_NECROMANCY,
4, SPTYP_SUMMONING,
2, SPTYP_CONJURATION,
1, SPTYP_CHARMS,
1, SPTYP_HEXES);
MiscastEffect(&you, nullptr, HELL_EFFECT_MISCAST, which_miscast,
4 + random2(6), random2avg(97, 3),
"the effects of Hell");
}
/// The thematically appropriate hell effects for a given hell branch.
struct hell_effect_spec
{
/// The type of greater demon to spawn from hell effects.
vector<monster_type> fiend_types;
/// The appropriate theme of miscast effects to toss at the player.
spschool_flag_type miscast_type;
/// A weighted list of lesser creatures to spawn.
vector<pair<monster_type, int>> minor_summons;
};
/// Hell effects for each branch of hell
static map<branch_type, hell_effect_spec> hell_effects_by_branch =
{
{ BRANCH_DIS, { {RANDOM_DEMON_GREATER}, SPTYP_EARTH, {
{ RANDOM_MONSTER, 100 }, // TODO
}}},
{ BRANCH_GEHENNA, { {MONS_BRIMSTONE_FIEND}, SPTYP_FIRE, {
{ RANDOM_MONSTER, 100 }, // TODO
}}},
{ BRANCH_COCYTUS, { {MONS_ICE_FIEND, MONS_SHARD_SHRIKE}, SPTYP_ICE, {
// total weight 100
{ MONS_ZOMBIE, 15 },
{ MONS_SKELETON, 10 },
{ MONS_SIMULACRUM, 10 },
{ MONS_FREEZING_WRAITH, 10 },
{ MONS_FLYING_SKULL, 10 },
{ MONS_TORMENTOR, 10 },
{ MONS_REAPER, 10 },
{ MONS_BONE_DRAGON, 5 },
{ MONS_ICE_DRAGON, 5 },
{ MONS_BLIZZARD_DEMON, 5 },
{ MONS_ICE_DEVIL, 5 },
}}},
{ BRANCH_TARTARUS, { {MONS_TZITZIMITL}, SPTYP_NECROMANCY, {
{ RANDOM_MONSTER, 100 }, // TODO
}}},
};
/**
* Either dump a fiend or a hell-appropriate miscast effect on the player.
*
* 40% chance of fiend, 60% chance of miscast.
*/
static void _themed_hell_summon_or_miscast()
{
const hell_effect_spec *spec = map_find(hell_effects_by_branch,
you.where_are_you);
if (!spec)
die("Attempting to call down a hell effect in a non-hellish branch.");
if (x_chance_in_y(2, 5))
{
const monster_type fiend
= spec->fiend_types[random2(spec->fiend_types.size())];
create_monster(
mgen_data::hostile_at(fiend, true, you.pos())
.set_non_actor_summoner("the effects of Hell"));
}
else
{
MiscastEffect(&you, nullptr, HELL_EFFECT_MISCAST, spec->miscast_type,
4 + random2(6), random2avg(97, 3),
"the effects of Hell");
}
}
/**
* Try to summon at some number of random spawns from the current branch, to
* harass the player & give them easy xp/TSO piety. Occasionally, to kill them.
*
* Min zero, max five, average 1.67.
*
* Can and does summon bands as individual spawns.
*/
static void _minor_hell_summons()
{
hell_effect_spec *spec = map_find(hell_effects_by_branch,
you.where_are_you);
if (!spec)
die("Attempting to call down a hell effect in a non-hellish branch.");
// Try to summon at least one and up to five random monsters. {dlb}
mgen_data mg;
mg.pos = you.pos();
mg.foe = MHITYOU;
mg.non_actor_summoner = "the effects of Hell";
create_monster(mg);
for (int i = 0; i < 4; ++i)
{
if (one_chance_in(3))
{
monster_type *type
= random_choose_weighted(spec->minor_summons);
ASSERT(type);
mg.cls = *type;
create_monster(mg);
}
}
}
/// Nasty things happen to people who spend too long in Hell.
static void _hell_effects(int /*time_delta*/)
{
if (!player_in_hell())
return;
// 50% chance at max piety
if (have_passive(passive_t::resist_hell_effects)
&& x_chance_in_y(you.piety, MAX_PIETY * 2) || is_sanctuary(you.pos()))
{
simple_god_message("'s power protects you from the chaos of Hell!");
return;
}
_hell_effect_noise();
if (one_chance_in(5))
_random_hell_miscast();
else if (x_chance_in_y(4, 11))
_themed_hell_summon_or_miscast();
if (one_chance_in(4)) // NB: No "else"
_minor_hell_summons();
}
// This function checks whether we can turn a wall into a floor space and
// still keep a corridor-like environment. The wall in position x is a
// a candidate for switching if it's flanked by floor grids to two sides
// and by walls (any type) to the remaining cardinal directions.
//
// . # 2
// #x# or .x. -> 0x1
// . # 3
static bool _feat_is_flanked_by_walls(const coord_def &p)
{
const coord_def adjs[] = { coord_def(p.x-1,p.y),
coord_def(p.x+1,p.y),
coord_def(p.x ,p.y-1),
coord_def(p.x ,p.y+1) };
// paranoia!
for (coord_def c : adjs)
if (!in_bounds(c))
return false;
return feat_is_wall(grd(adjs[0])) && feat_is_wall(grd(adjs[1]))
&& feat_has_solid_floor(grd(adjs[2])) && feat_has_solid_floor(grd(adjs[3]))
|| feat_has_solid_floor(grd(adjs[0])) && feat_has_solid_floor(grd(adjs[1]))
&& feat_is_wall(grd(adjs[2])) && feat_is_wall(grd(adjs[3]));
}
// Sometimes if a floor is turned into a wall, a dead-end will be created.
// If this is the case, we need to make sure that it is at least two grids
// deep.
//
// Example: If a wall is built at X (A), two dead-ends are created, a short
// and a long one. The latter is perfectly fine, but the former
// looks a bit odd. If Y is chosen, this looks much better (B).
//
// ####### (A) ####### (B) #######
// ...XY.. ...#... ....#..
// #.##### #.##### #.#####
//
// What this function does is check whether the neighbouring floor grids
// are flanked by walls on both sides, and if so, the grids following that
// also have to be floor flanked by walls.
//
// czd
// a.b -> if (a, b == walls) then (c, d == walls) or return false
// #X#
// .
//
// Grid z may be floor or wall, either way we have a corridor of at least
// length 2.
static bool _deadend_check_wall(const coord_def &p)
{
// The grids to the left and right of p are walls. (We already know that
// they are symmetric, so only need to check one side. We also know that
// the other direction, here up/down must then be non-walls.)
if (feat_is_wall(grd[p.x-1][p.y]))
{
// Run the check twice, once in either direction.
for (int i = -1; i <= 1; i++)
{
if (i == 0)
continue;
const coord_def a(p.x-1, p.y+i);
const coord_def b(p.x+1, p.y+i);
const coord_def c(p.x-1, p.y+2*i);
const coord_def d(p.x+1, p.y+2*i);
if (in_bounds(a) && in_bounds(b)
&& feat_is_wall(grd(a)) && feat_is_wall(grd(b))
&& (!in_bounds(c) || !in_bounds(d)
|| !feat_is_wall(grd(c)) || !feat_is_wall(grd(d))))
{
return false;
}
}
}
else // The grids above and below p are walls.
{
for (int i = -1; i <= 1; i++)
{
if (i == 0)
continue;
const coord_def a(p.x+i , p.y-1);
const coord_def b(p.x+i , p.y+1);
const coord_def c(p.x+2*i, p.y-1);
const coord_def d(p.x+2*i, p.y+1);
if (in_bounds(a) && in_bounds(b)
&& feat_is_wall(grd(a)) && feat_is_wall(grd(b))
&& (!in_bounds(c) || !in_bounds(d)
|| !feat_is_wall(grd(c)) || !feat_is_wall(grd(d))))
{
return false;
}
}
}
return true;
}
// Similar to the above, checks whether turning a wall grid into floor
// would create a short "dead-end" of only 1 grid.
//
// In the example below, X would create miniature dead-ends at positions
// a and b, but both Y and Z avoid this, and the resulting mini-mazes
// look much better.
//
// ######## (A) ######## (B) ######## (C) ########
// #.....#. #....a#. #.....#. #.....#.
// #.#YXZ#. #.##.##. #.#.###. #.###.#.
// #.#..... #.#b.... #.#..... #.#.....
//
// In general, if a floor grid horizontally or vertically adjacent to the
// change target has a floor neighbour diagonally adjacent to the change
// target, the next neighbour in the same direction needs to be floor,
// as well.
static bool _deadend_check_floor(const coord_def &p)
{
if (feat_is_wall(grd[p.x-1][p.y]))
{
for (int i = -1; i <= 1; i++)
{
if (i == 0)
continue;
const coord_def a(p.x, p.y+2*i);
if (!in_bounds(a) || feat_has_solid_floor(grd(a)))
continue;
for (int j = -1; j <= 1; j++)
{
if (j == 0)
continue;
const coord_def b(p.x+2*j, p.y+i);
if (!in_bounds(b))
continue;
const coord_def c(p.x+j, p.y+i);
if (feat_has_solid_floor(grd(c)) && !feat_has_solid_floor(grd(b)))
return false;
}
}
}
else
{
for (int i = -1; i <= 1; i++)
{
if (i == 0)
continue;
const coord_def a(p.x+2*i, p.y);
if (!in_bounds(a) || feat_has_solid_floor(grd(a)))
continue;
for (int j = -1; j <= 1; j++)
{
if (j == 0)
continue;
const coord_def b(p.x+i, p.y+2*j);
if (!in_bounds(b))
continue;
const coord_def c(p.x+i, p.y+j);
if (feat_has_solid_floor(grd(c)) && !feat_has_solid_floor(grd(b)))
return false;
}
}
}
return true;
}
// Changes a small portion of a labyrinth by exchanging wall against floor
// grids in such a way that connectivity remains guaranteed.
void change_labyrinth(bool msg)
{
int size = random_range(12, 24); // size of the shifted area (square)
coord_def c1, c2; // upper left, lower right corners of the shifted area
vector<coord_def> targets;
// Try 10 times for an area that is little mapped.
for (int tries = 10; tries > 0; --tries)
{
targets.clear();
int x = random_range(LABYRINTH_BORDER, GXM - LABYRINTH_BORDER - size);
int y = random_range(LABYRINTH_BORDER, GYM - LABYRINTH_BORDER - size);
c1 = coord_def(x, y);
c2 = coord_def(x + size, y + size);
int count_known = 0;
for (rectangle_iterator ri(c1, c2); ri; ++ri)
if (env.map_knowledge(*ri).seen())
count_known++;
if (tries > 1 && count_known > size * size / 6)
continue;
// Fill a vector with wall grids that are potential targets for
// swapping against floor, i.e. are flanked by walls to two cardinal
// directions, and by floor on the two remaining sides.
for (rectangle_iterator ri(c1, c2); ri; ++ri)
{
if (env.map_knowledge(*ri).seen() || !feat_is_wall(grd(*ri)))
continue;
// Skip on grids inside vaults so as not to disrupt them.
if (map_masked(*ri, MMT_VAULT))
continue;
// Make sure we don't accidentally create "ugly" dead-ends.
if (_feat_is_flanked_by_walls(*ri) && _deadend_check_floor(*ri))
targets.push_back(*ri);
}
if (targets.size() >= 8)
break;
}
if (targets.empty())
{
if (msg)
mpr("No unexplored wall grids found!");
return;
}
if (msg)
{
mprf(MSGCH_DIAGNOSTICS, "Changing labyrinth from (%d, %d) to (%d, %d)",
c1.x, c1.y, c2.x, c2.y);
string path_str = "";
mprf(MSGCH_DIAGNOSTICS, "Here's the list of targets: ");
for (coord_def target : targets)
path_str += make_stringf("(%d, %d) ", target.x, target.y);
mprf(MSGCH_DIAGNOSTICS, "%s", path_str.c_str());
mprf(MSGCH_DIAGNOSTICS, "-> #targets = %u", (unsigned int)targets.size());
}
#ifdef WIZARD
// Remove old highlighted areas to make place for the new ones.
if (you.wizard)
for (rectangle_iterator ri(1); ri; ++ri)
env.pgrid(*ri) &= ~(FPROP_HIGHLIGHT);
#endif
// How many switches we'll be doing.
const int max_targets = random_range(min((int) targets.size(), 12),
min((int) targets.size(), 45));
// Shuffle the targets, then pick the max_targets first ones.
shuffle_array(targets);
// For each of the chosen wall grids, calculate the path connecting the
// two floor grids to either side, and block off one floor grid on this
// path to close the circle opened by turning the wall into floor.
for (int count = 0; count < max_targets; count++)
{
const coord_def c(targets[count]);
// Maybe not valid anymore...
if (!feat_is_wall(grd(c)) || !_feat_is_flanked_by_walls(c))
continue;
// Use the adjacent floor grids as source and destination.
coord_def src(c.x-1,c.y);
coord_def dst(c.x+1,c.y);
if (!feat_has_solid_floor(grd(src)) || !feat_has_solid_floor(grd(dst)))
{
src = coord_def(c.x, c.y-1);
dst = coord_def(c.x, c.y+1);
}
// Pathfinding from src to dst...
monster_pathfind mp;
bool success = mp.init_pathfind(src, dst, false, msg);
if (!success)
{
if (msg)
mprf(MSGCH_DIAGNOSTICS, "Something went badly wrong - no path found!");
continue;
}
// Get the actual path.
const vector<coord_def> path = mp.backtrack();
// Replace the wall with floor, but preserve the old grid in case
// we find no floor grid to swap with.
// It's better if the change is done now, so the grid can be
// treated as floor rather than a wall, and we don't need any
// special cases.
dungeon_feature_type old_grid = grd(c);
grd(c) = DNGN_FLOOR;
set_terrain_changed(c);
// Add all floor grids meeting a couple of conditions to a vector
// of potential switch points.
vector<coord_def> points;
for (const coord_def p : path)
{
// The point must be inside the changed area.
if (p.x < c1.x || p.x > c2.x || p.y < c1.y || p.y > c2.y)
continue;
// Only replace plain floor.
if (grd(p) != DNGN_FLOOR)
continue;
// Don't change any grids we remember.
if (env.map_knowledge(p).seen())
continue;
// We don't want to deal with monsters being shifted around.
if (monster_at(p))
continue;
// Do not pick a grid right next to the original wall.
if (abs(p.x-c.x) + abs(p.y-c.y) <= 1)
continue;
if (_feat_is_flanked_by_walls(p) && _deadend_check_wall(p))
points.push_back(p);
}
if (points.empty())
{
// Take back the previous change.
grd(c) = old_grid;
set_terrain_changed(c);
continue;
}
// Randomly pick one floor grid from the vector and replace it
// with an adjacent wall type.
const int pick = random_range(0, (int) points.size() - 1);
const coord_def p(points[pick]);
if (msg)
{
mprf(MSGCH_DIAGNOSTICS, "Switch %d (%d, %d) with %d (%d, %d).",
(int) old_grid, c.x, c.y, (int) grd(p), p.x, p.y);
}
#ifdef WIZARD
if (you.wizard)
{
// Highlight the switched grids.
env.pgrid(c) |= FPROP_HIGHLIGHT;
env.pgrid(p) |= FPROP_HIGHLIGHT;
}
#endif
// Shift blood some of the time.
if (is_bloodcovered(c))
{
if (one_chance_in(4))
{
int wall_count = 0;
coord_def old_adj(c);
for (adjacent_iterator ai(c); ai; ++ai)
if (feat_is_wall(grd(*ai)) && one_chance_in(++wall_count))
old_adj = *ai;
if (old_adj != c && maybe_bloodify_square(old_adj))
env.pgrid(c) &= (~FPROP_BLOODY);
}
}
else if (one_chance_in(500))
{
// Rarely add blood randomly, accumulating with time...
maybe_bloodify_square(c);
}
// Rather than use old_grid directly, replace with an adjacent
// wall type, preferably stone, rock, or metal.
old_grid = grd[p.x-1][p.y];
if (!feat_is_wall(old_grid))
{
old_grid = grd[p.x][p.y-1];
if (!feat_is_wall(old_grid))
{
if (msg)
{
mprf(MSGCH_DIAGNOSTICS,
"No adjacent walls at pos (%d, %d)?", p.x, p.y);
}
old_grid = DNGN_STONE_WALL;
}
else if (old_grid != DNGN_ROCK_WALL && old_grid != DNGN_STONE_WALL
&& old_grid != DNGN_METAL_WALL && !one_chance_in(3))
{
old_grid = grd[p.x][p.y+1];
}
}
else if (old_grid != DNGN_ROCK_WALL && old_grid != DNGN_STONE_WALL
&& old_grid != DNGN_METAL_WALL && !one_chance_in(3))
{
old_grid = grd[p.x+1][p.y];
}
grd(p) = old_grid;
set_terrain_changed(p);
// Shift blood some of the time.
if (is_bloodcovered(p))
{
if (one_chance_in(4))
{
int floor_count = 0;
coord_def new_adj(p);
for (adjacent_iterator ai(c); ai; ++ai)
if (feat_has_solid_floor(grd(*ai)) && one_chance_in(++floor_count))
new_adj = *ai;
if (new_adj != p && maybe_bloodify_square(new_adj))
env.pgrid(p) &= (~FPROP_BLOODY);
}
}
else if (one_chance_in(100))
{
// Occasionally add blood randomly, accumulating with time...
maybe_bloodify_square(p);
}
}
// The directions are used to randomly decide where to place items that
// have ended up in walls during the switching.
vector<coord_def> dirs;
dirs.emplace_back(-1,-1);
dirs.emplace_back(0,-1);
dirs.emplace_back(1,-1);
dirs.emplace_back(-1, 0);
dirs.emplace_back(1, 0);
dirs.emplace_back(-1, 1);
dirs.emplace_back(0, 1);
dirs.emplace_back(1, 1);
// Search the entire shifted area for stacks of items now stuck in walls
// and move them to a random adjacent non-wall grid.
for (rectangle_iterator ri(c1, c2); ri; ++ri)
{
if (!feat_is_wall(grd(*ri)) || igrd(*ri) == NON_ITEM)
continue;
if (msg)
{
mprf(MSGCH_DIAGNOSTICS,
"Need to move around some items at pos (%d, %d)...",
ri->x, ri->y);
}
// Search the eight possible directions in random order.
shuffle_array(dirs);
for (coord_def dir : dirs)
{
const coord_def p = *ri + dir;
if (!in_bounds(p))
continue;
if (feat_has_solid_floor(grd(p)))
{
// Once a valid grid is found, move all items from the
// stack onto it.
move_items(*ri, p);
if (msg)
{
mprf(MSGCH_DIAGNOSTICS, "Moved items over to (%d, %d)",
p.x, p.y);
}
break;
}
}
}
// Recheck item coordinates, to make totally sure.
fix_item_coordinates();
// Finally, give the player a clue about what just happened.
const int which = (silenced(you.pos()) ? 2 + random2(2)
: random2(4));
switch (which)
{
case 0: mpr("You hear an odd grinding sound!"); break;
case 1: mpr("You hear the creaking of ancient gears!"); break;
case 2: mpr("The floor suddenly vibrates beneath you!"); break;
case 3: mpr("You feel a sudden draft!"); break;
}
}
static void _handle_magic_contamination()
{
int added_contamination = 0;
// Scale has been increased by a factor of 1000, but the effect now happens
// every turn instead of every 20 turns, so everything has been multiplied
// by 50 and scaled to you.time_taken.
if (you.duration[DUR_INVIS])
added_contamination += 30;
if (you.duration[DUR_HASTE])
added_contamination += 30;
#if TAG_MAJOR_VERSION == 34
if (you.duration[DUR_REGENERATION] && you.species == SP_DJINNI)
added_contamination += 20;
#endif
// The Orb halves dissipation (well a bit more, I had to round it),
// but won't cause glow on its own -- otherwise it'd spam the player
// with messages about contamination oscillating near zero.
if (you.magic_contamination && player_has_orb())
added_contamination += 13;
// Normal dissipation
if (!you.duration[DUR_INVIS] && !you.duration[DUR_HASTE])
added_contamination -= 25;
// Scaling to turn length
added_contamination = div_rand_round(added_contamination * you.time_taken,
BASELINE_DELAY);
contaminate_player(added_contamination, false);
}
// Bad effects from magic contamination.
static void _magic_contamination_effects()
{
mprf(MSGCH_WARN, "Your body shudders with the violent release "
"of wild energies!");
const int contam = you.magic_contamination;
// For particularly violent releases, make a little boom.
if (contam > 10000 && coinflip())
{
bolt beam;
beam.flavour = BEAM_RANDOM;
beam.glyph = dchar_glyph(DCHAR_FIRED_BURST);
beam.damage = dice_def(3, div_rand_round(contam, 2000));
beam.target = you.pos();
beam.name = "magical storm";
//XXX: Should this be MID_PLAYER?
beam.source_id = MID_NOBODY;
beam.aux_source = "a magical explosion";
beam.ex_size = max(1, min(LOS_RADIUS,
div_rand_round(contam, 15000)));
beam.ench_power = div_rand_round(contam, 200);
beam.is_explosion = true;
beam.explode();
}
#if TAG_MAJOR_VERSION == 34
const mutation_permanence_class mutclass = you.species == SP_DJINNI
? MUTCLASS_TEMPORARY
: MUTCLASS_NORMAL;
#else
const mutation_permanence_class mutclass = MUTCLASS_NORMAL;
#endif
// We want to warp the player, not do good stuff!
mutate(one_chance_in(5) ? RANDOM_MUTATION : RANDOM_BAD_MUTATION,
"mutagenic glow", true, coinflip(), false, false, mutclass, false);
// we're meaner now, what with explosions and whatnot, but
// we dial down the contamination a little faster if its actually
// mutating you. -- GDL
contaminate_player(-(random2(contam / 4) + 1000));
}
// Checks if the player should be hit with magic contaimination effects,
// then actually does it if they should be.
static void _handle_magic_contamination(int /*time_delta*/)
{
// [ds] Move magic contamination effects closer to b26 again.
const bool glow_effect = player_severe_contamination()
&& x_chance_in_y(you.magic_contamination, 12000);
if (glow_effect)
{
if (is_sanctuary(you.pos()))
{
mprf(MSGCH_GOD, "Your body momentarily shudders from a surge of wild "
"energies until Zin's power calms it.");
}
else
_magic_contamination_effects();
}
}
// Exercise armour *xor* stealth skill: {dlb}
static void _wait_practice(int /*time_delta*/)
{
practise_waiting();
}
static void _lab_change(int /*time_delta*/)
{
if (player_in_branch(BRANCH_LABYRINTH))
change_labyrinth();
}
// Update the abyss speed. This place is unstable and the speed can
// fluctuate. It's not a constant increase.
static void _abyss_speed(int /*time_delta*/)
{
if (!player_in_branch(BRANCH_ABYSS))
return;
if (have_passive(passive_t::slow_abyss) && coinflip())
; // Speed change less often for Chei.
else if (coinflip() && you.abyss_speed < 100)
++you.abyss_speed;
else if (one_chance_in(5) && you.abyss_speed > 0)
--you.abyss_speed;
}
static void _jiyva_effects(int /*time_delta*/)
{
return;
}
static void _evolve(int time_delta)
{
if (you.get_mutation_level(MUT_EVOLUTION))
if (x_chance_in_y(4, 5)
&& you.attribute[ATTR_EVOL_XP] * (1 + random2(10))
> (int)exp_needed(you.experience_level + 1))
{
you.attribute[ATTR_EVOL_XP] = 0;
mpr("You feel a genetic drift.");
bool evol = false;
if(you.species == SP_KOBOLD && one_chance_in(7))
{
evol = one_chance_in(4) ?
delete_mutation(RANDOM_KOBOLD_MUTATION, "evolution", false) :
mutate(RANDOM_KOBOLD_MUTATION, "evolution",
false, false, false, false, MUTCLASS_NORMAL, true);
}
else
{
evol = one_chance_in(5) ?
delete_mutation(RANDOM_BAD_MUTATION, "evolution", false) :
mutate(coinflip() ? RANDOM_GOOD_MUTATION : RANDOM_MUTATION,
"evolution", false, false, false, false, MUTCLASS_NORMAL,
true);
}
// it would kill itself anyway, but let's speed that up
if (one_chance_in(10)
&& (!you.rmut_from_item()
|| one_chance_in(10)))
{
const string reason = "end of evolution";
evol |= delete_mutation(MUT_EVOLUTION, reason, false);
}
// interrupt the player only if something actually happened
if (evol)
more();
}
}
// Get around C++ dividing integers towards 0.
static int _div(int num, int denom)
{
div_t res = div(num, denom);
return res.rem >= 0 ? res.quot : res.quot - 1;
}
static const pop_entry _antiscum_summons[] =
{ // reeeeeemove scummers
{ 1, 7, 2, FLAT, MONS_CENTAUR },
{ 4, 12, 2, FLAT, MONS_ORC_SORCERER },
{ 10, 18, 2, FLAT, MONS_DEEP_ELF_HIGH_PRIEST },
{ 15, 24, 2, FLAT, MONS_TITAN },
{ 21, 27, 2, FLAT, MONS_ANCIENT_LICH },
{ 26, 27, 2, FLAT, MONS_PANDEMONIUM_LORD },
{ 0,0,0,FLAT,MONS_0 }
};
static bool _antiscumming_summon()
{
monster_type mtyp = pick_monster_from(_antiscum_summons,
you.experience_level);
mgen_data mg = mgen_data::hostile_at(mtyp, true, you.pos())
.set_summoned(nullptr, 0, 0)
.set_non_actor_summoner("The dungeon");
mg.extra_flags |= (MF_NO_REWARD | MF_HARD_RESET);
return create_monster(mg, false);
}
static void _antiscumming(int /*time_delta*/)
{
if (crawl_state.difficulty == DIFFICULTY_CASUAL)
return;
if(env.turns_on_level < 3000)
return;
if(player_in_branch(BRANCH_ABYSS))
return;
//make it loud
noisy(30, you.pos());
mprf(MSGCH_WARN, "The dungeon lashes out against you!");
int num_summons = 2 + random2(4);
for(int i = 1; i <= num_summons; ++i)
{
_antiscumming_summon();
}
}
static void _timeout_traps(int /*time_delta*/)
{
for (rectangle_iterator ri(0); ri; ++ri)
{
if (in_bounds(*ri))
{
trap_def* ptrap = trap_at(*ri);
if (ptrap && ptrap->type == TRAP_ZOT && ptrap->ammo_qty)
{
ptrap->ammo_qty -= 1;
if(ptrap->ammo_qty <= 0)
destroy_trap(*ri);
}
}
}
}
struct timed_effect
{
void (*trigger)(int);
int min_time;
int max_time;
bool arena;
};
static struct timed_effect timed_effects[] =
{
{ rot_floor_items, 200, 200, true },
{ _hell_effects, 200, 600, false },
#if TAG_MAJOR_VERSION == 34
{ nullptr, 0, 0, false },
#endif
{ _handle_magic_contamination, 200, 600, false },
#if TAG_MAJOR_VERSION == 34
{ nullptr, 0, 0, false },
#endif
{ handle_god_time, 100, 300, false },
#if TAG_MAJOR_VERSION == 34
{ nullptr, 0, 0, false },
#endif
{ _antiscumming, 400, 700, false },
{ _wait_practice, 100, 300, false },
{ _lab_change, 1000, 3000, false },
{ _abyss_speed, 100, 300, false },
{ _jiyva_effects, 100, 300, false },
{ _evolve, 5000, 15000, false },
#if TAG_MAJOR_VERSION == 34
{ nullptr, 0, 0, false },
#endif
{ _timeout_traps, 200, 300, false },
};
// Do various time related actions...
void handle_time()
{
int base_time = you.elapsed_time % 200;
int old_time = base_time - you.time_taken;
// The checks below assume the function is called at least
// once every 50 elapsed time units.
// Every 5 turns, spawn random monsters
if (_div(base_time, 50) > _div(old_time, 50))
{
spawn_random_monsters();
if (player_in_branch(BRANCH_ABYSS))
for (int i = 1; i < you.depth; ++i)
if (x_chance_in_y(i, 5))
spawn_random_monsters();
}
// Labyrinth and Abyss maprot.
if (player_in_branch(BRANCH_LABYRINTH) || player_in_branch(BRANCH_ABYSS))
forget_map(true);
// Magic contamination from spells and Orb.
if (!crawl_state.game_is_arena())
_handle_magic_contamination();
for (unsigned int i = 0; i < ARRAYSZ(timed_effects); i++)
{
if (crawl_state.game_is_arena() && !timed_effects[i].arena)
continue;
if (!timed_effects[i].trigger)
{
if (you.next_timer_effect[i] < INT_MAX)
you.next_timer_effect[i] = INT_MAX;
continue;
}
if (you.elapsed_time >= you.next_timer_effect[i])
{
int time_delta = you.elapsed_time - you.last_timer_effect[i];
(timed_effects[i].trigger)(time_delta);
you.last_timer_effect[i] = you.next_timer_effect[i];
you.next_timer_effect[i] =
you.last_timer_effect[i]
+ random_range(timed_effects[i].min_time,
timed_effects[i].max_time);
}
}
}
/**
* Return the number of turns it takes for monsters to forget about the player
* 50% of the time.
*
* @param The intelligence of the monster.
* @return An average number of turns before the monster forgets.
*/
static int _mon_forgetfulness_time(mon_intel_type intelligence)
{
switch (intelligence)
{
case I_HUMAN:
return 600;
case I_ANIMAL:
return 300;
case I_BRAINLESS:
return 150;
default:
die("Invalid intelligence type!");
}
}
/**
* Make monsters forget about the player after enough time passes off-level.
*
* @param mon The monster in question.
* @param mon_turns Monster turns. (Turns * monster speed)
* @return Whether the monster forgot about the player.
*/
static bool _monster_forget(monster* mon, int mon_turns)
{
// After x turns, half of the monsters will have forgotten about the
// player. A given monster has a 95% chance of forgetting the player after
// 4*x turns.
const int forgetfulness_time = _mon_forgetfulness_time(mons_intel(*mon));
const int forget_chances = mon_turns / forgetfulness_time;
// n.b. this is an integer division, so if range < forgetfulness_time
// nothing happens
if (bernoulli(forget_chances, 0.5))
{
mon->behaviour = BEH_WANDER;
mon->foe = MHITNOT;
mon->target = random_in_bounds();
return true;
}
return false;
}
/**
* Make ranged monsters flee from the player during their time offlevel.
*
* @param mon The monster in question.
*/
static void _monster_flee(monster *mon)
{
mon->behaviour = BEH_FLEE;
dprf("backing off...");
if (mon->pos() != mon->target)
return;
// If the monster is on the target square, fleeing won't work.
if (in_bounds(env.old_player_pos) && env.old_player_pos != mon->pos())
{
// Flee from player's old position if different.
mon->target = env.old_player_pos;
return;
}
// Randomise the target so we have a direction to flee.
coord_def mshift(random2(3) - 1, random2(3) - 1);
// Bounds check: don't let fleeing monsters try to run off the grid.
const coord_def s = mon->target + mshift;
if (!in_bounds_x(s.x))
mshift.x = 0;
if (!in_bounds_y(s.y))
mshift.y = 0;
mon->target.x += mshift.x;
mon->target.y += mshift.y;
return;
}
/**
* Make a monster take a number of moves toward (or away from, if fleeing)
* their current target, very crudely.
*
* @param mon The mon in question.
* @param moves The number of moves to take.
*/
static void _catchup_monster_move(monster* mon, int moves)
{
coord_def pos(mon->pos());
// Dirt simple movement.
for (int i = 0; i < moves; ++i)
{
coord_def inc(mon->target - pos);
inc = coord_def(sgn(inc.x), sgn(inc.y));
if (mons_is_retreating(*mon))
inc *= -1;
// Bounds check: don't let shifting monsters try to run off the
// grid.
const coord_def s = pos + inc;
if (!in_bounds_x(s.x))
inc.x = 0;
if (!in_bounds_y(s.y))
inc.y = 0;
if (inc.origin())
break;
const coord_def next(pos + inc);
const dungeon_feature_type feat = grd(next);
if (feat_is_solid(feat)
|| monster_at(next)
|| !monster_habitable_grid(mon, feat))
{
break;
}
pos = next;
}
if (!mon->shift(pos))
mon->shift(mon->pos());
}
/**
* Move monsters around to fake them walking around while player was
* off-level.
*
* Does not account for monster move speeds.
*
* Also make them forget about the player over time.
*
* @param mon The monster under consideration
* @param turns The number of offlevel player turns to simulate.
*/
static void _catchup_monster_moves(monster* mon, int turns)
{
// Summoned monsters might have disappeared.
if (!mon->alive())
return;
// Expire friendly summons
if (mon->friendly() && mon->is_summoned() && !mon->is_perm_summoned())
{
// You might still see them disappear if you were quick
if (turns > 2)
monster_die(mon, KILL_DISMISSED, NON_MONSTER);
else
{
mon_enchant abj = mon->get_ench(ENCH_ABJ);
abj.duration = 0;
mon->update_ench(abj);
}
return;
}
// Don't move non-land or stationary monsters around.
if (mons_primary_habitat(*mon) != HT_LAND
|| mons_is_zombified(*mon)
&& mons_class_primary_habitat(mon->base_monster) != HT_LAND
|| mon->is_stationary())
{
return;
}
// Don't shift ballistomycete spores since that would disrupt their trail.
if (mon->type == MONS_BALLISTOMYCETE_SPORE)
return;
// special movement code for ioods, boulder beetles...
if (mon->is_projectile())
{
iood_catchup(mon, turns);
return;
}
// Let sleeping monsters lie.
if (mon->asleep() || mon->paralysed())
return;
const int mon_turns = (turns * mon->speed) / 10;
const int moves = min(mon_turns, 50);
// probably too annoying even for DEBUG_DIAGNOSTICS
dprf("mon #%d: range %d; "
"pos (%d,%d); targ %d(%d,%d); flags %" PRIx64,
mon->mindex(), mon_turns, mon->pos().x, mon->pos().y,
mon->foe, mon->target.x, mon->target.y, mon->flags.flags);
if (mon_turns <= 0)
return;
// did the monster forget about the player?
const bool forgot = _monster_forget(mon, mon_turns);
// restore behaviour later if we start fleeing
unwind_var<beh_type> saved_beh(mon->behaviour);
if (!forgot && mons_has_ranged_attack(*mon))
{
// If we're doing short time movement and the monster has a
// ranged attack (missile or spell), then the monster will
// flee to gain distance if it's "too close", else it will
// just shift its position rather than charge the player. -- bwr
if (grid_distance(mon->pos(), mon->target) >= 3)
{
mon->shift(mon->pos());
dprf("shifted to (%d, %d)", mon->pos().x, mon->pos().y);
return;
}
_monster_flee(mon);
}
_catchup_monster_move(mon, moves);
dprf("moved to (%d, %d)", mon->pos().x, mon->pos().y);
}
/**
* Update a monster's enchantments when the player returns
* to the level.
*
* Management for enchantments... problems with this are the oddities
* (monster dying from poison several thousands of turns later), and
* game balance.
*
* Consider: Poison/Sticky Flame a monster at range and leave, monster
* dies but can't leave level to get to player (implied game balance of
* the delayed damage is that the monster could be a danger before
* it dies). This could be fixed by keeping some monsters active
* off level and allowing them to take stairs (a very serious change).
*
* Compare this to the current abuse where the player gets
* effectively extended duration of these effects (although only
* the actual effects only occur on level, the player can leave
* and heal up without having the effect disappear).
*
* This is a simple compromise between the two... the enchantments
* go away, but the effects don't happen off level. -- bwr
*
* @param levels XXX: sometimes the missing aut/10, sometimes aut/100
*/
void monster::timeout_enchantments(int levels)
{
if (enchantments.empty())
return;
const mon_enchant_list ec = enchantments;
for (auto &entry : ec)
{
switch (entry.first)
{
case ENCH_POISON: case ENCH_CORONA:
case ENCH_STICKY_FLAME: case ENCH_ABJ: case ENCH_SHORT_LIVED:
case ENCH_HASTE: case ENCH_MIGHT: case ENCH_FEAR:
case ENCH_CHARM: case ENCH_SLEEP_WARY: case ENCH_SICK:
case ENCH_PARALYSIS: case ENCH_PETRIFYING:
case ENCH_PETRIFIED: case ENCH_SWIFT: case ENCH_SILENCE:
case ENCH_LOWERED_MR: case ENCH_SOUL_RIPE: case ENCH_ANTIMAGIC:
case ENCH_FEAR_INSPIRING: case ENCH_REGENERATION: case ENCH_RAISED_MR:
case ENCH_MIRROR_DAMAGE: case ENCH_LIQUEFYING:
case ENCH_SILVER_CORONA: case ENCH_DAZED: case ENCH_FAKE_ABJURATION:
case ENCH_BREATH_WEAPON: case ENCH_WRETCHED:
case ENCH_SCREAMED: case ENCH_BLIND: case ENCH_WORD_OF_RECALL:
case ENCH_INJURY_BOND: case ENCH_FLAYED: case ENCH_BARBS:
case ENCH_AGILE: case ENCH_FROZEN:
case ENCH_BLACK_MARK: case ENCH_SAP_MAGIC: case ENCH_NEUTRAL_BRIBED:
case ENCH_FRIENDLY_BRIBED: case ENCH_CORROSION: case ENCH_GOLD_LUST:
case ENCH_RESISTANCE: case ENCH_HEXED: case ENCH_IDEALISED:
case ENCH_BOUND_SOUL:
case ENCH_STILL_WINDS: case ENCH_PHASE_SHIFT:
case ENCH_WHIRLWIND_PINNED:
lose_ench_levels(entry.second, levels);
break;
case ENCH_SLOW:
if (torpor_slowed())
{
lose_ench_levels(entry.second,
min(levels, entry.second.degree - 1));
}
else
{
lose_ench_levels(entry.second, levels);
if (props.exists(TORPOR_SLOWED_KEY))
props.erase(TORPOR_SLOWED_KEY);
}
break;
case ENCH_INVIS:
if (!mons_class_flag(type, M_INVIS))
lose_ench_levels(entry.second, levels);
break;
case ENCH_INSANE:
case ENCH_BERSERK:
case ENCH_INNER_FLAME:
case ENCH_ROLLING:
case ENCH_MERFOLK_AVATAR_SONG:
case ENCH_INFESTATION:
del_ench(entry.first);
break;
case ENCH_FATIGUE:
del_ench(entry.first);
del_ench(ENCH_SLOW);
break;
case ENCH_TP:
teleport(true);
del_ench(entry.first);
break;
case ENCH_CONFUSION:
if (!mons_class_flag(type, M_CONFUSED))
del_ench(entry.first);
// That triggered a behaviour_event, which could have made a
// pacified monster leave the level.
if (alive() && !is_stationary())
monster_blink(this, true);
break;
case ENCH_HELD:
del_ench(entry.first);
break;
case ENCH_TIDE:
{
const int actdur = speed_to_duration(speed) * levels;
lose_ench_duration(entry.first, actdur);
break;
}
case ENCH_SLOWLY_DYING:
{
const int actdur = speed_to_duration(speed) * levels;
if (lose_ench_duration(entry.first, actdur))
monster_die(this, KILL_MISC, NON_MONSTER, true);
break;
}
default:
break;
}
if (!alive())
break;
}
}
/**
* Update the level upon the player's return.
*
* @param elapsedTime how long the player was away.
*/
void update_level(int elapsedTime)
{
ASSERT(!crawl_state.game_is_arena());
const int turns = elapsedTime / 10;
#ifdef DEBUG_DIAGNOSTICS
int mons_total = 0;
dprf("turns: %d", turns);
#endif
rot_floor_items(elapsedTime);
shoals_apply_tides(turns, true, turns < 5);
timeout_tombs(turns);
if (env.sanctuary_time)
{
if (turns >= env.sanctuary_time)
remove_sanctuary();
else
env.sanctuary_time -= turns;
}
dungeon_events.fire_event(
dgn_event(DET_TURN_ELAPSED, coord_def(0, 0), turns * 10));
for (monster_iterator mi; mi; ++mi)
{
#ifdef DEBUG_DIAGNOSTICS
mons_total++;
#endif
// Pacified monsters often leave the level now.
if (mi->pacified() && turns > random2(40) + 21)
{
make_mons_leave_level(*mi);
continue;
}
// Following monsters don't get movement.
if (mi->flags & MF_JUST_SUMMONED)
continue;
// XXX: Allow some spellcasting (like Healing and Teleport)? - bwr
// const bool healthy = (mi->hit_points * 2 > mi->max_hit_points);
mi->heal(div_rand_round(turns * mi->off_level_regen_rate(), 100));
// Handle nets specially to remove the trapping property of the net.
if (mi->caught())
mi->del_ench(ENCH_HELD, true);
_catchup_monster_moves(*mi, turns);
mi->foe_memory = max(mi->foe_memory - turns, 0);
if (turns >= 10 && mi->alive())
mi->timeout_enchantments(turns / 10);
}
#ifdef DEBUG_DIAGNOSTICS
dprf("total monsters on level = %d", mons_total);
#endif
delete_all_clouds();
}
static void _drop_tomb(const coord_def& pos, bool premature, bool zin)
{
int count = 0;
monster* mon = monster_at(pos);
// Don't wander on duty!
if (mon)
mon->behaviour = BEH_SEEK;
bool seen_change = false;
for (adjacent_iterator ai(pos); ai; ++ai)
{
// "Normal" tomb (card or monster spell)
if (!zin && revert_terrain_change(*ai, TERRAIN_CHANGE_TOMB))
{
count++;
if (you.see_cell(*ai))
seen_change = true;
}
// Zin's Imprison.
else if (zin && revert_terrain_change(*ai, TERRAIN_CHANGE_IMPRISON))
{
for (map_marker *mark : env.markers.get_markers_at(*ai))
{
if (mark->property("feature_description")
== "a gleaming silver wall")
{
env.markers.remove(mark);
}
}
env.grid_colours(*ai) = 0;
tile_clear_flavour(*ai);
tile_init_flavour(*ai);
count++;
if (you.see_cell(*ai))
seen_change = true;
}
}
if (count)
{
if (seen_change && !zin)
mprf("The walls disappear%s!", premature ? " prematurely" : "");
else if (seen_change && zin)
{
mprf("Zin %s %s %s.",
(mon) ? "releases"
: "dismisses",
(mon) ? mon->name(DESC_THE).c_str()
: "the silver walls,",
(mon) ? make_stringf("from %s prison",
mon->pronoun(PRONOUN_POSSESSIVE).c_str()).c_str()
: "but there is nothing inside them");
}
else
{
if (!silenced(you.pos()))
mprf(MSGCH_SOUND, "You hear a deep rumble.");
else
mpr("You feel the ground shudder.");
}
}
}
static vector<map_malign_gateway_marker*> _get_malign_gateways()
{
vector<map_malign_gateway_marker*> mm_markers;
for (map_marker *mark : env.markers.get_all(MAT_MALIGN))
{
if (mark->get_type() != MAT_MALIGN)
continue;
map_malign_gateway_marker *mmark = dynamic_cast<map_malign_gateway_marker*>(mark);
mm_markers.push_back(mmark);
}
return mm_markers;
}
int count_malign_gateways()
{
return _get_malign_gateways().size();
}
void timeout_malign_gateways(int duration)
{
// Passing 0 should allow us to just touch the gateway and see
// if it should decay. This, in theory, should resolve the one
// turn delay between it timing out and being recastable. -due
for (map_malign_gateway_marker *mmark : _get_malign_gateways())
{
if (duration)
mmark->duration -= duration;
if (mmark->duration > 0)
big_cloud(CLOUD_TLOC_ENERGY, 0, mmark->pos, 3+random2(10), 2+random2(5));
else
{
monster* mons = monster_at(mmark->pos);
if (mmark->monster_summoned && !mons)
{
// The marker hangs around until later.
if (env.grid(mmark->pos) == DNGN_MALIGN_GATEWAY)
env.grid(mmark->pos) = DNGN_FLOOR;
env.markers.remove(mmark);
}
else if (!mmark->monster_summoned && !mons)
{
bool is_player = mmark->is_player;
actor* caster = 0;
if (is_player)
caster = &you;
mgen_data mg = mgen_data(MONS_ELDRITCH_TENTACLE,
mmark->behaviour,
mmark->pos,
MHITNOT,
MG_FORCE_PLACE);
mg.set_summoned(caster, 0, 0, mmark->god);
if (!is_player)
mg.non_actor_summoner = mmark->summoner_string;
if (monster *tentacle = create_monster(mg))
{
tentacle->flags |= MF_NO_REWARD;
tentacle->add_ench(ENCH_PORTAL_TIMER);
mon_enchant kduration = mon_enchant(ENCH_PORTAL_PACIFIED, 4,
caster, (random2avg(mmark->power, 6)-random2(4))*10);
tentacle->props["base_position"].get_coord()
= tentacle->pos();
tentacle->add_ench(kduration);
mmark->monster_summoned = true;
}
}
}
}
}
void timeout_tombs(int duration)
{
if (!duration)
return;
for (map_marker *mark : env.markers.get_all(MAT_TOMB))
{
if (mark->get_type() != MAT_TOMB)
continue;
map_tomb_marker *cmark = dynamic_cast<map_tomb_marker*>(mark);
cmark->duration -= duration;
// Empty tombs disappear early.
monster* mon_entombed = monster_at(cmark->pos);
bool empty_tomb = !(mon_entombed || you.pos() == cmark->pos);
bool zin = (cmark->source == -GOD_ZIN);
if (cmark->duration <= 0 || empty_tomb)
{
_drop_tomb(cmark->pos, empty_tomb, zin);
monster* mon_src =
!invalid_monster_index(cmark->source) ? &menv[cmark->source]
: nullptr;
// A monster's Tomb of Doroklohe spell.
if (mon_src
&& mon_src == mon_entombed)
{
mon_src->lose_energy(EUT_SPELL);
}
env.markers.remove(cmark);
}
}
}
void timeout_terrain_changes(int duration, bool force)
{
if (!duration && !force)
return;
int num_seen[NUM_TERRAIN_CHANGE_TYPES] = {0};
for (map_marker *mark : env.markers.get_all(MAT_TERRAIN_CHANGE))
{
map_terrain_change_marker *marker =
dynamic_cast<map_terrain_change_marker*>(mark);
if (marker->duration != INFINITE_DURATION)
marker->duration -= duration;
if (marker->change_type == TERRAIN_CHANGE_DOOR_SEAL
&& !feat_is_sealed(grd(marker->pos)))
{
// TODO: could this be done inside `revert_terrain_change`? The
// two things to test are corrupting sealed doors, and destroying
// sealed doors. See 7aedcd24e1be3ed58fef9542786c1a194e4c07d0 and
// 6c286a4f22bcba4cfcb36053eb066367874be752.
if (marker->duration <= 0)
env.markers.remove(marker); // deletes `marker`
continue;
}
if (marker->change_type == TERRAIN_CHANGE_QUICKSAND
&& !you.see_cell(marker->pos))
{
marker->duration = 0;
}
monster* mon_src = monster_by_mid(marker->mon_num);
if (marker->duration <= 0
|| (marker->mon_num != 0
&& (!mon_src || !mon_src->alive() || mon_src->pacified())))
{
if (you.see_cell(marker->pos))
num_seen[marker->change_type]++;
// will delete `marker`.
revert_terrain_change(marker->pos, marker->change_type);
}
}
if (num_seen[TERRAIN_CHANGE_DOOR_SEAL] > 1)
mpr("The runic seals fade away.");
else if (num_seen[TERRAIN_CHANGE_DOOR_SEAL] > 0)
mpr("The runic seal fades away.");
}
////////////////////////////////////////////////////////////////////////////
// Living breathing dungeon stuff.
//
static vector<coord_def> sfx_seeds;
void setup_environment_effects()
{
sfx_seeds.clear();
for (int x = X_BOUND_1; x <= X_BOUND_2; ++x)
{
for (int y = Y_BOUND_1; y <= Y_BOUND_2; ++y)
{
if (!in_bounds(x, y))
continue;
const int grid = grd[x][y];
if (grid == DNGN_LAVA
|| (grid == DNGN_SHALLOW_WATER
&& player_in_branch(BRANCH_SWAMP)))
{
const coord_def c(x, y);
sfx_seeds.push_back(c);
}
}
}
dprf("%u environment effect seeds", (unsigned int)sfx_seeds.size());
}
static void apply_environment_effect(const coord_def &c)
{
const dungeon_feature_type grid = grd(c);
// Don't apply if if the feature doesn't want it.
if (testbits(env.pgrid(c), FPROP_NO_CLOUD_GEN))
return;
if (grid == DNGN_LAVA)
check_place_cloud(CLOUD_BLACK_SMOKE, c, random_range(4, 8), 0);
else if (one_chance_in(3) && grid == DNGN_SHALLOW_WATER)
check_place_cloud(CLOUD_MIST, c, random_range(2, 5), 0);
}
static const int Base_Sfx_Chance = 5;
void run_environment_effects()
{
if (!you.time_taken)
return;
dungeon_events.fire_event(DET_TURN_ELAPSED);
// Each square in sfx_seeds has this chance of doing something special
// per turn.
const int sfx_chance = Base_Sfx_Chance * you.time_taken / 10;
const int nseeds = sfx_seeds.size();
// If there are a large number of seeds, speed things up by fudging the
// numbers.
if (nseeds > 50)
{
int nsels = div_rand_round(sfx_seeds.size() * sfx_chance, 100);
if (one_chance_in(5))
nsels += random2(nsels * 3);
for (int i = 0; i < nsels; ++i)
apply_environment_effect(sfx_seeds[ random2(nseeds) ]);
}
else
{
for (int i = 0; i < nseeds; ++i)
{
if (random2(100) >= sfx_chance)
continue;
apply_environment_effect(sfx_seeds[i]);
}
}
run_corruption_effects(you.time_taken);
shoals_apply_tides(div_rand_round(you.time_taken, BASELINE_DELAY),
false, true);
timeout_tombs(you.time_taken);
timeout_malign_gateways(you.time_taken);
timeout_terrain_changes(you.time_taken);
run_cloud_spreaders(you.time_taken);
}
// Converts a movement speed to a duration. i.e., answers the
// question: if the monster is so fast, how much time has it spent in
// its last movement?
//
// If speed is 10 (normal), one movement is a duration of 10.
// If speed is 1 (very slow), each movement is a duration of 100.
// If speed is 15 (50% faster than normal), each movement is a duration of
// 6.6667.
int speed_to_duration(int speed)
{
if (speed < 1)
speed = 10;
else if (speed > 100)
speed = 100;
return div_rand_round(100, speed);
}
| 31.290216 | 90 | 0.560649 | [
"vector"
] |
33a69e8beb7c620d10cf5213742a8d41a0212a1a | 115,706 | cpp | C++ | lib/CodeGen/AsmPrinter/CodeViewDebug.cpp | AlexVlx/llvm | 08ba61dfeeac3e1eccff413870340197935e28bc | [
"Apache-2.0"
] | null | null | null | lib/CodeGen/AsmPrinter/CodeViewDebug.cpp | AlexVlx/llvm | 08ba61dfeeac3e1eccff413870340197935e28bc | [
"Apache-2.0"
] | null | null | null | lib/CodeGen/AsmPrinter/CodeViewDebug.cpp | AlexVlx/llvm | 08ba61dfeeac3e1eccff413870340197935e28bc | [
"Apache-2.0"
] | null | null | null | //===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing Microsoft CodeView debug info.
//
//===----------------------------------------------------------------------===//
#include "CodeViewDebug.h"
#include "DwarfExpression.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/CodeGen/AsmPrinter.h"
#include "llvm/CodeGen/LexicalScopes.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/TargetFrameLowering.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
#include "llvm/DebugInfo/CodeView/CodeView.h"
#include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h"
#include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h"
#include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h"
#include "llvm/DebugInfo/CodeView/EnumTables.h"
#include "llvm/DebugInfo/CodeView/Line.h"
#include "llvm/DebugInfo/CodeView/SymbolRecord.h"
#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
#include "llvm/DebugInfo/CodeView/TypeIndex.h"
#include "llvm/DebugInfo/CodeView/TypeRecord.h"
#include "llvm/DebugInfo/CodeView/TypeTableCollection.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/BinaryByteStream.h"
#include "llvm/Support/BinaryStreamReader.h"
#include "llvm/Support/BinaryStreamWriter.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/ScopedPrinter.h"
#include "llvm/Target/TargetLoweringObjectFile.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <limits>
#include <string>
#include <utility>
#include <vector>
using namespace llvm;
using namespace llvm::codeview;
static CPUType mapArchToCVCPUType(Triple::ArchType Type) {
switch (Type) {
case Triple::ArchType::x86:
return CPUType::Pentium3;
case Triple::ArchType::x86_64:
return CPUType::X64;
case Triple::ArchType::thumb:
return CPUType::Thumb;
case Triple::ArchType::aarch64:
return CPUType::ARM64;
default:
report_fatal_error("target architecture doesn't map to a CodeView CPUType");
}
}
CodeViewDebug::CodeViewDebug(AsmPrinter *AP)
: DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) {
// If module doesn't have named metadata anchors or COFF debug section
// is not available, skip any debug info related stuff.
if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") ||
!AP->getObjFileLowering().getCOFFDebugSymbolsSection()) {
Asm = nullptr;
MMI->setDebugInfoAvailability(false);
return;
}
// Tell MMI that we have debug info.
MMI->setDebugInfoAvailability(true);
TheCPU =
mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch());
collectGlobalVariableInfo();
// Check if we should emit type record hashes.
ConstantInt *GH = mdconst::extract_or_null<ConstantInt>(
MMI->getModule()->getModuleFlag("CodeViewGHash"));
EmitDebugGlobalHashes = GH && !GH->isZero();
}
StringRef CodeViewDebug::getFullFilepath(const DIFile *File) {
std::string &Filepath = FileToFilepathMap[File];
if (!Filepath.empty())
return Filepath;
StringRef Dir = File->getDirectory(), Filename = File->getFilename();
// If this is a Unix-style path, just use it as is. Don't try to canonicalize
// it textually because one of the path components could be a symlink.
if (Dir.startswith("/") || Filename.startswith("/")) {
if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix))
return Filename;
Filepath = Dir;
if (Dir.back() != '/')
Filepath += '/';
Filepath += Filename;
return Filepath;
}
// Clang emits directory and relative filename info into the IR, but CodeView
// operates on full paths. We could change Clang to emit full paths too, but
// that would increase the IR size and probably not needed for other users.
// For now, just concatenate and canonicalize the path here.
if (Filename.find(':') == 1)
Filepath = Filename;
else
Filepath = (Dir + "\\" + Filename).str();
// Canonicalize the path. We have to do it textually because we may no longer
// have access the file in the filesystem.
// First, replace all slashes with backslashes.
std::replace(Filepath.begin(), Filepath.end(), '/', '\\');
// Remove all "\.\" with "\".
size_t Cursor = 0;
while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos)
Filepath.erase(Cursor, 2);
// Replace all "\XXX\..\" with "\". Don't try too hard though as the original
// path should be well-formatted, e.g. start with a drive letter, etc.
Cursor = 0;
while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) {
// Something's wrong if the path starts with "\..\", abort.
if (Cursor == 0)
break;
size_t PrevSlash = Filepath.rfind('\\', Cursor - 1);
if (PrevSlash == std::string::npos)
// Something's wrong, abort.
break;
Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash);
// The next ".." might be following the one we've just erased.
Cursor = PrevSlash;
}
// Remove all duplicate backslashes.
Cursor = 0;
while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos)
Filepath.erase(Cursor, 1);
return Filepath;
}
unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) {
StringRef FullPath = getFullFilepath(F);
unsigned NextId = FileIdMap.size() + 1;
auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId));
if (Insertion.second) {
// We have to compute the full filepath and emit a .cv_file directive.
ArrayRef<uint8_t> ChecksumAsBytes;
FileChecksumKind CSKind = FileChecksumKind::None;
if (F->getChecksum()) {
std::string Checksum = fromHex(F->getChecksum()->Value);
void *CKMem = OS.getContext().allocate(Checksum.size(), 1);
memcpy(CKMem, Checksum.data(), Checksum.size());
ChecksumAsBytes = ArrayRef<uint8_t>(
reinterpret_cast<const uint8_t *>(CKMem), Checksum.size());
switch (F->getChecksum()->Kind) {
case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break;
case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break;
}
}
bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes,
static_cast<unsigned>(CSKind));
(void)Success;
assert(Success && ".cv_file directive failed");
}
return Insertion.first->second;
}
CodeViewDebug::InlineSite &
CodeViewDebug::getInlineSite(const DILocation *InlinedAt,
const DISubprogram *Inlinee) {
auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()});
InlineSite *Site = &SiteInsertion.first->second;
if (SiteInsertion.second) {
unsigned ParentFuncId = CurFn->FuncId;
if (const DILocation *OuterIA = InlinedAt->getInlinedAt())
ParentFuncId =
getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram())
.SiteFuncId;
Site->SiteFuncId = NextFuncId++;
OS.EmitCVInlineSiteIdDirective(
Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()),
InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc());
Site->Inlinee = Inlinee;
InlinedSubprograms.insert(Inlinee);
getFuncIdForSubprogram(Inlinee);
}
return *Site;
}
static StringRef getPrettyScopeName(const DIScope *Scope) {
StringRef ScopeName = Scope->getName();
if (!ScopeName.empty())
return ScopeName;
switch (Scope->getTag()) {
case dwarf::DW_TAG_enumeration_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
return "<unnamed-tag>";
case dwarf::DW_TAG_namespace:
return "`anonymous namespace'";
}
return StringRef();
}
static const DISubprogram *getQualifiedNameComponents(
const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) {
const DISubprogram *ClosestSubprogram = nullptr;
while (Scope != nullptr) {
if (ClosestSubprogram == nullptr)
ClosestSubprogram = dyn_cast<DISubprogram>(Scope);
StringRef ScopeName = getPrettyScopeName(Scope);
if (!ScopeName.empty())
QualifiedNameComponents.push_back(ScopeName);
Scope = Scope->getScope();
}
return ClosestSubprogram;
}
static std::string getQualifiedName(ArrayRef<StringRef> QualifiedNameComponents,
StringRef TypeName) {
std::string FullyQualifiedName;
for (StringRef QualifiedNameComponent :
llvm::reverse(QualifiedNameComponents)) {
FullyQualifiedName.append(QualifiedNameComponent);
FullyQualifiedName.append("::");
}
FullyQualifiedName.append(TypeName);
return FullyQualifiedName;
}
static std::string getFullyQualifiedName(const DIScope *Scope, StringRef Name) {
SmallVector<StringRef, 5> QualifiedNameComponents;
getQualifiedNameComponents(Scope, QualifiedNameComponents);
return getQualifiedName(QualifiedNameComponents, Name);
}
struct CodeViewDebug::TypeLoweringScope {
TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; }
~TypeLoweringScope() {
// Don't decrement TypeEmissionLevel until after emitting deferred types, so
// inner TypeLoweringScopes don't attempt to emit deferred types.
if (CVD.TypeEmissionLevel == 1)
CVD.emitDeferredCompleteTypes();
--CVD.TypeEmissionLevel;
}
CodeViewDebug &CVD;
};
static std::string getFullyQualifiedName(const DIScope *Ty) {
const DIScope *Scope = Ty->getScope();
return getFullyQualifiedName(Scope, getPrettyScopeName(Ty));
}
TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) {
// No scope means global scope and that uses the zero index.
if (!Scope || isa<DIFile>(Scope))
return TypeIndex();
assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type");
// Check if we've already translated this scope.
auto I = TypeIndices.find({Scope, nullptr});
if (I != TypeIndices.end())
return I->second;
// Build the fully qualified name of the scope.
std::string ScopeName = getFullyQualifiedName(Scope);
StringIdRecord SID(TypeIndex(), ScopeName);
auto TI = TypeTable.writeLeafType(SID);
return recordTypeIndexForDINode(Scope, TI);
}
TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) {
assert(SP);
// Check if we've already translated this subprogram.
auto I = TypeIndices.find({SP, nullptr});
if (I != TypeIndices.end())
return I->second;
// The display name includes function template arguments. Drop them to match
// MSVC.
StringRef DisplayName = SP->getName().split('<').first;
const DIScope *Scope = SP->getScope();
TypeIndex TI;
if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) {
// If the scope is a DICompositeType, then this must be a method. Member
// function types take some special handling, and require access to the
// subprogram.
TypeIndex ClassType = getTypeIndex(Class);
MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class),
DisplayName);
TI = TypeTable.writeLeafType(MFuncId);
} else {
// Otherwise, this must be a free function.
TypeIndex ParentScope = getScopeIndex(Scope);
FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName);
TI = TypeTable.writeLeafType(FuncId);
}
return recordTypeIndexForDINode(SP, TI);
}
static bool isNonTrivial(const DICompositeType *DCTy) {
return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial);
}
static FunctionOptions
getFunctionOptions(const DISubroutineType *Ty,
const DICompositeType *ClassTy = nullptr,
StringRef SPName = StringRef("")) {
FunctionOptions FO = FunctionOptions::None;
const DIType *ReturnTy = nullptr;
if (auto TypeArray = Ty->getTypeArray()) {
if (TypeArray.size())
ReturnTy = TypeArray[0];
}
if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) {
if (isNonTrivial(ReturnDCTy))
FO |= FunctionOptions::CxxReturnUdt;
}
// DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison.
if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) {
FO |= FunctionOptions::Constructor;
// TODO: put the FunctionOptions::ConstructorWithVirtualBases flag.
}
return FO;
}
TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP,
const DICompositeType *Class) {
// Always use the method declaration as the key for the function type. The
// method declaration contains the this adjustment.
if (SP->getDeclaration())
SP = SP->getDeclaration();
assert(!SP->getDeclaration() && "should use declaration as key");
// Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide
// with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}.
auto I = TypeIndices.find({SP, Class});
if (I != TypeIndices.end())
return I->second;
// Make sure complete type info for the class is emitted *after* the member
// function type, as the complete class type is likely to reference this
// member function type.
TypeLoweringScope S(*this);
const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0;
FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName());
TypeIndex TI = lowerTypeMemberFunction(
SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO);
return recordTypeIndexForDINode(SP, TI, Class);
}
TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node,
TypeIndex TI,
const DIType *ClassTy) {
auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI});
(void)InsertResult;
assert(InsertResult.second && "DINode was already assigned a type index");
return TI;
}
unsigned CodeViewDebug::getPointerSizeInBytes() {
return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8;
}
void CodeViewDebug::recordLocalVariable(LocalVariable &&Var,
const LexicalScope *LS) {
if (const DILocation *InlinedAt = LS->getInlinedAt()) {
// This variable was inlined. Associate it with the InlineSite.
const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram();
InlineSite &Site = getInlineSite(InlinedAt, Inlinee);
Site.InlinedLocals.emplace_back(Var);
} else {
// This variable goes into the corresponding lexical scope.
ScopeVariables[LS].emplace_back(Var);
}
}
static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs,
const DILocation *Loc) {
auto B = Locs.begin(), E = Locs.end();
if (std::find(B, E, Loc) == E)
Locs.push_back(Loc);
}
void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL,
const MachineFunction *MF) {
// Skip this instruction if it has the same location as the previous one.
if (!DL || DL == PrevInstLoc)
return;
const DIScope *Scope = DL.get()->getScope();
if (!Scope)
return;
// Skip this line if it is longer than the maximum we can record.
LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true);
if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() ||
LI.isNeverStepInto())
return;
ColumnInfo CI(DL.getCol(), /*EndColumn=*/0);
if (CI.getStartColumn() != DL.getCol())
return;
if (!CurFn->HaveLineInfo)
CurFn->HaveLineInfo = true;
unsigned FileId = 0;
if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile())
FileId = CurFn->LastFileId;
else
FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile());
PrevInstLoc = DL;
unsigned FuncId = CurFn->FuncId;
if (const DILocation *SiteLoc = DL->getInlinedAt()) {
const DILocation *Loc = DL.get();
// If this location was actually inlined from somewhere else, give it the ID
// of the inline call site.
FuncId =
getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId;
// Ensure we have links in the tree of inline call sites.
bool FirstLoc = true;
while ((SiteLoc = Loc->getInlinedAt())) {
InlineSite &Site =
getInlineSite(SiteLoc, Loc->getScope()->getSubprogram());
if (!FirstLoc)
addLocIfNotPresent(Site.ChildSites, Loc);
FirstLoc = false;
Loc = SiteLoc;
}
addLocIfNotPresent(CurFn->ChildSites, Loc);
}
OS.EmitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(),
/*PrologueEnd=*/false, /*IsStmt=*/false,
DL->getFilename(), SMLoc());
}
void CodeViewDebug::emitCodeViewMagicVersion() {
OS.EmitValueToAlignment(4);
OS.AddComment("Debug section magic");
OS.EmitIntValue(COFF::DEBUG_SECTION_MAGIC, 4);
}
void CodeViewDebug::endModule() {
if (!Asm || !MMI->hasDebugInfo())
return;
assert(Asm != nullptr);
// The COFF .debug$S section consists of several subsections, each starting
// with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length
// of the payload followed by the payload itself. The subsections are 4-byte
// aligned.
// Use the generic .debug$S section, and make a subsection for all the inlined
// subprograms.
switchToDebugSectionForSymbol(nullptr);
MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols);
emitCompilerInformation();
endCVSubsection(CompilerInfo);
emitInlineeLinesSubsection();
// Emit per-function debug information.
for (auto &P : FnDebugInfo)
if (!P.first->isDeclarationForLinker())
emitDebugInfoForFunction(P.first, *P.second);
// Emit global variable debug information.
setCurrentSubprogram(nullptr);
emitDebugInfoForGlobals();
// Emit retained types.
emitDebugInfoForRetainedTypes();
// Switch back to the generic .debug$S section after potentially processing
// comdat symbol sections.
switchToDebugSectionForSymbol(nullptr);
// Emit UDT records for any types used by global variables.
if (!GlobalUDTs.empty()) {
MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
emitDebugInfoForUDTs(GlobalUDTs);
endCVSubsection(SymbolsEnd);
}
// This subsection holds a file index to offset in string table table.
OS.AddComment("File index to string table offset subsection");
OS.EmitCVFileChecksumsDirective();
// This subsection holds the string table.
OS.AddComment("String table");
OS.EmitCVStringTableDirective();
// Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol
// subsection in the generic .debug$S section at the end. There is no
// particular reason for this ordering other than to match MSVC.
emitBuildInfo();
// Emit type information and hashes last, so that any types we translate while
// emitting function info are included.
emitTypeInformation();
if (EmitDebugGlobalHashes)
emitTypeGlobalHashes();
clear();
}
static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S,
unsigned MaxFixedRecordLength = 0xF00) {
// The maximum CV record length is 0xFF00. Most of the strings we emit appear
// after a fixed length portion of the record. The fixed length portion should
// always be less than 0xF00 (3840) bytes, so truncate the string so that the
// overall record size is less than the maximum allowed.
SmallString<32> NullTerminatedString(
S.take_front(MaxRecordLength - MaxFixedRecordLength - 1));
NullTerminatedString.push_back('\0');
OS.EmitBytes(NullTerminatedString);
}
void CodeViewDebug::emitTypeInformation() {
if (TypeTable.empty())
return;
// Start the .debug$T or .debug$P section with 0x4.
OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection());
emitCodeViewMagicVersion();
SmallString<8> CommentPrefix;
if (OS.isVerboseAsm()) {
CommentPrefix += '\t';
CommentPrefix += Asm->MAI->getCommentString();
CommentPrefix += ' ';
}
TypeTableCollection Table(TypeTable.records());
Optional<TypeIndex> B = Table.getFirst();
while (B) {
// This will fail if the record data is invalid.
CVType Record = Table.getType(*B);
if (OS.isVerboseAsm()) {
// Emit a block comment describing the type record for readability.
SmallString<512> CommentBlock;
raw_svector_ostream CommentOS(CommentBlock);
ScopedPrinter SP(CommentOS);
SP.setPrefix(CommentPrefix);
TypeDumpVisitor TDV(Table, &SP, false);
Error E = codeview::visitTypeRecord(Record, *B, TDV);
if (E) {
logAllUnhandledErrors(std::move(E), errs(), "error: ");
llvm_unreachable("produced malformed type record");
}
// emitRawComment will insert its own tab and comment string before
// the first line, so strip off our first one. It also prints its own
// newline.
OS.emitRawComment(
CommentOS.str().drop_front(CommentPrefix.size() - 1).rtrim());
}
OS.EmitBinaryData(Record.str_data());
B = Table.getNext(*B);
}
}
void CodeViewDebug::emitTypeGlobalHashes() {
if (TypeTable.empty())
return;
// Start the .debug$H section with the version and hash algorithm, currently
// hardcoded to version 0, SHA1.
OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection());
OS.EmitValueToAlignment(4);
OS.AddComment("Magic");
OS.EmitIntValue(COFF::DEBUG_HASHES_SECTION_MAGIC, 4);
OS.AddComment("Section Version");
OS.EmitIntValue(0, 2);
OS.AddComment("Hash Algorithm");
OS.EmitIntValue(uint16_t(GlobalTypeHashAlg::SHA1_8), 2);
TypeIndex TI(TypeIndex::FirstNonSimpleIndex);
for (const auto &GHR : TypeTable.hashes()) {
if (OS.isVerboseAsm()) {
// Emit an EOL-comment describing which TypeIndex this hash corresponds
// to, as well as the stringified SHA1 hash.
SmallString<32> Comment;
raw_svector_ostream CommentOS(Comment);
CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR);
OS.AddComment(Comment);
++TI;
}
assert(GHR.Hash.size() == 8);
StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()),
GHR.Hash.size());
OS.EmitBinaryData(S);
}
}
static SourceLanguage MapDWLangToCVLang(unsigned DWLang) {
switch (DWLang) {
case dwarf::DW_LANG_C:
case dwarf::DW_LANG_C89:
case dwarf::DW_LANG_C99:
case dwarf::DW_LANG_C11:
case dwarf::DW_LANG_ObjC:
return SourceLanguage::C;
case dwarf::DW_LANG_C_plus_plus:
case dwarf::DW_LANG_C_plus_plus_03:
case dwarf::DW_LANG_C_plus_plus_11:
case dwarf::DW_LANG_C_plus_plus_14:
return SourceLanguage::Cpp;
case dwarf::DW_LANG_Fortran77:
case dwarf::DW_LANG_Fortran90:
case dwarf::DW_LANG_Fortran03:
case dwarf::DW_LANG_Fortran08:
return SourceLanguage::Fortran;
case dwarf::DW_LANG_Pascal83:
return SourceLanguage::Pascal;
case dwarf::DW_LANG_Cobol74:
case dwarf::DW_LANG_Cobol85:
return SourceLanguage::Cobol;
case dwarf::DW_LANG_Java:
return SourceLanguage::Java;
case dwarf::DW_LANG_D:
return SourceLanguage::D;
case dwarf::DW_LANG_Swift:
return SourceLanguage::Swift;
default:
// There's no CodeView representation for this language, and CV doesn't
// have an "unknown" option for the language field, so we'll use MASM,
// as it's very low level.
return SourceLanguage::Masm;
}
}
namespace {
struct Version {
int Part[4];
};
} // end anonymous namespace
// Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out
// the version number.
static Version parseVersion(StringRef Name) {
Version V = {{0}};
int N = 0;
for (const char C : Name) {
if (isdigit(C)) {
V.Part[N] *= 10;
V.Part[N] += C - '0';
} else if (C == '.') {
++N;
if (N >= 4)
return V;
} else if (N > 0)
return V;
}
return V;
}
void CodeViewDebug::emitCompilerInformation() {
MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3);
uint32_t Flags = 0;
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
const MDNode *Node = *CUs->operands().begin();
const auto *CU = cast<DICompileUnit>(Node);
// The low byte of the flags indicates the source language.
Flags = MapDWLangToCVLang(CU->getSourceLanguage());
// TODO: Figure out which other flags need to be set.
OS.AddComment("Flags and language");
OS.EmitIntValue(Flags, 4);
OS.AddComment("CPUType");
OS.EmitIntValue(static_cast<uint64_t>(TheCPU), 2);
StringRef CompilerVersion = CU->getProducer();
Version FrontVer = parseVersion(CompilerVersion);
OS.AddComment("Frontend version");
for (int N = 0; N < 4; ++N)
OS.EmitIntValue(FrontVer.Part[N], 2);
// Some Microsoft tools, like Binscope, expect a backend version number of at
// least 8.something, so we'll coerce the LLVM version into a form that
// guarantees it'll be big enough without really lying about the version.
int Major = 1000 * LLVM_VERSION_MAJOR +
10 * LLVM_VERSION_MINOR +
LLVM_VERSION_PATCH;
// Clamp it for builds that use unusually large version numbers.
Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max());
Version BackVer = {{ Major, 0, 0, 0 }};
OS.AddComment("Backend version");
for (int N = 0; N < 4; ++N)
OS.EmitIntValue(BackVer.Part[N], 2);
OS.AddComment("Null-terminated compiler version string");
emitNullTerminatedSymbolName(OS, CompilerVersion);
endSymbolRecord(CompilerEnd);
}
static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable,
StringRef S) {
StringIdRecord SIR(TypeIndex(0x0), S);
return TypeTable.writeLeafType(SIR);
}
void CodeViewDebug::emitBuildInfo() {
// First, make LF_BUILDINFO. It's a sequence of strings with various bits of
// build info. The known prefix is:
// - Absolute path of current directory
// - Compiler path
// - Main source file path, relative to CWD or absolute
// - Type server PDB file
// - Canonical compiler command line
// If frontend and backend compilation are separated (think llc or LTO), it's
// not clear if the compiler path should refer to the executable for the
// frontend or the backend. Leave it blank for now.
TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {};
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs.
const auto *CU = cast<DICompileUnit>(Node);
const DIFile *MainSourceFile = CU->getFile();
BuildInfoArgs[BuildInfoRecord::CurrentDirectory] =
getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory());
BuildInfoArgs[BuildInfoRecord::SourceFile] =
getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename());
// FIXME: Path to compiler and command line. PDB is intentionally blank unless
// we implement /Zi type servers.
BuildInfoRecord BIR(BuildInfoArgs);
TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR);
// Make a new .debug$S subsection for the S_BUILDINFO record, which points
// from the module symbols into the type stream.
MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO);
OS.AddComment("LF_BUILDINFO index");
OS.EmitIntValue(BuildInfoIndex.getIndex(), 4);
endSymbolRecord(BIEnd);
endCVSubsection(BISubsecEnd);
}
void CodeViewDebug::emitInlineeLinesSubsection() {
if (InlinedSubprograms.empty())
return;
OS.AddComment("Inlinee lines subsection");
MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines);
// We emit the checksum info for files. This is used by debuggers to
// determine if a pdb matches the source before loading it. Visual Studio,
// for instance, will display a warning that the breakpoints are not valid if
// the pdb does not match the source.
OS.AddComment("Inlinee lines signature");
OS.EmitIntValue(unsigned(InlineeLinesSignature::Normal), 4);
for (const DISubprogram *SP : InlinedSubprograms) {
assert(TypeIndices.count({SP, nullptr}));
TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}];
OS.AddBlankLine();
unsigned FileId = maybeRecordFile(SP->getFile());
OS.AddComment("Inlined function " + SP->getName() + " starts at " +
SP->getFilename() + Twine(':') + Twine(SP->getLine()));
OS.AddBlankLine();
OS.AddComment("Type index of inlined function");
OS.EmitIntValue(InlineeIdx.getIndex(), 4);
OS.AddComment("Offset into filechecksum table");
OS.EmitCVFileChecksumOffsetDirective(FileId);
OS.AddComment("Starting line number");
OS.EmitIntValue(SP->getLine(), 4);
}
endCVSubsection(InlineEnd);
}
void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI,
const DILocation *InlinedAt,
const InlineSite &Site) {
assert(TypeIndices.count({Site.Inlinee, nullptr}));
TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}];
// SymbolRecord
MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE);
OS.AddComment("PtrParent");
OS.EmitIntValue(0, 4);
OS.AddComment("PtrEnd");
OS.EmitIntValue(0, 4);
OS.AddComment("Inlinee type index");
OS.EmitIntValue(InlineeIdx.getIndex(), 4);
unsigned FileId = maybeRecordFile(Site.Inlinee->getFile());
unsigned StartLineNum = Site.Inlinee->getLine();
OS.EmitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum,
FI.Begin, FI.End);
endSymbolRecord(InlineEnd);
emitLocalVariableList(FI, Site.InlinedLocals);
// Recurse on child inlined call sites before closing the scope.
for (const DILocation *ChildSite : Site.ChildSites) {
auto I = FI.InlineSites.find(ChildSite);
assert(I != FI.InlineSites.end() &&
"child site not in function inline site map");
emitInlinedCallSite(FI, ChildSite, I->second);
}
// Close the scope.
emitEndSymbolRecord(SymbolKind::S_INLINESITE_END);
}
void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) {
// If we have a symbol, it may be in a section that is COMDAT. If so, find the
// comdat key. A section may be comdat because of -ffunction-sections or
// because it is comdat in the IR.
MCSectionCOFF *GVSec =
GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr;
const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr;
MCSectionCOFF *DebugSec = cast<MCSectionCOFF>(
Asm->getObjFileLowering().getCOFFDebugSymbolsSection());
DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym);
OS.SwitchSection(DebugSec);
// Emit the magic version number if this is the first time we've switched to
// this section.
if (ComdatDebugSections.insert(DebugSec).second)
emitCodeViewMagicVersion();
}
// Emit an S_THUNK32/S_END symbol pair for a thunk routine.
// The only supported thunk ordinal is currently the standard type.
void CodeViewDebug::emitDebugInfoForThunk(const Function *GV,
FunctionInfo &FI,
const MCSymbol *Fn) {
std::string FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind.
OS.AddComment("Symbol subsection for " + Twine(FuncName));
MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
// Emit S_THUNK32
MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32);
OS.AddComment("PtrParent");
OS.EmitIntValue(0, 4);
OS.AddComment("PtrEnd");
OS.EmitIntValue(0, 4);
OS.AddComment("PtrNext");
OS.EmitIntValue(0, 4);
OS.AddComment("Thunk section relative address");
OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
OS.AddComment("Thunk section index");
OS.EmitCOFFSectionIndex(Fn);
OS.AddComment("Code size");
OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2);
OS.AddComment("Ordinal");
OS.EmitIntValue(unsigned(ordinal), 1);
OS.AddComment("Function name");
emitNullTerminatedSymbolName(OS, FuncName);
// Additional fields specific to the thunk ordinal would go here.
endSymbolRecord(ThunkRecordEnd);
// Local variables/inlined routines are purposely omitted here. The point of
// marking this as a thunk is so Visual Studio will NOT stop in this routine.
// Emit S_PROC_ID_END
emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
endCVSubsection(SymbolsEnd);
}
void CodeViewDebug::emitDebugInfoForFunction(const Function *GV,
FunctionInfo &FI) {
// For each function there is a separate subsection which holds the PC to
// file:line table.
const MCSymbol *Fn = Asm->getSymbol(GV);
assert(Fn);
// Switch to the to a comdat section, if appropriate.
switchToDebugSectionForSymbol(Fn);
std::string FuncName;
auto *SP = GV->getSubprogram();
assert(SP);
setCurrentSubprogram(SP);
if (SP->isThunk()) {
emitDebugInfoForThunk(GV, FI, Fn);
return;
}
// If we have a display name, build the fully qualified name by walking the
// chain of scopes.
if (!SP->getName().empty())
FuncName = getFullyQualifiedName(SP->getScope(), SP->getName());
// If our DISubprogram name is empty, use the mangled name.
if (FuncName.empty())
FuncName = GlobalValue::dropLLVMManglingEscape(GV->getName());
// Emit FPO data, but only on 32-bit x86. No other platforms use it.
if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86)
OS.EmitCVFPOData(Fn);
// Emit a symbol subsection, required by VS2012+ to find function boundaries.
OS.AddComment("Symbol subsection for " + Twine(FuncName));
MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols);
{
SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID
: SymbolKind::S_GPROC32_ID;
MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind);
// These fields are filled in by tools like CVPACK which run after the fact.
OS.AddComment("PtrParent");
OS.EmitIntValue(0, 4);
OS.AddComment("PtrEnd");
OS.EmitIntValue(0, 4);
OS.AddComment("PtrNext");
OS.EmitIntValue(0, 4);
// This is the important bit that tells the debugger where the function
// code is located and what's its size:
OS.AddComment("Code size");
OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4);
OS.AddComment("Offset after prologue");
OS.EmitIntValue(0, 4);
OS.AddComment("Offset before epilogue");
OS.EmitIntValue(0, 4);
OS.AddComment("Function type index");
OS.EmitIntValue(getFuncIdForSubprogram(GV->getSubprogram()).getIndex(), 4);
OS.AddComment("Function section relative address");
OS.EmitCOFFSecRel32(Fn, /*Offset=*/0);
OS.AddComment("Function section index");
OS.EmitCOFFSectionIndex(Fn);
OS.AddComment("Flags");
OS.EmitIntValue(0, 1);
// Emit the function display name as a null-terminated string.
OS.AddComment("Function name");
// Truncate the name so we won't overflow the record length field.
emitNullTerminatedSymbolName(OS, FuncName);
endSymbolRecord(ProcRecordEnd);
MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC);
// Subtract out the CSR size since MSVC excludes that and we include it.
OS.AddComment("FrameSize");
OS.EmitIntValue(FI.FrameSize - FI.CSRSize, 4);
OS.AddComment("Padding");
OS.EmitIntValue(0, 4);
OS.AddComment("Offset of padding");
OS.EmitIntValue(0, 4);
OS.AddComment("Bytes of callee saved registers");
OS.EmitIntValue(FI.CSRSize, 4);
OS.AddComment("Exception handler offset");
OS.EmitIntValue(0, 4);
OS.AddComment("Exception handler section");
OS.EmitIntValue(0, 2);
OS.AddComment("Flags (defines frame register)");
OS.EmitIntValue(uint32_t(FI.FrameProcOpts), 4);
endSymbolRecord(FrameProcEnd);
emitLocalVariableList(FI, FI.Locals);
emitGlobalVariableList(FI.Globals);
emitLexicalBlockList(FI.ChildBlocks, FI);
// Emit inlined call site information. Only emit functions inlined directly
// into the parent function. We'll emit the other sites recursively as part
// of their parent inline site.
for (const DILocation *InlinedAt : FI.ChildSites) {
auto I = FI.InlineSites.find(InlinedAt);
assert(I != FI.InlineSites.end() &&
"child site not in function inline site map");
emitInlinedCallSite(FI, InlinedAt, I->second);
}
for (auto Annot : FI.Annotations) {
MCSymbol *Label = Annot.first;
MDTuple *Strs = cast<MDTuple>(Annot.second);
MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION);
OS.EmitCOFFSecRel32(Label, /*Offset=*/0);
// FIXME: Make sure we don't overflow the max record size.
OS.EmitCOFFSectionIndex(Label);
OS.EmitIntValue(Strs->getNumOperands(), 2);
for (Metadata *MD : Strs->operands()) {
// MDStrings are null terminated, so we can do EmitBytes and get the
// nice .asciz directive.
StringRef Str = cast<MDString>(MD)->getString();
assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString");
OS.EmitBytes(StringRef(Str.data(), Str.size() + 1));
}
endSymbolRecord(AnnotEnd);
}
for (auto HeapAllocSite : FI.HeapAllocSites) {
MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
// The labels might not be defined if the instruction was replaced
// somewhere in the codegen pipeline.
if (!BeginLabel->isDefined() || !EndLabel->isDefined())
continue;
DIType *DITy = std::get<2>(HeapAllocSite);
MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
OS.AddComment("Call site offset");
OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
OS.AddComment("Call site section index");
OS.EmitCOFFSectionIndex(BeginLabel);
OS.AddComment("Call instruction length");
OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
OS.AddComment("Type index");
OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
endSymbolRecord(HeapAllocEnd);
}
if (SP != nullptr)
emitDebugInfoForUDTs(LocalUDTs);
// We're done with this function.
emitEndSymbolRecord(SymbolKind::S_PROC_ID_END);
}
endCVSubsection(SymbolsEnd);
// We have an assembler directive that takes care of the whole line table.
OS.EmitCVLinetableDirective(FI.FuncId, Fn, FI.End);
}
CodeViewDebug::LocalVarDefRange
CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) {
LocalVarDefRange DR;
DR.InMemory = -1;
DR.DataOffset = Offset;
assert(DR.DataOffset == Offset && "truncation");
DR.IsSubfield = 0;
DR.StructOffset = 0;
DR.CVRegister = CVRegister;
return DR;
}
void CodeViewDebug::collectVariableInfoFromMFTable(
DenseSet<InlinedEntity> &Processed) {
const MachineFunction &MF = *Asm->MF;
const TargetSubtargetInfo &TSI = MF.getSubtarget();
const TargetFrameLowering *TFI = TSI.getFrameLowering();
const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) {
if (!VI.Var)
continue;
assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
"Expected inlined-at fields to agree");
Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt()));
LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
// If variable scope is not found then skip this variable.
if (!Scope)
continue;
// If the variable has an attached offset expression, extract it.
// FIXME: Try to handle DW_OP_deref as well.
int64_t ExprOffset = 0;
if (VI.Expr)
if (!VI.Expr->extractIfOffset(ExprOffset))
continue;
// Get the frame register used and the offset.
unsigned FrameReg = 0;
int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg);
uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg);
// Calculate the label ranges.
LocalVarDefRange DefRange =
createDefRangeMem(CVReg, FrameOffset + ExprOffset);
for (const InsnRange &Range : Scope->getRanges()) {
const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
const MCSymbol *End = getLabelAfterInsn(Range.second);
End = End ? End : Asm->getFunctionEnd();
DefRange.Ranges.emplace_back(Begin, End);
}
LocalVariable Var;
Var.DIVar = VI.Var;
Var.DefRanges.emplace_back(std::move(DefRange));
recordLocalVariable(std::move(Var), Scope);
}
}
static bool canUseReferenceType(const DbgVariableLocation &Loc) {
return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0;
}
static bool needsReferenceType(const DbgVariableLocation &Loc) {
return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0;
}
void CodeViewDebug::calculateRanges(
LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) {
const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo();
// Calculate the definition ranges.
for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) {
const auto &Entry = *I;
if (!Entry.isDbgValue())
continue;
const MachineInstr *DVInst = Entry.getInstr();
assert(DVInst->isDebugValue() && "Invalid History entry");
// FIXME: Find a way to represent constant variables, since they are
// relatively common.
Optional<DbgVariableLocation> Location =
DbgVariableLocation::extractFromMachineInstruction(*DVInst);
if (!Location)
continue;
// CodeView can only express variables in register and variables in memory
// at a constant offset from a register. However, for variables passed
// indirectly by pointer, it is common for that pointer to be spilled to a
// stack location. For the special case of one offseted load followed by a
// zero offset load (a pointer spilled to the stack), we change the type of
// the local variable from a value type to a reference type. This tricks the
// debugger into doing the load for us.
if (Var.UseReferenceType) {
// We're using a reference type. Drop the last zero offset load.
if (canUseReferenceType(*Location))
Location->LoadChain.pop_back();
else
continue;
} else if (needsReferenceType(*Location)) {
// This location can't be expressed without switching to a reference type.
// Start over using that.
Var.UseReferenceType = true;
Var.DefRanges.clear();
calculateRanges(Var, Entries);
return;
}
// We can only handle a register or an offseted load of a register.
if (Location->Register == 0 || Location->LoadChain.size() > 1)
continue;
{
LocalVarDefRange DR;
DR.CVRegister = TRI->getCodeViewRegNum(Location->Register);
DR.InMemory = !Location->LoadChain.empty();
DR.DataOffset =
!Location->LoadChain.empty() ? Location->LoadChain.back() : 0;
if (Location->FragmentInfo) {
DR.IsSubfield = true;
DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8;
} else {
DR.IsSubfield = false;
DR.StructOffset = 0;
}
if (Var.DefRanges.empty() ||
Var.DefRanges.back().isDifferentLocation(DR)) {
Var.DefRanges.emplace_back(std::move(DR));
}
}
// Compute the label range.
const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr());
const MCSymbol *End;
if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) {
auto &EndingEntry = Entries[Entry.getEndIndex()];
End = EndingEntry.isDbgValue()
? getLabelBeforeInsn(EndingEntry.getInstr())
: getLabelAfterInsn(EndingEntry.getInstr());
} else
End = Asm->getFunctionEnd();
// If the last range end is our begin, just extend the last range.
// Otherwise make a new range.
SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R =
Var.DefRanges.back().Ranges;
if (!R.empty() && R.back().second == Begin)
R.back().second = End;
else
R.emplace_back(Begin, End);
// FIXME: Do more range combining.
}
}
void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) {
DenseSet<InlinedEntity> Processed;
// Grab the variable info that was squirreled away in the MMI side-table.
collectVariableInfoFromMFTable(Processed);
for (const auto &I : DbgValues) {
InlinedEntity IV = I.first;
if (Processed.count(IV))
continue;
const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first);
const DILocation *InlinedAt = IV.second;
// Instruction ranges, specifying where IV is accessible.
const auto &Entries = I.second;
LexicalScope *Scope = nullptr;
if (InlinedAt)
Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt);
else
Scope = LScopes.findLexicalScope(DIVar->getScope());
// If variable scope is not found then skip this variable.
if (!Scope)
continue;
LocalVariable Var;
Var.DIVar = DIVar;
calculateRanges(Var, Entries);
recordLocalVariable(std::move(Var), Scope);
}
}
void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) {
const TargetSubtargetInfo &TSI = MF->getSubtarget();
const TargetRegisterInfo *TRI = TSI.getRegisterInfo();
const MachineFrameInfo &MFI = MF->getFrameInfo();
const Function &GV = MF->getFunction();
auto Insertion = FnDebugInfo.insert({&GV, llvm::make_unique<FunctionInfo>()});
assert(Insertion.second && "function already has info");
CurFn = Insertion.first->second.get();
CurFn->FuncId = NextFuncId++;
CurFn->Begin = Asm->getFunctionBegin();
// The S_FRAMEPROC record reports the stack size, and how many bytes of
// callee-saved registers were used. For targets that don't use a PUSH
// instruction (AArch64), this will be zero.
CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters();
CurFn->FrameSize = MFI.getStackSize();
CurFn->OffsetAdjustment = MFI.getOffsetAdjustment();
CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF);
// For this function S_FRAMEPROC record, figure out which codeview register
// will be the frame pointer.
CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None.
CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None.
if (CurFn->FrameSize > 0) {
if (!TSI.getFrameLowering()->hasFP(*MF)) {
CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr;
} else {
// If there is an FP, parameters are always relative to it.
CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr;
if (CurFn->HasStackRealignment) {
// If the stack needs realignment, locals are relative to SP or VFRAME.
CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr;
} else {
// Otherwise, locals are relative to EBP, and we probably have VLAs or
// other stack adjustments.
CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr;
}
}
}
// Compute other frame procedure options.
FrameProcedureOptions FPO = FrameProcedureOptions::None;
if (MFI.hasVarSizedObjects())
FPO |= FrameProcedureOptions::HasAlloca;
if (MF->exposesReturnsTwice())
FPO |= FrameProcedureOptions::HasSetJmp;
// FIXME: Set HasLongJmp if we ever track that info.
if (MF->hasInlineAsm())
FPO |= FrameProcedureOptions::HasInlineAssembly;
if (GV.hasPersonalityFn()) {
if (isAsynchronousEHPersonality(
classifyEHPersonality(GV.getPersonalityFn())))
FPO |= FrameProcedureOptions::HasStructuredExceptionHandling;
else
FPO |= FrameProcedureOptions::HasExceptionHandling;
}
if (GV.hasFnAttribute(Attribute::InlineHint))
FPO |= FrameProcedureOptions::MarkedInline;
if (GV.hasFnAttribute(Attribute::Naked))
FPO |= FrameProcedureOptions::Naked;
if (MFI.hasStackProtectorIndex())
FPO |= FrameProcedureOptions::SecurityChecks;
FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U);
FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U);
if (Asm->TM.getOptLevel() != CodeGenOpt::None &&
!GV.hasOptSize() && !GV.hasOptNone())
FPO |= FrameProcedureOptions::OptimizedForSpeed;
// FIXME: Set GuardCfg when it is implemented.
CurFn->FrameProcOpts = FPO;
OS.EmitCVFuncIdDirective(CurFn->FuncId);
// Find the end of the function prolog. First known non-DBG_VALUE and
// non-frame setup location marks the beginning of the function body.
// FIXME: is there a simpler a way to do this? Can we just search
// for the first instruction of the function, not the last of the prolog?
DebugLoc PrologEndLoc;
bool EmptyPrologue = true;
for (const auto &MBB : *MF) {
for (const auto &MI : MBB) {
if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
MI.getDebugLoc()) {
PrologEndLoc = MI.getDebugLoc();
break;
} else if (!MI.isMetaInstruction()) {
EmptyPrologue = false;
}
}
}
// Record beginning of function if we have a non-empty prologue.
if (PrologEndLoc && !EmptyPrologue) {
DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc();
maybeRecordLocation(FnStartDL, MF);
}
}
static bool shouldEmitUdt(const DIType *T) {
if (!T)
return false;
// MSVC does not emit UDTs for typedefs that are scoped to classes.
if (T->getTag() == dwarf::DW_TAG_typedef) {
if (DIScope *Scope = T->getScope()) {
switch (Scope->getTag()) {
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_union_type:
return false;
}
}
}
while (true) {
if (!T || T->isForwardDecl())
return false;
const DIDerivedType *DT = dyn_cast<DIDerivedType>(T);
if (!DT)
return true;
T = DT->getBaseType();
}
return true;
}
void CodeViewDebug::addToUDTs(const DIType *Ty) {
// Don't record empty UDTs.
if (Ty->getName().empty())
return;
if (!shouldEmitUdt(Ty))
return;
SmallVector<StringRef, 5> QualifiedNameComponents;
const DISubprogram *ClosestSubprogram =
getQualifiedNameComponents(Ty->getScope(), QualifiedNameComponents);
std::string FullyQualifiedName =
getQualifiedName(QualifiedNameComponents, getPrettyScopeName(Ty));
if (ClosestSubprogram == nullptr) {
GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
} else if (ClosestSubprogram == CurrentSubprogram) {
LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty);
}
// TODO: What if the ClosestSubprogram is neither null or the current
// subprogram? Currently, the UDT just gets dropped on the floor.
//
// The current behavior is not desirable. To get maximal fidelity, we would
// need to perform all type translation before beginning emission of .debug$S
// and then make LocalUDTs a member of FunctionInfo
}
TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) {
// Generic dispatch for lowering an unknown type.
switch (Ty->getTag()) {
case dwarf::DW_TAG_array_type:
return lowerTypeArray(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_typedef:
return lowerTypeAlias(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_base_type:
return lowerTypeBasic(cast<DIBasicType>(Ty));
case dwarf::DW_TAG_pointer_type:
if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type")
return lowerTypeVFTableShape(cast<DIDerivedType>(Ty));
LLVM_FALLTHROUGH;
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_rvalue_reference_type:
return lowerTypePointer(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_ptr_to_member_type:
return lowerTypeMemberPointer(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_restrict_type:
case dwarf::DW_TAG_const_type:
case dwarf::DW_TAG_volatile_type:
// TODO: add support for DW_TAG_atomic_type here
return lowerTypeModifier(cast<DIDerivedType>(Ty));
case dwarf::DW_TAG_subroutine_type:
if (ClassTy) {
// The member function type of a member function pointer has no
// ThisAdjustment.
return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy,
/*ThisAdjustment=*/0,
/*IsStaticMethod=*/false);
}
return lowerTypeFunction(cast<DISubroutineType>(Ty));
case dwarf::DW_TAG_enumeration_type:
return lowerTypeEnum(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
return lowerTypeClass(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_union_type:
return lowerTypeUnion(cast<DICompositeType>(Ty));
case dwarf::DW_TAG_unspecified_type:
if (Ty->getName() == "decltype(nullptr)")
return TypeIndex::NullptrT();
return TypeIndex::None();
default:
// Use the null type index.
return TypeIndex();
}
}
TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) {
TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType());
StringRef TypeName = Ty->getName();
addToUDTs(Ty);
if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) &&
TypeName == "HRESULT")
return TypeIndex(SimpleTypeKind::HResult);
if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) &&
TypeName == "wchar_t")
return TypeIndex(SimpleTypeKind::WideCharacter);
return UnderlyingTypeIndex;
}
TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) {
const DIType *ElementType = Ty->getBaseType();
TypeIndex ElementTypeIndex = getTypeIndex(ElementType);
// IndexType is size_t, which depends on the bitness of the target.
TypeIndex IndexType = getPointerSizeInBytes() == 8
? TypeIndex(SimpleTypeKind::UInt64Quad)
: TypeIndex(SimpleTypeKind::UInt32Long);
uint64_t ElementSize = getBaseTypeSize(ElementType) / 8;
// Add subranges to array type.
DINodeArray Elements = Ty->getElements();
for (int i = Elements.size() - 1; i >= 0; --i) {
const DINode *Element = Elements[i];
assert(Element->getTag() == dwarf::DW_TAG_subrange_type);
const DISubrange *Subrange = cast<DISubrange>(Element);
assert(Subrange->getLowerBound() == 0 &&
"codeview doesn't support subranges with lower bounds");
int64_t Count = -1;
if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>())
Count = CI->getSExtValue();
// Forward declarations of arrays without a size and VLAs use a count of -1.
// Emit a count of zero in these cases to match what MSVC does for arrays
// without a size. MSVC doesn't support VLAs, so it's not clear what we
// should do for them even if we could distinguish them.
if (Count == -1)
Count = 0;
// Update the element size and element type index for subsequent subranges.
ElementSize *= Count;
// If this is the outermost array, use the size from the array. It will be
// more accurate if we had a VLA or an incomplete element type size.
uint64_t ArraySize =
(i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize;
StringRef Name = (i == 0) ? Ty->getName() : "";
ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name);
ElementTypeIndex = TypeTable.writeLeafType(AR);
}
return ElementTypeIndex;
}
TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) {
TypeIndex Index;
dwarf::TypeKind Kind;
uint32_t ByteSize;
Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding());
ByteSize = Ty->getSizeInBits() / 8;
SimpleTypeKind STK = SimpleTypeKind::None;
switch (Kind) {
case dwarf::DW_ATE_address:
// FIXME: Translate
break;
case dwarf::DW_ATE_boolean:
switch (ByteSize) {
case 1: STK = SimpleTypeKind::Boolean8; break;
case 2: STK = SimpleTypeKind::Boolean16; break;
case 4: STK = SimpleTypeKind::Boolean32; break;
case 8: STK = SimpleTypeKind::Boolean64; break;
case 16: STK = SimpleTypeKind::Boolean128; break;
}
break;
case dwarf::DW_ATE_complex_float:
switch (ByteSize) {
case 2: STK = SimpleTypeKind::Complex16; break;
case 4: STK = SimpleTypeKind::Complex32; break;
case 8: STK = SimpleTypeKind::Complex64; break;
case 10: STK = SimpleTypeKind::Complex80; break;
case 16: STK = SimpleTypeKind::Complex128; break;
}
break;
case dwarf::DW_ATE_float:
switch (ByteSize) {
case 2: STK = SimpleTypeKind::Float16; break;
case 4: STK = SimpleTypeKind::Float32; break;
case 6: STK = SimpleTypeKind::Float48; break;
case 8: STK = SimpleTypeKind::Float64; break;
case 10: STK = SimpleTypeKind::Float80; break;
case 16: STK = SimpleTypeKind::Float128; break;
}
break;
case dwarf::DW_ATE_signed:
switch (ByteSize) {
case 1: STK = SimpleTypeKind::SignedCharacter; break;
case 2: STK = SimpleTypeKind::Int16Short; break;
case 4: STK = SimpleTypeKind::Int32; break;
case 8: STK = SimpleTypeKind::Int64Quad; break;
case 16: STK = SimpleTypeKind::Int128Oct; break;
}
break;
case dwarf::DW_ATE_unsigned:
switch (ByteSize) {
case 1: STK = SimpleTypeKind::UnsignedCharacter; break;
case 2: STK = SimpleTypeKind::UInt16Short; break;
case 4: STK = SimpleTypeKind::UInt32; break;
case 8: STK = SimpleTypeKind::UInt64Quad; break;
case 16: STK = SimpleTypeKind::UInt128Oct; break;
}
break;
case dwarf::DW_ATE_UTF:
switch (ByteSize) {
case 2: STK = SimpleTypeKind::Character16; break;
case 4: STK = SimpleTypeKind::Character32; break;
}
break;
case dwarf::DW_ATE_signed_char:
if (ByteSize == 1)
STK = SimpleTypeKind::SignedCharacter;
break;
case dwarf::DW_ATE_unsigned_char:
if (ByteSize == 1)
STK = SimpleTypeKind::UnsignedCharacter;
break;
default:
break;
}
// Apply some fixups based on the source-level type name.
if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int")
STK = SimpleTypeKind::Int32Long;
if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int")
STK = SimpleTypeKind::UInt32Long;
if (STK == SimpleTypeKind::UInt16Short &&
(Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t"))
STK = SimpleTypeKind::WideCharacter;
if ((STK == SimpleTypeKind::SignedCharacter ||
STK == SimpleTypeKind::UnsignedCharacter) &&
Ty->getName() == "char")
STK = SimpleTypeKind::NarrowCharacter;
return TypeIndex(STK);
}
TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty,
PointerOptions PO) {
TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType());
// Pointers to simple types without any options can use SimpleTypeMode, rather
// than having a dedicated pointer type record.
if (PointeeTI.isSimple() && PO == PointerOptions::None &&
PointeeTI.getSimpleMode() == SimpleTypeMode::Direct &&
Ty->getTag() == dwarf::DW_TAG_pointer_type) {
SimpleTypeMode Mode = Ty->getSizeInBits() == 64
? SimpleTypeMode::NearPointer64
: SimpleTypeMode::NearPointer32;
return TypeIndex(PointeeTI.getSimpleKind(), Mode);
}
PointerKind PK =
Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32;
PointerMode PM = PointerMode::Pointer;
switch (Ty->getTag()) {
default: llvm_unreachable("not a pointer tag type");
case dwarf::DW_TAG_pointer_type:
PM = PointerMode::Pointer;
break;
case dwarf::DW_TAG_reference_type:
PM = PointerMode::LValueReference;
break;
case dwarf::DW_TAG_rvalue_reference_type:
PM = PointerMode::RValueReference;
break;
}
if (Ty->isObjectPointer())
PO |= PointerOptions::Const;
PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8);
return TypeTable.writeLeafType(PR);
}
static PointerToMemberRepresentation
translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) {
// SizeInBytes being zero generally implies that the member pointer type was
// incomplete, which can happen if it is part of a function prototype. In this
// case, use the unknown model instead of the general model.
if (IsPMF) {
switch (Flags & DINode::FlagPtrToMemberRep) {
case 0:
return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
: PointerToMemberRepresentation::GeneralFunction;
case DINode::FlagSingleInheritance:
return PointerToMemberRepresentation::SingleInheritanceFunction;
case DINode::FlagMultipleInheritance:
return PointerToMemberRepresentation::MultipleInheritanceFunction;
case DINode::FlagVirtualInheritance:
return PointerToMemberRepresentation::VirtualInheritanceFunction;
}
} else {
switch (Flags & DINode::FlagPtrToMemberRep) {
case 0:
return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown
: PointerToMemberRepresentation::GeneralData;
case DINode::FlagSingleInheritance:
return PointerToMemberRepresentation::SingleInheritanceData;
case DINode::FlagMultipleInheritance:
return PointerToMemberRepresentation::MultipleInheritanceData;
case DINode::FlagVirtualInheritance:
return PointerToMemberRepresentation::VirtualInheritanceData;
}
}
llvm_unreachable("invalid ptr to member representation");
}
TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty,
PointerOptions PO) {
assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type);
TypeIndex ClassTI = getTypeIndex(Ty->getClassType());
TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), Ty->getClassType());
PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
: PointerKind::Near32;
bool IsPMF = isa<DISubroutineType>(Ty->getBaseType());
PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction
: PointerMode::PointerToDataMember;
assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big");
uint8_t SizeInBytes = Ty->getSizeInBits() / 8;
MemberPointerInfo MPI(
ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags()));
PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI);
return TypeTable.writeLeafType(PR);
}
/// Given a DWARF calling convention, get the CodeView equivalent. If we don't
/// have a translation, use the NearC convention.
static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) {
switch (DwarfCC) {
case dwarf::DW_CC_normal: return CallingConvention::NearC;
case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast;
case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall;
case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall;
case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal;
case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector;
}
return CallingConvention::NearC;
}
TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) {
ModifierOptions Mods = ModifierOptions::None;
PointerOptions PO = PointerOptions::None;
bool IsModifier = true;
const DIType *BaseTy = Ty;
while (IsModifier && BaseTy) {
// FIXME: Need to add DWARF tags for __unaligned and _Atomic
switch (BaseTy->getTag()) {
case dwarf::DW_TAG_const_type:
Mods |= ModifierOptions::Const;
PO |= PointerOptions::Const;
break;
case dwarf::DW_TAG_volatile_type:
Mods |= ModifierOptions::Volatile;
PO |= PointerOptions::Volatile;
break;
case dwarf::DW_TAG_restrict_type:
// Only pointer types be marked with __restrict. There is no known flag
// for __restrict in LF_MODIFIER records.
PO |= PointerOptions::Restrict;
break;
default:
IsModifier = false;
break;
}
if (IsModifier)
BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType();
}
// Check if the inner type will use an LF_POINTER record. If so, the
// qualifiers will go in the LF_POINTER record. This comes up for types like
// 'int *const' and 'int *__restrict', not the more common cases like 'const
// char *'.
if (BaseTy) {
switch (BaseTy->getTag()) {
case dwarf::DW_TAG_pointer_type:
case dwarf::DW_TAG_reference_type:
case dwarf::DW_TAG_rvalue_reference_type:
return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO);
case dwarf::DW_TAG_ptr_to_member_type:
return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO);
default:
break;
}
}
TypeIndex ModifiedTI = getTypeIndex(BaseTy);
// Return the base type index if there aren't any modifiers. For example, the
// metadata could contain restrict wrappers around non-pointer types.
if (Mods == ModifierOptions::None)
return ModifiedTI;
ModifierRecord MR(ModifiedTI, Mods);
return TypeTable.writeLeafType(MR);
}
TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) {
SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices;
for (const DIType *ArgType : Ty->getTypeArray())
ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType));
// MSVC uses type none for variadic argument.
if (ReturnAndArgTypeIndices.size() > 1 &&
ReturnAndArgTypeIndices.back() == TypeIndex::Void()) {
ReturnAndArgTypeIndices.back() = TypeIndex::None();
}
TypeIndex ReturnTypeIndex = TypeIndex::Void();
ArrayRef<TypeIndex> ArgTypeIndices = None;
if (!ReturnAndArgTypeIndices.empty()) {
auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices);
ReturnTypeIndex = ReturnAndArgTypesRef.front();
ArgTypeIndices = ReturnAndArgTypesRef.drop_front();
}
ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
FunctionOptions FO = getFunctionOptions(Ty);
ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(),
ArgListIndex);
return TypeTable.writeLeafType(Procedure);
}
TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty,
const DIType *ClassTy,
int ThisAdjustment,
bool IsStaticMethod,
FunctionOptions FO) {
// Lower the containing class type.
TypeIndex ClassType = getTypeIndex(ClassTy);
DITypeRefArray ReturnAndArgs = Ty->getTypeArray();
unsigned Index = 0;
SmallVector<TypeIndex, 8> ArgTypeIndices;
TypeIndex ReturnTypeIndex = TypeIndex::Void();
if (ReturnAndArgs.size() > Index) {
ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]);
}
// If the first argument is a pointer type and this isn't a static method,
// treat it as the special 'this' parameter, which is encoded separately from
// the arguments.
TypeIndex ThisTypeIndex;
if (!IsStaticMethod && ReturnAndArgs.size() > Index) {
if (const DIDerivedType *PtrTy =
dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) {
if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) {
ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty);
Index++;
}
}
}
while (Index < ReturnAndArgs.size())
ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++]));
// MSVC uses type none for variadic argument.
if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void())
ArgTypeIndices.back() = TypeIndex::None();
ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices);
TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec);
CallingConvention CC = dwarfCCToCodeView(Ty->getCC());
MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO,
ArgTypeIndices.size(), ArgListIndex, ThisAdjustment);
return TypeTable.writeLeafType(MFR);
}
TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) {
unsigned VSlotCount =
Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize());
SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near);
VFTableShapeRecord VFTSR(Slots);
return TypeTable.writeLeafType(VFTSR);
}
static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) {
switch (Flags & DINode::FlagAccessibility) {
case DINode::FlagPrivate: return MemberAccess::Private;
case DINode::FlagPublic: return MemberAccess::Public;
case DINode::FlagProtected: return MemberAccess::Protected;
case 0:
// If there was no explicit access control, provide the default for the tag.
return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private
: MemberAccess::Public;
}
llvm_unreachable("access flags are exclusive");
}
static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) {
if (SP->isArtificial())
return MethodOptions::CompilerGenerated;
// FIXME: Handle other MethodOptions.
return MethodOptions::None;
}
static MethodKind translateMethodKindFlags(const DISubprogram *SP,
bool Introduced) {
if (SP->getFlags() & DINode::FlagStaticMember)
return MethodKind::Static;
switch (SP->getVirtuality()) {
case dwarf::DW_VIRTUALITY_none:
break;
case dwarf::DW_VIRTUALITY_virtual:
return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual;
case dwarf::DW_VIRTUALITY_pure_virtual:
return Introduced ? MethodKind::PureIntroducingVirtual
: MethodKind::PureVirtual;
default:
llvm_unreachable("unhandled virtuality case");
}
return MethodKind::Vanilla;
}
static TypeRecordKind getRecordKind(const DICompositeType *Ty) {
switch (Ty->getTag()) {
case dwarf::DW_TAG_class_type: return TypeRecordKind::Class;
case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct;
}
llvm_unreachable("unexpected tag");
}
/// Return ClassOptions that should be present on both the forward declaration
/// and the defintion of a tag type.
static ClassOptions getCommonClassOptions(const DICompositeType *Ty) {
ClassOptions CO = ClassOptions::None;
// MSVC always sets this flag, even for local types. Clang doesn't always
// appear to give every type a linkage name, which may be problematic for us.
// FIXME: Investigate the consequences of not following them here.
if (!Ty->getIdentifier().empty())
CO |= ClassOptions::HasUniqueName;
// Put the Nested flag on a type if it appears immediately inside a tag type.
// Do not walk the scope chain. Do not attempt to compute ContainsNestedClass
// here. That flag is only set on definitions, and not forward declarations.
const DIScope *ImmediateScope = Ty->getScope();
if (ImmediateScope && isa<DICompositeType>(ImmediateScope))
CO |= ClassOptions::Nested;
// Put the Scoped flag on function-local types. MSVC puts this flag for enum
// type only when it has an immediate function scope. Clang never puts enums
// inside DILexicalBlock scopes. Enum types, as generated by clang, are
// always in function, class, or file scopes.
if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) {
if (ImmediateScope && isa<DISubprogram>(ImmediateScope))
CO |= ClassOptions::Scoped;
} else {
for (const DIScope *Scope = ImmediateScope; Scope != nullptr;
Scope = Scope->getScope()) {
if (isa<DISubprogram>(Scope)) {
CO |= ClassOptions::Scoped;
break;
}
}
}
return CO;
}
void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) {
switch (Ty->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
case dwarf::DW_TAG_enumeration_type:
break;
default:
return;
}
if (const auto *File = Ty->getFile()) {
StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File));
TypeIndex SIDI = TypeTable.writeLeafType(SIDR);
UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine());
TypeTable.writeLeafType(USLR);
}
}
TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) {
ClassOptions CO = getCommonClassOptions(Ty);
TypeIndex FTI;
unsigned EnumeratorCount = 0;
if (Ty->isForwardDecl()) {
CO |= ClassOptions::ForwardReference;
} else {
ContinuationRecordBuilder ContinuationBuilder;
ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
for (const DINode *Element : Ty->getElements()) {
// We assume that the frontend provides all members in source declaration
// order, which is what MSVC does.
if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) {
EnumeratorRecord ER(MemberAccess::Public,
APSInt::getUnsigned(Enumerator->getValue()),
Enumerator->getName());
ContinuationBuilder.writeMemberType(ER);
EnumeratorCount++;
}
}
FTI = TypeTable.insertRecord(ContinuationBuilder);
}
std::string FullName = getFullyQualifiedName(Ty);
EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(),
getTypeIndex(Ty->getBaseType()));
TypeIndex EnumTI = TypeTable.writeLeafType(ER);
addUDTSrcLine(Ty, EnumTI);
return EnumTI;
}
//===----------------------------------------------------------------------===//
// ClassInfo
//===----------------------------------------------------------------------===//
struct llvm::ClassInfo {
struct MemberInfo {
const DIDerivedType *MemberTypeNode;
uint64_t BaseOffset;
};
// [MemberInfo]
using MemberList = std::vector<MemberInfo>;
using MethodsList = TinyPtrVector<const DISubprogram *>;
// MethodName -> MethodsList
using MethodsMap = MapVector<MDString *, MethodsList>;
/// Base classes.
std::vector<const DIDerivedType *> Inheritance;
/// Direct members.
MemberList Members;
// Direct overloaded methods gathered by name.
MethodsMap Methods;
TypeIndex VShapeTI;
std::vector<const DIType *> NestedTypes;
};
void CodeViewDebug::clear() {
assert(CurFn == nullptr);
FileIdMap.clear();
FnDebugInfo.clear();
FileToFilepathMap.clear();
LocalUDTs.clear();
GlobalUDTs.clear();
TypeIndices.clear();
CompleteTypeIndices.clear();
ScopeGlobals.clear();
}
void CodeViewDebug::collectMemberInfo(ClassInfo &Info,
const DIDerivedType *DDTy) {
if (!DDTy->getName().empty()) {
Info.Members.push_back({DDTy, 0});
return;
}
// An unnamed member may represent a nested struct or union. Attempt to
// interpret the unnamed member as a DICompositeType possibly wrapped in
// qualifier types. Add all the indirect fields to the current record if that
// succeeds, and drop the member if that fails.
assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!");
uint64_t Offset = DDTy->getOffsetInBits();
const DIType *Ty = DDTy->getBaseType();
bool FullyResolved = false;
while (!FullyResolved) {
switch (Ty->getTag()) {
case dwarf::DW_TAG_const_type:
case dwarf::DW_TAG_volatile_type:
// FIXME: we should apply the qualifier types to the indirect fields
// rather than dropping them.
Ty = cast<DIDerivedType>(Ty)->getBaseType();
break;
default:
FullyResolved = true;
break;
}
}
const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty);
if (!DCTy)
return;
ClassInfo NestedInfo = collectClassInfo(DCTy);
for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members)
Info.Members.push_back(
{IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset});
}
ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) {
ClassInfo Info;
// Add elements to structure type.
DINodeArray Elements = Ty->getElements();
for (auto *Element : Elements) {
// We assume that the frontend provides all members in source declaration
// order, which is what MSVC does.
if (!Element)
continue;
if (auto *SP = dyn_cast<DISubprogram>(Element)) {
Info.Methods[SP->getRawName()].push_back(SP);
} else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) {
if (DDTy->getTag() == dwarf::DW_TAG_member) {
collectMemberInfo(Info, DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) {
Info.Inheritance.push_back(DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type &&
DDTy->getName() == "__vtbl_ptr_type") {
Info.VShapeTI = getTypeIndex(DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_typedef) {
Info.NestedTypes.push_back(DDTy);
} else if (DDTy->getTag() == dwarf::DW_TAG_friend) {
// Ignore friend members. It appears that MSVC emitted info about
// friends in the past, but modern versions do not.
}
} else if (auto *Composite = dyn_cast<DICompositeType>(Element)) {
Info.NestedTypes.push_back(Composite);
}
// Skip other unrecognized kinds of elements.
}
return Info;
}
static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) {
// This routine is used by lowerTypeClass and lowerTypeUnion to determine
// if a complete type should be emitted instead of a forward reference.
return Ty->getName().empty() && Ty->getIdentifier().empty() &&
!Ty->isForwardDecl();
}
TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) {
// Emit the complete type for unnamed structs. C++ classes with methods
// which have a circular reference back to the class type are expected to
// be named by the front-end and should not be "unnamed". C unnamed
// structs should not have circular references.
if (shouldAlwaysEmitCompleteClassType(Ty)) {
// If this unnamed complete type is already in the process of being defined
// then the description of the type is malformed and cannot be emitted
// into CodeView correctly so report a fatal error.
auto I = CompleteTypeIndices.find(Ty);
if (I != CompleteTypeIndices.end() && I->second == TypeIndex())
report_fatal_error("cannot debug circular reference to unnamed type");
return getCompleteTypeIndex(Ty);
}
// First, construct the forward decl. Don't look into Ty to compute the
// forward decl options, since it might not be available in all TUs.
TypeRecordKind Kind = getRecordKind(Ty);
ClassOptions CO =
ClassOptions::ForwardReference | getCommonClassOptions(Ty);
std::string FullName = getFullyQualifiedName(Ty);
ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0,
FullName, Ty->getIdentifier());
TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR);
if (!Ty->isForwardDecl())
DeferredCompleteTypes.push_back(Ty);
return FwdDeclTI;
}
TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) {
// Construct the field list and complete type record.
TypeRecordKind Kind = getRecordKind(Ty);
ClassOptions CO = getCommonClassOptions(Ty);
TypeIndex FieldTI;
TypeIndex VShapeTI;
unsigned FieldCount;
bool ContainsNestedClass;
std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) =
lowerRecordFieldList(Ty);
if (ContainsNestedClass)
CO |= ClassOptions::ContainsNestedClass;
// MSVC appears to set this flag by searching any destructor or method with
// FunctionOptions::Constructor among the emitted members. Clang AST has all
// the members, however special member functions are not yet emitted into
// debug information. For now checking a class's non-triviality seems enough.
// FIXME: not true for a nested unnamed struct.
if (isNonTrivial(Ty))
CO |= ClassOptions::HasConstructorOrDestructor;
std::string FullName = getFullyQualifiedName(Ty);
uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI,
SizeInBytes, FullName, Ty->getIdentifier());
TypeIndex ClassTI = TypeTable.writeLeafType(CR);
addUDTSrcLine(Ty, ClassTI);
addToUDTs(Ty);
return ClassTI;
}
TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) {
// Emit the complete type for unnamed unions.
if (shouldAlwaysEmitCompleteClassType(Ty))
return getCompleteTypeIndex(Ty);
ClassOptions CO =
ClassOptions::ForwardReference | getCommonClassOptions(Ty);
std::string FullName = getFullyQualifiedName(Ty);
UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier());
TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR);
if (!Ty->isForwardDecl())
DeferredCompleteTypes.push_back(Ty);
return FwdDeclTI;
}
TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) {
ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty);
TypeIndex FieldTI;
unsigned FieldCount;
bool ContainsNestedClass;
std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) =
lowerRecordFieldList(Ty);
if (ContainsNestedClass)
CO |= ClassOptions::ContainsNestedClass;
uint64_t SizeInBytes = Ty->getSizeInBits() / 8;
std::string FullName = getFullyQualifiedName(Ty);
UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName,
Ty->getIdentifier());
TypeIndex UnionTI = TypeTable.writeLeafType(UR);
addUDTSrcLine(Ty, UnionTI);
addToUDTs(Ty);
return UnionTI;
}
std::tuple<TypeIndex, TypeIndex, unsigned, bool>
CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) {
// Manually count members. MSVC appears to count everything that generates a
// field list record. Each individual overload in a method overload group
// contributes to this count, even though the overload group is a single field
// list record.
unsigned MemberCount = 0;
ClassInfo Info = collectClassInfo(Ty);
ContinuationRecordBuilder ContinuationBuilder;
ContinuationBuilder.begin(ContinuationRecordKind::FieldList);
// Create base classes.
for (const DIDerivedType *I : Info.Inheritance) {
if (I->getFlags() & DINode::FlagVirtual) {
// Virtual base.
unsigned VBPtrOffset = I->getVBPtrOffset();
// FIXME: Despite the accessor name, the offset is really in bytes.
unsigned VBTableIndex = I->getOffsetInBits() / 4;
auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase
? TypeRecordKind::IndirectVirtualBaseClass
: TypeRecordKind::VirtualBaseClass;
VirtualBaseClassRecord VBCR(
RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()),
getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset,
VBTableIndex);
ContinuationBuilder.writeMemberType(VBCR);
MemberCount++;
} else {
assert(I->getOffsetInBits() % 8 == 0 &&
"bases must be on byte boundaries");
BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()),
getTypeIndex(I->getBaseType()),
I->getOffsetInBits() / 8);
ContinuationBuilder.writeMemberType(BCR);
MemberCount++;
}
}
// Create members.
for (ClassInfo::MemberInfo &MemberInfo : Info.Members) {
const DIDerivedType *Member = MemberInfo.MemberTypeNode;
TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType());
StringRef MemberName = Member->getName();
MemberAccess Access =
translateAccessFlags(Ty->getTag(), Member->getFlags());
if (Member->isStaticMember()) {
StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName);
ContinuationBuilder.writeMemberType(SDMR);
MemberCount++;
continue;
}
// Virtual function pointer member.
if ((Member->getFlags() & DINode::FlagArtificial) &&
Member->getName().startswith("_vptr$")) {
VFPtrRecord VFPR(getTypeIndex(Member->getBaseType()));
ContinuationBuilder.writeMemberType(VFPR);
MemberCount++;
continue;
}
// Data member.
uint64_t MemberOffsetInBits =
Member->getOffsetInBits() + MemberInfo.BaseOffset;
if (Member->isBitField()) {
uint64_t StartBitOffset = MemberOffsetInBits;
if (const auto *CI =
dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) {
MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset;
}
StartBitOffset -= MemberOffsetInBits;
BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(),
StartBitOffset);
MemberBaseType = TypeTable.writeLeafType(BFR);
}
uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8;
DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes,
MemberName);
ContinuationBuilder.writeMemberType(DMR);
MemberCount++;
}
// Create methods
for (auto &MethodItr : Info.Methods) {
StringRef Name = MethodItr.first->getString();
std::vector<OneMethodRecord> Methods;
for (const DISubprogram *SP : MethodItr.second) {
TypeIndex MethodType = getMemberFunctionType(SP, Ty);
bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual;
unsigned VFTableOffset = -1;
if (Introduced)
VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes();
Methods.push_back(OneMethodRecord(
MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()),
translateMethodKindFlags(SP, Introduced),
translateMethodOptionFlags(SP), VFTableOffset, Name));
MemberCount++;
}
assert(!Methods.empty() && "Empty methods map entry");
if (Methods.size() == 1)
ContinuationBuilder.writeMemberType(Methods[0]);
else {
// FIXME: Make this use its own ContinuationBuilder so that
// MethodOverloadList can be split correctly.
MethodOverloadListRecord MOLR(Methods);
TypeIndex MethodList = TypeTable.writeLeafType(MOLR);
OverloadedMethodRecord OMR(Methods.size(), MethodList, Name);
ContinuationBuilder.writeMemberType(OMR);
}
}
// Create nested classes.
for (const DIType *Nested : Info.NestedTypes) {
NestedTypeRecord R(getTypeIndex(Nested), Nested->getName());
ContinuationBuilder.writeMemberType(R);
MemberCount++;
}
TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder);
return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount,
!Info.NestedTypes.empty());
}
TypeIndex CodeViewDebug::getVBPTypeIndex() {
if (!VBPType.getIndex()) {
// Make a 'const int *' type.
ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const);
TypeIndex ModifiedTI = TypeTable.writeLeafType(MR);
PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64
: PointerKind::Near32;
PointerMode PM = PointerMode::Pointer;
PointerOptions PO = PointerOptions::None;
PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes());
VBPType = TypeTable.writeLeafType(PR);
}
return VBPType;
}
TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) {
// The null DIType is the void type. Don't try to hash it.
if (!Ty)
return TypeIndex::Void();
// Check if we've already translated this type. Don't try to do a
// get-or-create style insertion that caches the hash lookup across the
// lowerType call. It will update the TypeIndices map.
auto I = TypeIndices.find({Ty, ClassTy});
if (I != TypeIndices.end())
return I->second;
TypeLoweringScope S(*this);
TypeIndex TI = lowerType(Ty, ClassTy);
return recordTypeIndexForDINode(Ty, TI, ClassTy);
}
codeview::TypeIndex
CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy,
const DISubroutineType *SubroutineTy) {
assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type &&
"this type must be a pointer type");
PointerOptions Options = PointerOptions::None;
if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference)
Options = PointerOptions::LValueRefThisPointer;
else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference)
Options = PointerOptions::RValueRefThisPointer;
// Check if we've already translated this type. If there is no ref qualifier
// on the function then we look up this pointer type with no associated class
// so that the TypeIndex for the this pointer can be shared with the type
// index for other pointers to this class type. If there is a ref qualifier
// then we lookup the pointer using the subroutine as the parent type.
auto I = TypeIndices.find({PtrTy, SubroutineTy});
if (I != TypeIndices.end())
return I->second;
TypeLoweringScope S(*this);
TypeIndex TI = lowerTypePointer(PtrTy, Options);
return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy);
}
TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) {
PointerRecord PR(getTypeIndex(Ty),
getPointerSizeInBytes() == 8 ? PointerKind::Near64
: PointerKind::Near32,
PointerMode::LValueReference, PointerOptions::None,
Ty->getSizeInBits() / 8);
return TypeTable.writeLeafType(PR);
}
TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) {
// The null DIType is the void type. Don't try to hash it.
if (!Ty)
return TypeIndex::Void();
// Look through typedefs when getting the complete type index. Call
// getTypeIndex on the typdef to ensure that any UDTs are accumulated and are
// emitted only once.
if (Ty->getTag() == dwarf::DW_TAG_typedef)
(void)getTypeIndex(Ty);
while (Ty->getTag() == dwarf::DW_TAG_typedef)
Ty = cast<DIDerivedType>(Ty)->getBaseType();
// If this is a non-record type, the complete type index is the same as the
// normal type index. Just call getTypeIndex.
switch (Ty->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
case dwarf::DW_TAG_union_type:
break;
default:
return getTypeIndex(Ty);
}
const auto *CTy = cast<DICompositeType>(Ty);
TypeLoweringScope S(*this);
// Make sure the forward declaration is emitted first. It's unclear if this
// is necessary, but MSVC does it, and we should follow suit until we can show
// otherwise.
// We only emit a forward declaration for named types.
if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) {
TypeIndex FwdDeclTI = getTypeIndex(CTy);
// Just use the forward decl if we don't have complete type info. This
// might happen if the frontend is using modules and expects the complete
// definition to be emitted elsewhere.
if (CTy->isForwardDecl())
return FwdDeclTI;
}
// Check if we've already translated the complete record type.
// Insert the type with a null TypeIndex to signify that the type is currently
// being lowered.
auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()});
if (!InsertResult.second)
return InsertResult.first->second;
TypeIndex TI;
switch (CTy->getTag()) {
case dwarf::DW_TAG_class_type:
case dwarf::DW_TAG_structure_type:
TI = lowerCompleteTypeClass(CTy);
break;
case dwarf::DW_TAG_union_type:
TI = lowerCompleteTypeUnion(CTy);
break;
default:
llvm_unreachable("not a record");
}
// Update the type index associated with this CompositeType. This cannot
// use the 'InsertResult' iterator above because it is potentially
// invalidated by map insertions which can occur while lowering the class
// type above.
CompleteTypeIndices[CTy] = TI;
return TI;
}
/// Emit all the deferred complete record types. Try to do this in FIFO order,
/// and do this until fixpoint, as each complete record type typically
/// references
/// many other record types.
void CodeViewDebug::emitDeferredCompleteTypes() {
SmallVector<const DICompositeType *, 4> TypesToEmit;
while (!DeferredCompleteTypes.empty()) {
std::swap(DeferredCompleteTypes, TypesToEmit);
for (const DICompositeType *RecordTy : TypesToEmit)
getCompleteTypeIndex(RecordTy);
TypesToEmit.clear();
}
}
void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI,
ArrayRef<LocalVariable> Locals) {
// Get the sorted list of parameters and emit them first.
SmallVector<const LocalVariable *, 6> Params;
for (const LocalVariable &L : Locals)
if (L.DIVar->isParameter())
Params.push_back(&L);
llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) {
return L->DIVar->getArg() < R->DIVar->getArg();
});
for (const LocalVariable *L : Params)
emitLocalVariable(FI, *L);
// Next emit all non-parameters in the order that we found them.
for (const LocalVariable &L : Locals)
if (!L.DIVar->isParameter())
emitLocalVariable(FI, L);
}
/// Only call this on endian-specific types like ulittle16_t and little32_t, or
/// structs composed of them.
template <typename T>
static void copyBytesForDefRange(SmallString<20> &BytePrefix,
SymbolKind SymKind, const T &DefRangeHeader) {
BytePrefix.resize(2 + sizeof(T));
ulittle16_t SymKindLE = ulittle16_t(SymKind);
memcpy(&BytePrefix[0], &SymKindLE, 2);
memcpy(&BytePrefix[2], &DefRangeHeader, sizeof(T));
}
void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI,
const LocalVariable &Var) {
// LocalSym record, see SymbolRecord.h for more info.
MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL);
LocalSymFlags Flags = LocalSymFlags::None;
if (Var.DIVar->isParameter())
Flags |= LocalSymFlags::IsParameter;
if (Var.DefRanges.empty())
Flags |= LocalSymFlags::IsOptimizedOut;
OS.AddComment("TypeIndex");
TypeIndex TI = Var.UseReferenceType
? getTypeIndexForReferenceTo(Var.DIVar->getType())
: getCompleteTypeIndex(Var.DIVar->getType());
OS.EmitIntValue(TI.getIndex(), 4);
OS.AddComment("Flags");
OS.EmitIntValue(static_cast<uint16_t>(Flags), 2);
// Truncate the name so we won't overflow the record length field.
emitNullTerminatedSymbolName(OS, Var.DIVar->getName());
endSymbolRecord(LocalEnd);
// Calculate the on disk prefix of the appropriate def range record. The
// records and on disk formats are described in SymbolRecords.h. BytePrefix
// should be big enough to hold all forms without memory allocation.
SmallString<20> BytePrefix;
for (const LocalVarDefRange &DefRange : Var.DefRanges) {
BytePrefix.clear();
if (DefRange.InMemory) {
int Offset = DefRange.DataOffset;
unsigned Reg = DefRange.CVRegister;
// 32-bit x86 call sequences often use PUSH instructions, which disrupt
// ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0,
// instead. In frames without stack realignment, $T0 will be the CFA.
if (RegisterId(Reg) == RegisterId::ESP) {
Reg = unsigned(RegisterId::VFRAME);
Offset += FI.OffsetAdjustment;
}
// If we can use the chosen frame pointer for the frame and this isn't a
// sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record.
// Otherwise, use S_DEFRANGE_REGISTER_REL.
EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU);
if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None &&
(bool(Flags & LocalSymFlags::IsParameter)
? (EncFP == FI.EncodedParamFramePtrReg)
: (EncFP == FI.EncodedLocalFramePtrReg))) {
little32_t FPOffset = little32_t(Offset);
copyBytesForDefRange(BytePrefix, S_DEFRANGE_FRAMEPOINTER_REL, FPOffset);
} else {
uint16_t RegRelFlags = 0;
if (DefRange.IsSubfield) {
RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag |
(DefRange.StructOffset
<< DefRangeRegisterRelSym::OffsetInParentShift);
}
DefRangeRegisterRelSym::Header DRHdr;
DRHdr.Register = Reg;
DRHdr.Flags = RegRelFlags;
DRHdr.BasePointerOffset = Offset;
copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER_REL, DRHdr);
}
} else {
assert(DefRange.DataOffset == 0 && "unexpected offset into register");
if (DefRange.IsSubfield) {
DefRangeSubfieldRegisterSym::Header DRHdr;
DRHdr.Register = DefRange.CVRegister;
DRHdr.MayHaveNoName = 0;
DRHdr.OffsetInParent = DefRange.StructOffset;
copyBytesForDefRange(BytePrefix, S_DEFRANGE_SUBFIELD_REGISTER, DRHdr);
} else {
DefRangeRegisterSym::Header DRHdr;
DRHdr.Register = DefRange.CVRegister;
DRHdr.MayHaveNoName = 0;
copyBytesForDefRange(BytePrefix, S_DEFRANGE_REGISTER, DRHdr);
}
}
OS.EmitCVDefRangeDirective(DefRange.Ranges, BytePrefix);
}
}
void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks,
const FunctionInfo& FI) {
for (LexicalBlock *Block : Blocks)
emitLexicalBlock(*Block, FI);
}
/// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a
/// lexical block scope.
void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block,
const FunctionInfo& FI) {
MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32);
OS.AddComment("PtrParent");
OS.EmitIntValue(0, 4); // PtrParent
OS.AddComment("PtrEnd");
OS.EmitIntValue(0, 4); // PtrEnd
OS.AddComment("Code size");
OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size
OS.AddComment("Function section relative address");
OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset
OS.AddComment("Function section index");
OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol
OS.AddComment("Lexical block name");
emitNullTerminatedSymbolName(OS, Block.Name); // Name
endSymbolRecord(RecordEnd);
// Emit variables local to this lexical block.
emitLocalVariableList(FI, Block.Locals);
emitGlobalVariableList(Block.Globals);
// Emit lexical blocks contained within this block.
emitLexicalBlockList(Block.Children, FI);
// Close the lexical block scope.
emitEndSymbolRecord(SymbolKind::S_END);
}
/// Convenience routine for collecting lexical block information for a list
/// of lexical scopes.
void CodeViewDebug::collectLexicalBlockInfo(
SmallVectorImpl<LexicalScope *> &Scopes,
SmallVectorImpl<LexicalBlock *> &Blocks,
SmallVectorImpl<LocalVariable> &Locals,
SmallVectorImpl<CVGlobalVariable> &Globals) {
for (LexicalScope *Scope : Scopes)
collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals);
}
/// Populate the lexical blocks and local variable lists of the parent with
/// information about the specified lexical scope.
void CodeViewDebug::collectLexicalBlockInfo(
LexicalScope &Scope,
SmallVectorImpl<LexicalBlock *> &ParentBlocks,
SmallVectorImpl<LocalVariable> &ParentLocals,
SmallVectorImpl<CVGlobalVariable> &ParentGlobals) {
if (Scope.isAbstractScope())
return;
// Gather information about the lexical scope including local variables,
// global variables, and address ranges.
bool IgnoreScope = false;
auto LI = ScopeVariables.find(&Scope);
SmallVectorImpl<LocalVariable> *Locals =
LI != ScopeVariables.end() ? &LI->second : nullptr;
auto GI = ScopeGlobals.find(Scope.getScopeNode());
SmallVectorImpl<CVGlobalVariable> *Globals =
GI != ScopeGlobals.end() ? GI->second.get() : nullptr;
const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode());
const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges();
// Ignore lexical scopes which do not contain variables.
if (!Locals && !Globals)
IgnoreScope = true;
// Ignore lexical scopes which are not lexical blocks.
if (!DILB)
IgnoreScope = true;
// Ignore scopes which have too many address ranges to represent in the
// current CodeView format or do not have a valid address range.
//
// For lexical scopes with multiple address ranges you may be tempted to
// construct a single range covering every instruction where the block is
// live and everything in between. Unfortunately, Visual Studio only
// displays variables from the first matching lexical block scope. If the
// first lexical block contains exception handling code or cold code which
// is moved to the bottom of the routine creating a single range covering
// nearly the entire routine, then it will hide all other lexical blocks
// and the variables they contain.
if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second))
IgnoreScope = true;
if (IgnoreScope) {
// This scope can be safely ignored and eliminating it will reduce the
// size of the debug information. Be sure to collect any variable and scope
// information from the this scope or any of its children and collapse them
// into the parent scope.
if (Locals)
ParentLocals.append(Locals->begin(), Locals->end());
if (Globals)
ParentGlobals.append(Globals->begin(), Globals->end());
collectLexicalBlockInfo(Scope.getChildren(),
ParentBlocks,
ParentLocals,
ParentGlobals);
return;
}
// Create a new CodeView lexical block for this lexical scope. If we've
// seen this DILexicalBlock before then the scope tree is malformed and
// we can handle this gracefully by not processing it a second time.
auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()});
if (!BlockInsertion.second)
return;
// Create a lexical block containing the variables and collect the the
// lexical block information for the children.
const InsnRange &Range = Ranges.front();
assert(Range.first && Range.second);
LexicalBlock &Block = BlockInsertion.first->second;
Block.Begin = getLabelBeforeInsn(Range.first);
Block.End = getLabelAfterInsn(Range.second);
assert(Block.Begin && "missing label for scope begin");
assert(Block.End && "missing label for scope end");
Block.Name = DILB->getName();
if (Locals)
Block.Locals = std::move(*Locals);
if (Globals)
Block.Globals = std::move(*Globals);
ParentBlocks.push_back(&Block);
collectLexicalBlockInfo(Scope.getChildren(),
Block.Children,
Block.Locals,
Block.Globals);
}
void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) {
const Function &GV = MF->getFunction();
assert(FnDebugInfo.count(&GV));
assert(CurFn == FnDebugInfo[&GV].get());
collectVariableInfo(GV.getSubprogram());
// Build the lexical block structure to emit for this routine.
if (LexicalScope *CFS = LScopes.getCurrentFunctionScope())
collectLexicalBlockInfo(*CFS,
CurFn->ChildBlocks,
CurFn->Locals,
CurFn->Globals);
// Clear the scope and variable information from the map which will not be
// valid after we have finished processing this routine. This also prepares
// the map for the subsequent routine.
ScopeVariables.clear();
// Don't emit anything if we don't have any line tables.
// Thunks are compiler-generated and probably won't have source correlation.
if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) {
FnDebugInfo.erase(&GV);
CurFn = nullptr;
return;
}
CurFn->Annotations = MF->getCodeViewAnnotations();
CurFn->HeapAllocSites = MF->getCodeViewHeapAllocSites();
CurFn->End = Asm->getFunctionEnd();
CurFn = nullptr;
}
void CodeViewDebug::beginInstruction(const MachineInstr *MI) {
DebugHandlerBase::beginInstruction(MI);
// Ignore DBG_VALUE and DBG_LABEL locations and function prologue.
if (!Asm || !CurFn || MI->isDebugInstr() ||
MI->getFlag(MachineInstr::FrameSetup))
return;
// If the first instruction of a new MBB has no location, find the first
// instruction with a location and use that.
DebugLoc DL = MI->getDebugLoc();
if (!DL && MI->getParent() != PrevInstBB) {
for (const auto &NextMI : *MI->getParent()) {
if (NextMI.isDebugInstr())
continue;
DL = NextMI.getDebugLoc();
if (DL)
break;
}
}
PrevInstBB = MI->getParent();
// If we still don't have a debug location, don't record a location.
if (!DL)
return;
maybeRecordLocation(DL, Asm->MF);
}
MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) {
MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
*EndLabel = MMI->getContext().createTempSymbol();
OS.EmitIntValue(unsigned(Kind), 4);
OS.AddComment("Subsection size");
OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4);
OS.EmitLabel(BeginLabel);
return EndLabel;
}
void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) {
OS.EmitLabel(EndLabel);
// Every subsection must be aligned to a 4-byte boundary.
OS.EmitValueToAlignment(4);
}
static StringRef getSymbolName(SymbolKind SymKind) {
for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames())
if (EE.Value == SymKind)
return EE.Name;
return "";
}
MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) {
MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(),
*EndLabel = MMI->getContext().createTempSymbol();
OS.AddComment("Record length");
OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
OS.EmitLabel(BeginLabel);
if (OS.isVerboseAsm())
OS.AddComment("Record kind: " + getSymbolName(SymKind));
OS.EmitIntValue(unsigned(SymKind), 2);
return EndLabel;
}
void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) {
// MSVC does not pad out symbol records to four bytes, but LLVM does to avoid
// an extra copy of every symbol record in LLD. This increases object file
// size by less than 1% in the clang build, and is compatible with the Visual
// C++ linker.
OS.EmitValueToAlignment(4);
OS.EmitLabel(SymEnd);
}
void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) {
OS.AddComment("Record length");
OS.EmitIntValue(2, 2);
if (OS.isVerboseAsm())
OS.AddComment("Record kind: " + getSymbolName(EndKind));
OS.EmitIntValue(unsigned(EndKind), 2); // Record Kind
}
void CodeViewDebug::emitDebugInfoForUDTs(
ArrayRef<std::pair<std::string, const DIType *>> UDTs) {
for (const auto &UDT : UDTs) {
const DIType *T = UDT.second;
assert(shouldEmitUdt(T));
MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT);
OS.AddComment("Type");
OS.EmitIntValue(getCompleteTypeIndex(T).getIndex(), 4);
emitNullTerminatedSymbolName(OS, UDT.first);
endSymbolRecord(UDTRecordEnd);
}
}
void CodeViewDebug::collectGlobalVariableInfo() {
DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *>
GlobalMap;
for (const GlobalVariable &GV : MMI->getModule()->globals()) {
SmallVector<DIGlobalVariableExpression *, 1> GVEs;
GV.getDebugInfo(GVEs);
for (const auto *GVE : GVEs)
GlobalMap[GVE] = &GV;
}
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
for (const MDNode *Node : CUs->operands()) {
const auto *CU = cast<DICompileUnit>(Node);
for (const auto *GVE : CU->getGlobalVariables()) {
const DIGlobalVariable *DIGV = GVE->getVariable();
const DIExpression *DIE = GVE->getExpression();
// Emit constant global variables in a global symbol section.
if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) {
CVGlobalVariable CVGV = {DIGV, DIE};
GlobalVariables.emplace_back(std::move(CVGV));
}
const auto *GV = GlobalMap.lookup(GVE);
if (!GV || GV->isDeclarationForLinker())
continue;
DIScope *Scope = DIGV->getScope();
SmallVector<CVGlobalVariable, 1> *VariableList;
if (Scope && isa<DILocalScope>(Scope)) {
// Locate a global variable list for this scope, creating one if
// necessary.
auto Insertion = ScopeGlobals.insert(
{Scope, std::unique_ptr<GlobalVariableList>()});
if (Insertion.second)
Insertion.first->second = llvm::make_unique<GlobalVariableList>();
VariableList = Insertion.first->second.get();
} else if (GV->hasComdat())
// Emit this global variable into a COMDAT section.
VariableList = &ComdatVariables;
else
// Emit this global variable in a single global symbol section.
VariableList = &GlobalVariables;
CVGlobalVariable CVGV = {DIGV, GV};
VariableList->emplace_back(std::move(CVGV));
}
}
}
void CodeViewDebug::emitDebugInfoForGlobals() {
// First, emit all globals that are not in a comdat in a single symbol
// substream. MSVC doesn't like it if the substream is empty, so only open
// it if we have at least one global to emit.
switchToDebugSectionForSymbol(nullptr);
if (!GlobalVariables.empty()) {
OS.AddComment("Symbol subsection for globals");
MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
emitGlobalVariableList(GlobalVariables);
endCVSubsection(EndLabel);
}
// Second, emit each global that is in a comdat into its own .debug$S
// section along with its own symbol substream.
for (const CVGlobalVariable &CVGV : ComdatVariables) {
const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>();
MCSymbol *GVSym = Asm->getSymbol(GV);
OS.AddComment("Symbol subsection for " +
Twine(GlobalValue::dropLLVMManglingEscape(GV->getName())));
switchToDebugSectionForSymbol(GVSym);
MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols);
// FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
emitDebugInfoForGlobal(CVGV);
endCVSubsection(EndLabel);
}
}
void CodeViewDebug::emitDebugInfoForRetainedTypes() {
NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu");
for (const MDNode *Node : CUs->operands()) {
for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) {
if (DIType *RT = dyn_cast<DIType>(Ty)) {
getTypeIndex(RT);
// FIXME: Add to global/local DTU list.
}
}
}
}
// Emit each global variable in the specified array.
void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) {
for (const CVGlobalVariable &CVGV : Globals) {
// FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions.
emitDebugInfoForGlobal(CVGV);
}
}
void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) {
const DIGlobalVariable *DIGV = CVGV.DIGV;
if (const GlobalVariable *GV =
CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) {
// DataSym record, see SymbolRecord.h for more info. Thread local data
// happens to have the same format as global data.
MCSymbol *GVSym = Asm->getSymbol(GV);
SymbolKind DataSym = GV->isThreadLocal()
? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32
: SymbolKind::S_GTHREAD32)
: (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32
: SymbolKind::S_GDATA32);
MCSymbol *DataEnd = beginSymbolRecord(DataSym);
OS.AddComment("Type");
OS.EmitIntValue(getCompleteTypeIndex(DIGV->getType()).getIndex(), 4);
OS.AddComment("DataOffset");
OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0);
OS.AddComment("Segment");
OS.EmitCOFFSectionIndex(GVSym);
OS.AddComment("Name");
const unsigned LengthOfDataRecord = 12;
emitNullTerminatedSymbolName(OS, DIGV->getName(), LengthOfDataRecord);
endSymbolRecord(DataEnd);
} else {
// FIXME: Currently this only emits the global variables in the IR metadata.
// This should also emit enums and static data members.
const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>();
assert(DIE->isConstant() &&
"Global constant variables must contain a constant expression.");
uint64_t Val = DIE->getElement(1);
MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT);
OS.AddComment("Type");
OS.EmitIntValue(getTypeIndex(DIGV->getType()).getIndex(), 4);
OS.AddComment("Value");
// Encoded integers shouldn't need more than 10 bytes.
uint8_t data[10];
BinaryStreamWriter Writer(data, llvm::support::endianness::little);
CodeViewRecordIO IO(Writer);
cantFail(IO.mapEncodedInteger(Val));
StringRef SRef((char *)data, Writer.getOffset());
OS.EmitBinaryData(SRef);
OS.AddComment("Name");
const DIScope *Scope = DIGV->getScope();
// For static data members, get the scope from the declaration.
if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>(
DIGV->getRawStaticDataMemberDeclaration()))
Scope = MemberDecl->getScope();
emitNullTerminatedSymbolName(OS,
getFullyQualifiedName(Scope, DIGV->getName()));
endSymbolRecord(SConstantEnd);
}
}
| 37.542505 | 108 | 0.689402 | [
"object",
"vector",
"model"
] |
33a7a7a0ec083943f5877ad3316335e32f2865cf | 53,022 | cpp | C++ | golg__g1_render.cpp | poikilos/golgotha | d3184dea6b061f853423e0666dba23218042e5ba | [
"CC0-1.0"
] | 5 | 2015-12-09T20:37:49.000Z | 2021-08-10T08:06:29.000Z | golg__g1_render.cpp | poikilos/golgotha | d3184dea6b061f853423e0666dba23218042e5ba | [
"CC0-1.0"
] | 13 | 2021-09-20T16:25:30.000Z | 2022-03-17T04:59:40.000Z | golg__g1_render.cpp | poikilos/golgotha | d3184dea6b061f853423e0666dba23218042e5ba | [
"CC0-1.0"
] | 5 | 2016-01-04T22:54:22.000Z | 2021-09-20T16:09:03.000Z | /********************************************************************** <BR>
This file is part of Crack dot Com's free source code release of
Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for
information about compiling & licensing issues visit this URL</a>
<PRE> If that doesn't help, contact Jonathan Clark at
golgotha_source@usa.net (Subject should have "GOLG" in it)
***********************************************************************/
#include "pch.h"
#include "controller.h"
#include "map.h"
#include "window/win_evt.h"
#include "time/profile.h"
#include "menu/menu.h"
#include "menu/textitem.h"
#include "window/style.h"
#include "time/time.h"
#include "resources.h"
#include "input.h"
#include "mess_id.h"
#include "sound_man.h"
#include "g1_speed.h"
#include "remove_man.h"
#include "image/color.h"
#include "light.h"
#include "statistics.h"
#include "render/r1_api.h"
#include "render/r1_clip.h"
#include "math/random.h"
#include "math/pi.h"
#include "math/angle.h"
#include "math/trig.h"
#include "math/d_transform.h"
#include "g1_render.h"
#include "tile.h"
#include "g1_tint.h"
#include "time/profile.h"
#include "g1_texture_id.h"
#include "g1_tint.h"
#include "objs/map_piece.h"
#include "objs/stank.h"
#include "lisp/lisp.h"
#include "map_vert.h"
#include "loaders/load.h"
#include "render/r1_font.h"
#include "player.h"
#include "octree.h"
static i4_profile_class pf_render_object_transform("render_object (transform)"),
//pf_render_object_light("render_object (light)"),
pf_render_object_pack("render_object (project/pack)"),
pf_render_sprite("g1_render::render_sprite"),
pf_render_draw_outline("g1_render::draw_outline"),
pf_post_draw_quads("g1_render::post_draw_quads"),
pf_add_translucent_trail("g1_render::add_trans_trail"),
pf_draw_building("g1_render::draw_building"),
pf_draw_octree("render_octree");
const sw32 max_post_draw_quads = 1024;
static g1_post_draw_quad_class g1_post_draw_quads[max_post_draw_quads];
static sw32 g1_num_post_draw_quads = 0;
const sw32 max_post_draw_verts = max_post_draw_quads*4;
static r1_vert g1_post_draw_verts[max_post_draw_verts];
static sw32 g1_num_post_draw_verts = 0;
struct g1_post_draw_sprite_struct
{
r1_texture_handle tex;
float z;
float s1, t1, s2, t2;
float x1,y1,x2,y2;
} g1_post_draw_sprites[G1_MAX_SPRITES];
int g1_t_post_draw_sprites=0;
g1_render_class g1_render;
//this is used for the damage/blackening effect of hurt vehicles
static w8 charred_array[8] =
{
8|1|128|4|32|2|64,
8|1|128|4|32|2,
8|1|128|4|32,
8|1|128|4,
8|1|128,
8|1,
8,
0
};
i4_bool g1_render_class::main_draw=i4_F;
i4_float g1_render_class::scale_x,
g1_render_class::scale_y,
g1_render_class::ooscale_x,
g1_render_class::ooscale_y,
g1_render_class::center_x,
g1_render_class::center_y;
sw8 g1_render_class::render_damage_level = -1;
r1_render_api_class * g1_render_class::r_api;
float g1_render_class::calculate_frame_ratio()
{
if (g1_map_is_loaded())
{
i4_time_class now;
if (g1_resources.paused)
{
frame_ratio=1.0f;
}
else
{
frame_ratio=1.0f+now.milli_diff(g1_get_map()->tick_time)*G1_HZ/1000.0f;
}
if (frame_ratio>1)
{
frame_ratio=1;
}
}
else
{
frame_ratio=0;
}
return frame_ratio;
}
// this is the default function for handling tinted polygons
g1_quad_class *g1_tint_modify_function(g1_quad_class * in,
g1_player_type player)
{
g1_render.r_api->set_color_tint(g1_player_tint_handles[player]);
return in;
}
void g1_get_ambient_function(i4_transform_class * object_to_world,
i4_float &ar, i4_float &ag, i4_float &ab)
{
g1_get_map()->get_illumination_light(object_to_world->t.x,
object_to_world->t.y, ar,ag,ab);
}
//Does this also need to be changed to double precision?
void fast_transform(i4_transform_class * t,const i4_3d_vector &src, r1_3d_point_class &dst)
{
#ifndef _WINDOWS
dst.x = t->x.x*src.x + t->y.x*src.y + t->z.x*src.z + t->t.x;
dst.y = t->x.y*src.x + t->y.y*src.y + t->z.y*src.z + t->t.y;
dst.z = t->x.z*src.x + t->y.z*src.y + t->z.z*src.z + t->t.z;
#else
_asm
{
mov eax, t
mov ecx, src
mov edx, dst
//optimized transformation: 34 cycles
//compute t->x.x*src.x, t->x.y*src.x, t->x.z*src.x
fld dword ptr [ecx+0] ; starts & ends on cycle 0
fmul dword ptr [eax+0] ; starts on cycle 1
fld dword ptr [ecx+0] ; starts & ends on cycle 2
fmul dword ptr [eax+4] ; starts on cycle 3
fld dword ptr [ecx+0] ; starts & ends on cycle 4
fmul dword ptr [eax+8] ; starts on cycle 5
//compute t->y.x*src.y, t->y.y*src.y, t->y.z*src.y
fld dword ptr [ecx+4] ; starts & ends on cycle 6
fmul dword ptr [eax+12] ; starts on cycle 7
fld dword ptr [ecx+4] ; starts & ends on cycle 8
fmul dword ptr [eax+16] ; starts on cycle 9
fld dword ptr [ecx+4] ; starts & ends on cycle 10
fmul dword ptr [eax+20] ; starts on cycle 11
//st0 st1 st2 st3 st4 st5
//t->y.z*src.y t->y.y*src.y t->y.x*src.y t->x.z*src.x t->x.y*src.x t->x.x*src.x
fxch st(2) ; no cost
//st0 st1 st2 st3 st4 st5
//t->y.x*src.y t->y.y*src.y t->y.z*src.y t->x.z*src.x t->x.y*src.x t->x.x*src.x
faddp st(5),st(0) ; starts on cycle 12
//st0 st1 st2 st3 st4
//t->y.y*src.y t->y.z*src.y t->x.z*src.x t->x.y*src.x t->x.x*src.x+
// t->y.x*src.y
faddp st(3),st(0) ; starts on cycle 13
//st0 st1 st2 st3
//t->y.z*src.y t->x.z*src.x t->x.y*src.x+ t->x.x*src.x+
// t->y.y*src.y t->y.x*src.y
faddp st(1),st(0) ; starts on cycle 14
//st0 st1 st2
//t->x.z*src.x+ t->x.y*src.x+ t->x.x*src.x+
//t->y.z*src.y t->y.y*src.y t->y.x*src.y
//compute t->z.x*src.z, t->z.y*src.z, t->z.z*src.z
fld dword ptr [ecx+8] ; starts & ends on cycle 15
fmul dword ptr [eax+24] ; starts on cycle 16
fld dword ptr [ecx+8] ; starts & ends on cycle 17
fmul dword ptr [eax+28] ; starts on cycle 18
fld dword ptr [ecx+8] ; starts & ends on cycle 19
fmul dword ptr [eax+32] ; starts on cycle 20
//st0 st1 st2 st3 st4 st5
//t->z.z*src.z t->z.y*src.z t->z.x*src.z t->x.z*src.x+ t->x.y*src.x+ t->x.x*src.x+
// t->y.z*src.y t->y.y*src.y t->y.x*src.y
fxch st(2) ; no cost
faddp st(5),st(0) ; starts on cycle 21
//st0 st1 st2 st3 st4
//t->z.y*src.z t->z.z*src.z t->x.z*src.x+ t->x.y*src.x+ t->x.x*src.x+
// t->y.z*src.y t->y.y*src.y t->y.x*src.y+
// t->z.x*src.z
faddp st(3),st(0) ; starts on cycle 22
//st0 st1 st2 st3
//t->z.z*src.z t->x.z*src.x+ t->x.y*src.x+ t->x.x*src.x+
// t->y.z*src.y t->y.y*src.y+ t->y.x*src.y+
// t->z.y*src.z t->z.x*src.z
faddp st(1),st(0) ; starts on cycle 23
//st0 st1 st2
//t->x.z*src.x+ t->x.y*src.x+ t->x.x*src.x+
//t->y.z*src.y+ t->y.y*src.y+ t->y.x*src.y+
//t->z.z*src.z t->z.y*src.z t->z.x*src.z
fxch st(2) ; no cost
//st0 st1 st2
//t->x.x*src.x+ t->x.y*src.x+ t->x.z*src.x+
//t->y.x*src.y+ t->y.y*src.y+ t->y.z*src.y+
//t->z.x*src.z t->z.y*src.z t->z.z*src.z
fadd dword ptr [eax+36] ; starts on cycle 24
fxch st(1) ; starts on cycle 25
//st0 st1 st2
//t->x.y*src.x+ dest_x t->x.z*src.x+
//t->y.y*src.y+ t->y.z*src.y+
//t->z.y*src.z t->z.z*src.z
fadd dword ptr [eax+40] ; starts on cycle 26
fxch st(2) ; no cost
//st0 st1 st2
//t->x.z*src.x+ dest_x dest_y
//t->y.z*src.y+
//t->z.z*src.z
fadd dword ptr [eax+44] ; starts on cycle 27
fxch st(1) ; no cost
//st0 st1 st2
//dest_x dest_z dest_y
fstp dword ptr [edx+0] ; starts on cycle 28, ends on cycle 29
fstp dword ptr [edx+8] ; starts on cycle 30, ends on cycle 31
fstp dword ptr [edx+4] ; starts on cycle 32, ends on cycle 33
}
#endif
}
void g1_render_class::uninstall_font()
{
if (rendered_font)
{
delete rendered_font;
rendered_font=0;
}
}
void g1_render_class::install_font()
{
uninstall_font();
i4_image_class * im=i4_load_image("bitmaps/golg_font_18.bmp");
if (im)
{
rendered_font=new r1_font_class(r_api, im);
delete im;
}
}
static int g1_quad_sorter(g1_quad_class * const * a,
g1_quad_class * const * b)
{
if (*a==*b)
{
return 0;
}
if (*a>*b) //if a > b we want that a comes before b
{
return -1;
}
else
{
return 1;
}
}
i4_bool g1_render_class::prepare_octree_rendering(i4_array<g1_quad_class *> &qif,
g1_quad_object_class * obj,
g1_vert_class * src_vert,
i4_transform_class * tf,
i4_transform_class * object_to_world,
w8 &ANDCODE,
w8 &ORCODE)
{
g1_octree * oc=obj->octree;
//quads in frustrum
pf_draw_octree.start();
if (oc->DrawOctree(tf,qif,object_to_world ? 0 : 1)==i4_F)
{
pf_draw_octree.stop();
return i4_F;
}
//now: We first sort qif, such that we can later drop duplicate
//quads.
//Then we iterate trough it and grab all the vertices
//from the used quads, since we only need to transform those.
//we have to initialize the vertices array, such that we
//can check their validity later
//hmmm... this is quite expensive if num_vertices is large
//(which is very probable)
memset(t_vertices,0,(obj->num_vertex+1)*sizeof(r1_vert));
if (qif.empty())
{
pf_draw_octree.stop();
return i4_T; //will break completelly out, as andcode is still 0xff
}
qif.sort(g1_quad_sorter);
g1_quad_class * curquad;
g1_vert_class * src_v=0;
i4_3d_vector t_light;
i4_float ar=0.5f,ag=0.5f,ab=0.5f;
float dir_int=g1_lights.directional_intensity;
// get the ambient contribution from the map at the object's center point
i4_3d_vector light = g1_lights.direction;
t_light=light;
if (object_to_world)
{
//transform light into object space for lighting
//Warn: this doesn't work if no map is loaded!
get_ambient(object_to_world, ar,ag,ab);
object_to_world->inverse_transform_3x3(light,t_light);
}
w32 vertex;
w32 n_vert;
int vertid;
int curquadidx;
r1_vert * v;
w8 code;
i4_float ooz,dot,reflected_intensity;
for (curquadidx=0; curquadidx<qif.size(); curquadidx++)
{
curquad=qif[curquadidx];
if ((curquadidx>0)&&(curquad==qif[curquadidx-1]))
{
continue;
} //skip duplicate quads
n_vert=curquad->num_verts();
for (vertex=0; vertex<n_vert; vertex++)
{
vertid=curquad->vertex_ref[vertex];
v=&t_vertices[vertid];
if (v->flags)
{
continue;
}
src_v=&src_vert[vertid];
fast_transform(tf,src_v->v,v->v);
code = r1_calc_outcode(v);
ANDCODE &= code;
ORCODE |= code;
ooz = r1_ooz(v->v.z);
v->px = v->v.x * ooz * center_x + center_x;
v->py = v->v.y * ooz * center_y + center_y;
v->w = ooz;
dot=-src_v->normal.dot(t_light);
reflected_intensity = dir_int * dot;
if (reflected_intensity<0)
{
reflected_intensity=0;
}
v->r = reflected_intensity * dir_int + ar;
if (v->r>1.0)
{
v->r=1.0;
}
v->g = reflected_intensity * dir_int + ag;
if (v->g>1.0)
{
v->g=1.0;
}
v->b = reflected_intensity * dir_int + ab;
if (v->b>1.0)
{
v->b=1.0;
}
v->a = 1.0;
v->flags=1;
}
}
pf_draw_octree.stop();
return i4_T;
}
void g1_render_class::ensure_capacity(int num_vertices)
{
if (num_vertices>max_t_vertices)
{
max_t_vertices=num_vertices+50;
t_vertices=(r1_vert *)realloc(t_vertices,max_t_vertices*sizeof(r1_vert));
}
}
void g1_render_class::render_object(g1_quad_object_class * obj,
i4_transform_class * object_to_view,
i4_transform_class * object_to_world,
i4_float texture_scale,
int player_num,
sw32 current_frame,
g1_screen_box * bound_box,
w32 option_flags)
{
if (!obj)
{
//its not 100% clear in wich rare cases this happens
return;
}
g1_stat_counter.increment(g1_statistics_counter_class::OBJECTS);
int i,j, /*k,*/ num_vertices;
//r1_vert* t_vertices=0;
//int src_quad[4];
i4_transform_class view_transform;
num_vertices = obj->num_vertex;
ensure_capacity(num_vertices+1);
r1_vert * v = t_vertices;
g1_vert_class * src_vert = obj->get_verts(0, current_frame);
w8 ANDCODE = 0xFF;
w8 ORCODE = 0;
g1_vert_class * src_v=src_vert;
//pf_render_object_transform.start();
//get this vector before we warp the transform
i4_3d_vector cam_in_object_space;
object_to_view->inverse_transform(i4_3d_vector(0,0,0),cam_in_object_space);
view_transform.x.x = object_to_view->x.x * scale_x;
view_transform.x.y = object_to_view->x.y * scale_y;
view_transform.x.z = object_to_view->x.z;
view_transform.y.x = object_to_view->y.x * scale_x;
view_transform.y.y = object_to_view->y.y * scale_y;
view_transform.y.z = object_to_view->y.z;
view_transform.z.x = object_to_view->z.x * scale_x;
view_transform.z.y = object_to_view->z.y * scale_y;
view_transform.z.z = object_to_view->z.z;
view_transform.t.x = object_to_view->t.x * scale_x;
view_transform.t.y = object_to_view->t.y * scale_y;
view_transform.t.z = object_to_view->t.z;
//if we have an octree, we need to iterate over a
//limited set of polys and vertices only.
quad_object_list.clear();
i4_bool use_ot=i4_F;
if (obj->octree)
{
//hiddenly modificates the t_vertices array
use_ot=prepare_octree_rendering(quad_object_list,obj,src_vert,
&view_transform,
object_to_world,
ANDCODE,ORCODE);
if (ANDCODE&&use_ot)
{
return;
}
}
if (!obj->octree || (use_ot==i4_F))
{
for (i=0; i<num_vertices; i++, src_v++, v++)
{
fast_transform(&view_transform,src_v->v,v->v);
//v->v.x *= scale_x; //this is accomplished by the above matrix multiplies
//v->v.y *= scale_y;
w8 code = r1_calc_outcode(v);
ANDCODE &= code;
ORCODE |= code;
if (!code)
{
//valid point
i4_float ooz = r1_ooz(v->v.z);
v->px = v->v.x * ooz * center_x + center_x;
v->py = v->v.y * ooz * center_y + center_y;
v->w = ooz;
if (option_flags & RENDER_PROJECTTOPLANE)
{
v->w=r1_ooz(r1_near_clip_z);
}
}
}
//pf_render_object_transform.stop();
if (ANDCODE)
{
//free(t_vertices);
return;
}
//pf_render_object_light.start();
//IMPORTANT
//we need this transform to do lighting
if (object_to_world)
{
//worldspace light vector
i4_3d_vector light = g1_lights.direction;
i4_3d_vector t_light;
// get the ambient contribution from the map at the object's center point
i4_float ar,ag,ab;
get_ambient(object_to_world, ar,ag,ab);
float dir_int=g1_lights.directional_intensity;
//transform light into object space for lighting
object_to_world->inverse_transform_3x3(light,t_light);
src_vert = obj->get_verts(0,current_frame);
v = t_vertices;
//We'll need to further investigate here, since it's no more
//acceptable to iterate over all vertices if there is an octree
//(num_vertices might be several hundred thousand)
for (i=0; i<num_vertices; i++, v++)
{
// i4_float reflected_intensity = 1.0;
i4_float dot=-src_vert[i].normal.dot(t_light);
i4_float reflected_intensity = g1_lights.directional_intensity * dot;
if (reflected_intensity<0)
{
reflected_intensity=0;
}
v->r = reflected_intensity * dir_int + ar;
if (v->r>1.0)
{
v->r=1.0;
}
v->g = reflected_intensity * dir_int + ag;
if (v->g>1.0)
{
v->g=1.0;
}
v->b = reflected_intensity * dir_int + ab;
if (v->b>1.0)
{
v->b=1.0;
}
v->a = 1.0;
}
}
else
{
v = t_vertices;
for (i=0; i<num_vertices; i++, v++)
{
v->r = v->g = v->b = 1.f; //g1_lights.ambient_intensity;
v->a = 1.0f; /// we will decrease this... (was 1.0, just to remember)
//ok? let's try this?
}
}
if (render_damage_level != -1)
{
//set their lighting values to 1
v = t_vertices;
for (i=0; i<num_vertices; i++, v++)
{
if ((1<<(i&7)) & charred_array[render_damage_level])
{
v->r = v->g = v->b = 0;
}
}
}
} //else not octree
//pf_render_object_light.stop();
pf_render_object_pack.start();
g1_quad_class * q_ptr = obj->quad, * q;
int allquads=obj->num_quad;
if (use_ot)
{
allquads=quad_object_list.size();
q_ptr=quad_object_list[0];
}
for (i=0; i<allquads; i++, q_ptr++)
{
if (use_ot)
{
q_ptr=quad_object_list[i];
if (i>0 && q_ptr==quad_object_list[i-1])
{
//we've already drawn this quad.
continue;
}
}
sw32 num_poly_verts = q_ptr->num_verts();
i4_3d_vector cam_to_pt = src_vert[q_ptr->vertex_ref[0]].v;
cam_to_pt -= cam_in_object_space;
float dot = cam_to_pt.dot(q_ptr->normal);
if (dot<0||q_ptr->get_flags(g1_quad_class::BOTHSIDED))
{
if (g1_tint!=G1_TINT_OFF && g1_hurt_tint==0)
{
if ((q_ptr->get_flags(g1_quad_class::TINT)||(g1_tint==G1_TINT_ALL))
&& player_num!=-1)
{
q=tint_modify(q_ptr, player_num);
}
else
{
r_api->set_color_tint(0);
q=q_ptr;
}
}
else
{
q=q_ptr;
}
// copy in the texture coordinates
for (j=0; j<num_poly_verts; j++)
{
int ref=q->vertex_ref[j];
//src_quad[j]=ref;
v = &t_vertices[ref];
v->s = q->u[j];
v->t = q->v[j];
}
if (ORCODE==0)
{
float nearest_w = 0;
if (bound_box)
{
for (j=0; j<num_poly_verts; j++)
{
r1_vert * temp_vert = &t_vertices[q->vertex_ref[j]];
float ooz = temp_vert->w;
if (ooz > nearest_w)
{
nearest_w=ooz;
}
if (temp_vert->px < bound_box->x1)
{
bound_box->x1 = temp_vert->px;
}
if (temp_vert->px > bound_box->x2)
{
bound_box->x2 = temp_vert->px;
}
if (temp_vert->py < bound_box->y1)
{
bound_box->y1 = temp_vert->py;
}
if (temp_vert->py > bound_box->y2)
{
bound_box->y2 = temp_vert->py;
}
if (temp_vert->v.z > bound_box->z2)
{
bound_box->z2 = temp_vert->v.z;
}
if (temp_vert->v.z < bound_box->z1)
{
bound_box->z1 = temp_vert->v.z;
bound_box->w = ooz;
}
}
}
else
{
for (j=0; j<num_poly_verts; j++)
{
r1_vert * temp_vert = &t_vertices[q->vertex_ref[j]];
float ooz = temp_vert->w;
if (ooz > nearest_w)
{
nearest_w=ooz;
}
}
}
i4_float twidth = nearest_w * q->texture_scale * texture_scale * center_x * 2;
r_api->use_texture(q->material_ref, i4_f_to_i(twidth), current_frame);
g1_stat_counter.increment(g1_statistics_counter_class::OBJECT_POLYS);
g1_stat_counter.increment(g1_statistics_counter_class::TOTAL_POLYS);
r_api->render_poly(num_poly_verts,t_vertices,q->vertex_ref);
}
else
{
r1_vert temp_buf_1[64];
r1_vert temp_buf_2[64];
r1_vert * clipped_poly;
clipped_poly = r_api->clip_poly(&num_poly_verts,
t_vertices,
q->vertex_ref,
temp_buf_1,
temp_buf_2,
R1_CLIP_NO_CALC_OUTCODE
);
if (clipped_poly && num_poly_verts>=3)
{
float nearest_w = 0;
if (!bound_box)
{
r1_vert * temp_vert = clipped_poly;
for (j=0; j<num_poly_verts; j++, temp_vert++)
{
i4_float ooz = r1_ooz(temp_vert->v.z);
temp_vert->w = ooz;
temp_vert->px = temp_vert->v.x * ooz * center_x + center_x;
temp_vert->py = temp_vert->v.y * ooz * center_y + center_y;
if (ooz > nearest_w)
{
nearest_w=ooz;
}
}
}
else
{
r1_vert * temp_vert = clipped_poly;
for (j=0; j<num_poly_verts; j++,temp_vert++)
{
float ooz = r1_ooz(temp_vert->v.z);
temp_vert->w = ooz;
temp_vert->px = temp_vert->v.x * ooz * center_x + center_x;
temp_vert->py = temp_vert->v.y * ooz * center_y + center_y;
if (ooz > nearest_w)
{
nearest_w=ooz;
}
if (temp_vert->px < bound_box->x1)
{
bound_box->x1 = temp_vert->px;
}
if (temp_vert->px > bound_box->x2)
{
bound_box->x2 = temp_vert->px;
}
if (temp_vert->py < bound_box->y1)
{
bound_box->y1 = temp_vert->py;
}
if (temp_vert->py > bound_box->y2)
{
bound_box->y2 = temp_vert->py;
}
if (temp_vert->v.z > bound_box->z2)
{
bound_box->z2 = temp_vert->v.z;
}
if (temp_vert->v.z < bound_box->z1)
{
bound_box->z1 = temp_vert->v.z;
bound_box->w = ooz;
}
}
}
i4_float twidth = nearest_w * q->texture_scale * texture_scale * center_x * 2;
r_api->use_texture(q->material_ref, i4_f_to_i(twidth), current_frame);
r_api->render_poly(num_poly_verts,clipped_poly);
g1_stat_counter.increment(g1_statistics_counter_class::OBJECT_POLYS);
g1_stat_counter.increment(g1_statistics_counter_class::TOTAL_POLYS);
}
}
}
}
if (g1_tint!=G1_TINT_OFF && g1_hurt_tint==0)
{
r_api->set_color_tint(0);
}
//free(t_vertices);
pf_render_object_pack.stop();
}
void g1_render_class::render_object_polys(g1_quad_object_class * obj,
i4_transform_class * object_to_view,
sw32 current_frame)
{
int i,j, /*k,*/ num_vertices;
//r1_vert* t_vertices=0;
//int src_quad[4];
i4_transform_class view_transform;
num_vertices = obj->num_vertex;
if (num_vertices>max_t_vertices)
{
max_t_vertices=num_vertices+50;
t_vertices=(r1_vert *)realloc(t_vertices,max_t_vertices*sizeof(r1_vert));
}
r1_vert * v = t_vertices;
g1_vert_class * src_vert = obj->get_verts(0, current_frame);
w8 ANDCODE = 0xFF;
w8 ORCODE = 0;
g1_vert_class * src_v=src_vert;
pf_render_object_transform.start();
view_transform.x.x = object_to_view->x.x * scale_x;
view_transform.x.y = object_to_view->x.y * scale_y;
view_transform.x.z = object_to_view->x.z;
view_transform.y.x = object_to_view->y.x * scale_x;
view_transform.y.y = object_to_view->y.y * scale_y;
view_transform.y.z = object_to_view->y.z;
view_transform.z.x = object_to_view->z.x * scale_x;
view_transform.z.y = object_to_view->z.y * scale_y;
view_transform.z.z = object_to_view->z.z;
view_transform.t.x = object_to_view->t.x * scale_x;
view_transform.t.y = object_to_view->t.y * scale_y;
view_transform.t.z = object_to_view->t.z;
i4_float adjuster = -0.01f;
for (i=0; i<num_vertices; i++, src_v++, v++)
{
fast_transform(&view_transform,src_v->v,v->v);
//v->v.x *= scale_x; //this is accomplished by the above matrix multiplies
//v->v.y *= scale_y;
w8 code = r1_calc_outcode(v);
ANDCODE &= code;
ORCODE |= code;
if (!code)
{
//valid point
i4_float ooz = r1_ooz(v->v.z);
i4_float ooz_adjusted = r1_ooz(v->v.z + adjuster);
v->px = v->v.x * ooz * center_x + center_x;
v->py = v->v.y * ooz * center_y + center_y;
v->w = ooz_adjusted;
v->a = v->r = v->g = v->b = 1.f;
}
}
pf_render_object_transform.stop();
if (ANDCODE)
{
//free(t_vertices);
return;
}
pf_render_object_pack.start();
g1_quad_class * q_ptr = obj->quad;
for (i=0; i<obj->num_quad; i++, q_ptr++)
{
sw32 num_poly_verts = q_ptr->num_verts();
if (ORCODE==0)
{
r_api->render_poly(num_poly_verts,t_vertices,q_ptr->vertex_ref);
}
else
{
r1_vert temp_buf_1[64];
r1_vert temp_buf_2[64];
r1_vert * clipped_poly;
clipped_poly = r_api->clip_poly(&num_poly_verts,
t_vertices,
q_ptr->vertex_ref,
temp_buf_1,
temp_buf_2,
R1_CLIP_NO_CALC_OUTCODE
);
if (clipped_poly && num_poly_verts>=3)
{
r1_vert * temp_vert = clipped_poly;
for (j=0; j<num_poly_verts; j++, temp_vert++)
{
float ooz = r1_ooz(temp_vert->v.z);
float ooz_adjusted = r1_ooz(temp_vert->v.z + adjuster);
temp_vert->px = temp_vert->v.x * ooz * center_x + center_x;
temp_vert->py = temp_vert->v.y * ooz * center_y + center_y;
temp_vert->w = ooz_adjusted;
}
r_api->render_poly(num_poly_verts,clipped_poly);
}
}
}
//free(t_vertices);
pf_render_object_pack.stop();
}
void g1_render_class::render_3d_line(const i4_3d_point_class &p1,
const i4_3d_point_class &p2,
i4_color color1,
i4_color color2,
i4_transform_class * t,
i4_bool draw_in_front_of_everything)
{
r1_vert v[2];
project_point(p1, v[0], t);
project_point(p2, v[1], t);
// Ignored for now, since it doesn't work (any line using this flag is always clipped away)
//if (draw_in_front_of_everything)
//{
// v[0].v.z=r1_near_clip_z;//g1_near_z_range();
// v[1].v.z=r1_near_clip_z;//g1_near_z_range();
//
// float ooz = r1_ooz(r1_near_clip_z);//r1_ooz(g1_near_z_range());
//
// v[0].w = r1_near_clip_z;
// v[1].w = r1_near_clip_z;
//}
v[0].r=g1_table_0_255_to_0_1[(color1&0xff0000)>>16];
v[0].g=g1_table_0_255_to_0_1[(color1&0xff00)>>8];
v[0].b=g1_table_0_255_to_0_1[(color1&0xff)>>0];
v[0].a=1;
v[0].s=0;
v[0].t=0;
v[1].r=g1_table_0_255_to_0_1[(color2&0xff0000)>>16];
v[1].g=g1_table_0_255_to_0_1[(color2&0xff00)>>8];
v[1].b=g1_table_0_255_to_0_1[(color2&0xff)>>0];
v[1].a=1;
v[1].s=0;
v[1].t=0;
r1_shading_type oldshade=r_api->get_shade_mode();
r1_alpha_type oldalpha=r_api->get_alpha_mode();
r_api->set_shading_mode(R1_COLORED_SHADING);
r_api->set_alpha_mode(R1_ALPHA_DISABLED);
r_api->disable_texture();
r1_clip_render_lines(1, v, center_x, center_y, r_api);
//restore old modes. Since lines are realy seldom used primitives,
//this is no performance problem compared to what might happen if
//the caller unexspectedly finds the render device in a new state.
r_api->set_shading_mode(oldshade);
r_api->set_alpha_mode(oldalpha);
//r_api->use_default_texture();
//r_api->set_constant_color(0xffffff);
}
void g1_render_class::render_2d_point(int px, int py, i4_color color)
{
if (px>0 && py>0 && px<center_x*2-1 && py<center_y*2-1)
{
r_api->r1_render_api_class::clear_area(px-1,py-1,px+1,py+1,color,
r1_near_clip_z);
}
}
void g1_render_class::render_3d_point(const i4_3d_point_class &p1, i4_color color, i4_transform_class * t)
{
r1_vert v;
project_point(p1, v, t);
int ix = int (v.px),iy = int (v.py);
if (ix>0 && iy>0 && ix<center_x*2-1 && iy<center_y*2-1)
{
r_api->r1_render_api_class::clear_area(ix-1,iy-1,ix+1,iy+1,color,
v.v.z);
}
}
void g1_draw_vert_line(float x, float y1, float y2, r1_vert * v)
{
r1_vert * v1=v, * v2=v+1;
v1->px=x;
v2->px=x;
v1->py=y1;
v2->py=y2;
g1_render.r_api->render_lines(1, v);
}
void g1_draw_horz_line(float y, float x1, float x2, r1_vert * v)
{
r1_vert * v1=v, * v2=v+1;
v1->py=y;
v2->py=y;
v1->px=x1;
v2->px=x2;
g1_render.r_api->render_lines(1, v);
}
/*! The following function draws a border around a given unit
Together with a health bar indicating the remaining health of the unit
@param box The screen bounding box of the object (from the draw routine)
@param for_who The object itself
*/
void g1_render_class::draw_outline(g1_screen_box * box, g1_object_class * for_who)
{
if ((box->flags&g1_screen_box::DRAWN))
{
return;
}
box->flags|=g1_screen_box::DRAWN;
pf_render_draw_outline.start();
r1_vert line_points[3];
//memset(line_points,0,sizeof(r1_vert)*3);
sw32 width = (sw32)(center_x*2);
sw32 height = (sw32)(center_y*2);
//dunno whats up w/these.. looks like the box is ending up outside the viewport somehow
sw32 box_x1 = i4_f_to_i(box->x1);
sw32 box_y1 = i4_f_to_i(box->y1);
sw32 box_x2 = i4_f_to_i(box->x2);
sw32 box_y2 = i4_f_to_i(box->y2);
if (box_y1<6)
{
box_y1=6; //draw the health-bar even if the unit
//is at the top of the screen.
if (box_y2<8)
{
box_y2=8;
} //to avoid that the bottom becomes higher than the top
}
//box_x1++;
//box_y1++;
//box_x2--;
//box_y2--;
if (box_x1 < 0 || box_y1 < 0 || box_x2<0 || box_y2<0)
{
pf_render_draw_outline.stop();
return;
}
if (box_x2 > width || box_x1>width || box_y2 > height || box_y1 > height)
{
pf_render_draw_outline.stop();
return;
}
r_api->disable_texture();
i4_float depth = box->z1-0.1f;
i4_float oodepth = box->z1-0.1f; //box->w;
line_points[0].v.z = depth;
line_points[0].w = oodepth;
line_points[0].s=0;
line_points[0].t=0;
line_points[1].v.z = depth;
line_points[1].w = oodepth;
line_points[1].s=0;
line_points[1].t=0;
line_points[2].v.z = depth;
line_points[2].w = oodepth;
line_points[2].s=0;
line_points[2].t=0;
r_api->set_alpha_mode(R1_ALPHA_DISABLED);
if (for_who->player_num==0)
{
line_points[0].r = 0.5f; //0.25f;
line_points[0].g = 0.5f; //0.25f;
line_points[0].b = 0.5f; //0.f;
line_points[0].a = 0.5f;
line_points[1].r = 0.5f;
line_points[1].g = 0.5f;
line_points[1].b = 0.5f; //0.f;
line_points[1].a = 0.5f;
line_points[2].r = 0.5f; //0.25f;
line_points[2].g = 0.5f; //0.25f;
line_points[2].b = 0.5f; //0.f;
line_points[2].a = 0.5f;
r_api->set_constant_color(0xffffffff);
}
else
{
g1_player_info_class * p=g1_player_man.get(for_who->player_num);
float r = ((p->map_player_color >> 16) & 0xff) / 255.f;
float g = ((p->map_player_color >> 8) & 0xff) / 255.f;
float b = (p->map_player_color & 0xff) / 255.0f;
line_points[0].r = r;
line_points[0].g = g;
line_points[0].b = b;
line_points[1].r = r;
line_points[1].g = g;
line_points[1].b = b;
line_points[2].r = r;
line_points[2].g = g;
line_points[2].b = b;
r_api->set_constant_color(0xffff0000);
}
//dunno whats up w/these.. looks like the box is ending up outside the viewport somehow
//box->x1 += 1;
//box->y1 += 1;
float width_adjust = (float)((box_x2 - box_x1)/6);
float height_adjust = (float)((box_y2 - box_y1)/6);
line_points[0].px = (float)box_x1;
line_points[0].py = box_y1 + height_adjust;
line_points[1].px = (float)box_x1;
line_points[1].py = (float)box_y1;
line_points[2].px = box_x1 + width_adjust;
line_points[2].py = (float)box_y1;
r_api->disable_texture();
//The box must be at least 10 pixels wide for drawing the health.
if (for_who && (box_x1+10<=box_x2) && box_y1>=5)
{
//mp=g1_map_piece_class::cast(for_who);
if (for_who->health>0)
{
float percent=(float) ((for_who->health - for_who->get_min_health())/(float) ( for_who->get_max_health()-for_who->get_min_health() ) );
//protect against invalid health values
if (percent > 1.f)
{
percent = 1.f;
}
if (percent < 0.f)
{
percent = 0.f;
}
i4_color c;
if (percent<=0.25)
{
c=0xff0000;
} // red
else if (percent<=0.5)
{
c=0xffff00;
} // yellow
else
{
c=0x00ff00;
} // green
r_api->clear_area(box_x1, box_y1-5, box_x2, box_y1-2, 0, box->z1);
int box_w=(box_x2-1)-(box_x1+1);
r_api->clear_area(box_x1+1, box_y1-4, box_x1+1+(int)(box_w*percent), box_y1-3, c, box->z1-0.01f);
}
}
//r_api->use_default_texture();
r_api->set_shading_mode(R1_COLORED_SHADING);
r_api->render_lines(2,line_points);
line_points[0].px = box_x2 - width_adjust;
line_points[0].py = (float)box_y1;
line_points[1].px = (float)box_x2;
line_points[1].py = (float)box_y1;
line_points[2].px = (float)box_x2;
line_points[2].py = box_y1 + height_adjust;
r_api->render_lines(2,line_points);
line_points[0].px = (float)box_x2;
line_points[0].py = box_y2 - height_adjust;
line_points[1].px = (float)box_x2;
line_points[1].py = (float)box_y2;
line_points[2].px = box_x2 - width_adjust;
line_points[2].py = (float)box_y2;
r_api->render_lines(2,line_points);
line_points[0].px = box_x1 + width_adjust;
line_points[0].py = (float)box_y2;
line_points[1].px = (float)box_x1;
line_points[1].py = (float)box_y2;
line_points[2].px = (float)box_x1;
line_points[2].py = box_y2 - height_adjust;
r_api->render_lines(2,line_points);
pf_render_draw_outline.stop();
}
int g1_sprite_depth_compare(const void * a, const void * b)
{
if (((g1_post_draw_sprite_struct *)a)->z<((g1_post_draw_sprite_struct *)b)->z)
{
return -1;
}
else if (((g1_post_draw_sprite_struct *)a)->z>((g1_post_draw_sprite_struct *)b)->z)
{
return 1;
}
else
{
return 0;
}
}
sw32 g1_render_class::add_post_draw_vert(r1_vert &a)
{
g1_post_draw_verts[g1_num_post_draw_verts] = a;
g1_num_post_draw_verts++;
return (g1_num_post_draw_verts-1);
}
sw32 g1_render_class::add_post_draw_quad(g1_post_draw_quad_class &q)
{
g1_post_draw_quads[g1_num_post_draw_quads] = q;
g1_num_post_draw_quads++;
return (g1_num_post_draw_quads-1);
}
void g1_render_class::post_draw_quads()
{
int i,j;
if (g1_num_post_draw_quads)
{
pf_post_draw_quads.start();
r1_vert temp_buf_1[8];
r1_vert temp_buf_2[8];
r_api->disable_texture();
r_api->set_alpha_mode(R1_ALPHA_LINEAR);
// r_api->set_shading_mode(R1_COLORED_SHADING);
// r_api->set_write_mode(R1_COMPARE_W | R1_WRITE_COLOR);
int t = g1_num_post_draw_quads;
for (i=0; i<t; i++)
{
g1_post_draw_quad_class * q = &g1_post_draw_quads[i];
sw32 num_poly_verts = (q->vert_ref[3]==0xFFFF) ? (3) : (4);
r1_vert * clipped_poly = r_api->clip_poly(&num_poly_verts,
g1_post_draw_verts,
q->vert_ref,
temp_buf_1,
temp_buf_2,
0);
if (clipped_poly && num_poly_verts>=3)
{
for (j=0; j<num_poly_verts; j++)
{
float ooz = r1_ooz(clipped_poly[j].v.z);
clipped_poly[j].px = clipped_poly[j].v.x * ooz * center_x + center_x;
clipped_poly[j].py = clipped_poly[j].v.y * ooz * center_y + center_y;
clipped_poly[j].w = ooz;
}
r_api->render_poly(num_poly_verts,clipped_poly);
}
}
r_api->set_alpha_mode(R1_ALPHA_DISABLED);
g1_num_post_draw_quads = 0;
g1_num_post_draw_verts = 0;
pf_post_draw_quads.stop();
}
qsort(g1_post_draw_sprites, g1_t_post_draw_sprites, sizeof(g1_post_draw_sprite_struct),
g1_sprite_depth_compare);
for (i=0; i<g1_t_post_draw_sprites; i++)
{
g1_post_draw_sprite_struct * s=g1_post_draw_sprites + i;
r1_clip_render_textured_rect(s->x1,s->y1,s->x2,s->y2, s->z,
1.0,
i4_f_to_i(g1_render.center_x*2),
i4_f_to_i(g1_render.center_y*2),
s->tex, 0, g1_render.r_api, s->s1, s->t1, s->s2, s->t2);
g1_stat_counter.increment(g1_statistics_counter_class::SPRITES);
}
r_api->states_have_changed=i4_T;
r_api->flush_vert_buffer();
g1_t_post_draw_sprites=0;
}
void g1_render_class::clip_render_quad(g1_quad_class * q,
r1_vert * verts,
i4_transform_class * t,
int current_frame)
{
int i;
i4_3d_vector p;
w8 ANDCODE = 0xFF;
w8 ORCODE = 0;
for (i=0; i<4; i++)
{
int vref=q->vertex_ref[i];
r1_3d_point_class * v=&verts[vref].v;
p=i4_3d_vector(v->x, v->y, v->z);
i4_3d_vector &temp_v = (i4_3d_vector &)verts[vref].v;
t->transform(p, temp_v);
verts[vref].v.x *= scale_x;
verts[vref].v.y *= scale_y;
w8 code = r1_calc_outcode(verts+vref);
ANDCODE &= code;
}
if (ANDCODE)
{
return ;
}
sw32 num_poly_verts = 4;
r1_vert temp_buf_1[32];
r1_vert temp_buf_2[32];
r1_vert * clipped_poly = r_api->clip_poly(&num_poly_verts,
verts,
q->vertex_ref,
temp_buf_1,
temp_buf_2,
R1_CLIP_NO_CALC_OUTCODE);
if (clipped_poly && num_poly_verts>=3)
{
float nearest_w = 0;
int j;
for (j=0; j<num_poly_verts; j++)
{
float ooz = r1_ooz(clipped_poly[j].v.z);
if (ooz > nearest_w)
{
nearest_w=ooz;
}
clipped_poly[j].px = clipped_poly[j].v.x * ooz * center_x + center_x;
clipped_poly[j].py = clipped_poly[j].v.y * ooz * center_y + center_y;
clipped_poly[j].w = ooz;
}
if (q->material_ref)
{
i4_float twidth = nearest_w * q->texture_scale * center_x * 2;
r_api->use_texture(q->material_ref, i4_f_to_i(twidth), current_frame);
}
r_api->render_poly(num_poly_verts, clipped_poly);
}
}
void g1_render_class::add_translucent_trail(i4_transform_class * t,
i4_3d_point_class * spots, int t_spots,
float start_width, float end_width,
float start_alpha, float end_alpha,
w32 sc, w32 ec)
{
if (t_spots<2)
{
return;
}
pf_add_translucent_trail.start();
//make sure there's enough space in our arrays
if ((t_spots+1)*3 > (max_post_draw_verts - g1_num_post_draw_verts))
{
//i4_warning("g1_render::no space for tail vertices");
pf_add_translucent_trail.stop();
return;
}
if ((t_spots*2) > (max_post_draw_quads - g1_num_post_draw_quads))
{
//i4_warning("g1_render::no space for tail polys");
pf_add_translucent_trail.stop();
return;
}
i4_float start_r=g1_table_0_255_to_0_1[((sc>>16)&0xff)];
i4_float start_g=g1_table_0_255_to_0_1[((sc>>8)&0xff)];
i4_float start_b=g1_table_0_255_to_0_1[((sc>>0)&0xff)];
i4_float end_r=g1_table_0_255_to_0_1[((ec>>16)&0xff)];
i4_float end_g=g1_table_0_255_to_0_1[((ec>>8)&0xff)];
i4_float end_b=g1_table_0_255_to_0_1[((ec>>0)&0xff)];
int i;
i4_3d_point_class proj[256];
i4_3d_point_class * p = proj;
for (i=0; i<t_spots; i++, p++)
{
t->transform(spots[i], *p);
}
float width = start_width;
float width_step = (end_width-start_width)/(t_spots-1);
float next_width = start_width;
float alpha_step = (end_alpha-start_alpha)/(t_spots-1);
float r_step = (end_r-start_r)/(t_spots-1);
float g_step = (end_g-start_g)/(t_spots-1);
float b_step = (end_b-start_b)/(t_spots-1);
i4_2d_vector perp0( -(proj[1].y-proj[0].y), proj[1].x-proj[0].x);
if (perp0.x==0 && perp0.y==0)
{
perp0.x=1;
}
else
{
perp0.normalize();
}
float &ooxscale = scale_x; //ooscale_x;
float &ooyscale = scale_y; //ooscale_y;
int sv = g1_num_post_draw_verts;
i4_float r = start_r;
i4_float g = start_g;
i4_float b = start_b;
i4_float edge_alpha = 0.1f;
add_smoke_vert((proj[0].x + perp0.x * width) * ooxscale,
(proj[0].y + perp0.y * width) * ooyscale,
proj[0].z, r,g,b, edge_alpha);
add_smoke_vert((proj[0].x) * ooxscale,
(proj[0].y) * ooyscale,
proj[0].z, r,g,b, start_alpha);
add_smoke_vert((proj[0].x - perp0.x * width) * ooxscale,
(proj[0].y - perp0.y * width) * ooyscale,
proj[0].z, r,g,b, edge_alpha);
for (i=1; i<t_spots; i++)
{
next_width += width_step;
r += r_step;
g += g_step;
b += b_step;
start_alpha += alpha_step;
i4_2d_vector perp_last, perp_next, perp;
perp_last.x =-(proj[i].y-proj[i-1].y);
perp_last.y = (proj[i].x-proj[i-1].x);
if (perp_last.x==0 && perp_last.y==0)
{
perp_last.x=1;
}
else
{
perp_last.normalize();
}
if (i==t_spots-1)
{
perp=perp_last;
}
else
{
perp_next.x =-(proj[i+1].y-proj[i].y);
perp_next.y = (proj[i+1].x-proj[i].x);
if (perp_next.x==0 && perp_next.y==0)
{
perp_next.x=1;
}
else
{
perp_next.normalize();
}
perp.x=perp_last.x + perp_next.x;
perp.y=perp_last.y + perp_next.y;
if (perp.x==0 && perp.y==0)
{
perp.x=1;
}
else
{
perp.normalize();
}
}
add_smoke_vert((proj[i].x + perp.x * next_width) * ooxscale,
(proj[i].y + perp.y * next_width) * ooyscale,
proj[i].z, r,g,b, edge_alpha);
add_smoke_vert((proj[i].x) * ooxscale,
(proj[i].y) * ooyscale,
proj[i].z, r,g,b, start_alpha);
add_smoke_vert((proj[i].x - perp.x * next_width) * ooxscale,
(proj[i].y - perp.y * next_width) * ooyscale,
proj[i].z, r,g,b, edge_alpha);
g1_post_draw_quad_class q1(sv+ i * 3,
sv + i * 3+1,
sv + i * 3-2,
sv + i * 3-3);
add_post_draw_quad(q1);
g1_post_draw_quad_class q2(sv +i * 3+1,
sv + i * 3+2,
sv + i * 3-1,
sv + i * 3-2);
add_post_draw_quad(q2);
}
pf_add_translucent_trail.stop();
}
inline g1_map_vertex_class *g1vmin(g1_map_vertex_class * v1,
g1_map_vertex_class * v2)
{
if (v1->get_height_value()<v2->get_height_value())
{
return v1;
}
else
{
return v2;
}
}
i4_bool g1_render_class::project_point(const i4_3d_point_class &p,
r1_vert &v,
i4_transform_class * transform)
{
i4_3d_vector &temp_v = (i4_3d_vector &)v.v;
/*i4_d3d_vector dtemp_v;
i4_dtransform_class dtrans(*transform);
dtrans.transform(i4_d3d_point_class(p),dtemp_v);
dtemp_v.x *= (double)scale_x;
dtemp_v.y *= (double)scale_y;
if (dtemp_v.z>0.000001)
{
double ooz = 0.999999/dtemp_v.z;
v.v.x = dtemp_v.x;
v.v.y = dtemp_v.y;
v.v.z = dtemp_v.z;
v.px = dtemp_v.x * ooz * center_x + center_x;
v.py = dtemp_v.y * ooz * center_y + center_y;
v.w = ooz;
return i4_T;
}
else
{
v.v.x=dtemp_v.x;
v.v.y=dtemp_v.y;
v.v.z=0.001;
return i4_F;
}
*/
//this is appropriate enough (and faster)
transform->transform(p,temp_v);
v.v.x *= scale_x;
v.v.y *= scale_y;
if (v.v.z>0.001)
{
float ooz = r1_ooz(v.v.z);
v.px = v.v.x * ooz * center_x + center_x;
v.py = v.v.y * ooz * center_y + center_y;
v.w = ooz;
return i4_T;
}
else
{
v.v.z=0.001f;
return i4_F;
}
}
w8 g1_render_class::point_classify(const i4_3d_point_class &p,
i4_transform_class * transform)
{
i4_3d_vector temp;
transform->transform(p,temp);
//temp.x *= scale_x; //although project_point above is exactly doing the same,
//temp.y *= scale_y; //this is wrong here (causes point to be off by a factor for the larger of the two)
w8 code=0;
if (temp.z<r1_near_clip_z)
{
//no further investigation ( a real vertex can't be outside of
//all planes)
code=0xff;
return code;
}
float ooz=r1_ooz(temp.z);
float px,py;
px = temp.x * ooz *center_x+ center_x;
py = temp.y * ooz *center_y+ center_y;
//render_2d_point(px,py,0xffffff); // for testing purposes only
if (px<0)
{
code|=2;
}
if (px>2*center_x)
{
code|=1;
}
if (py<0)
{
code|=8;
}
if (py>2*center_y)
{
code|=4;
}
//if code is non-null it is outside of at least one plane of the frustrum
return code;
}
i4_bool g1_render_class::point_in_frustrum(const i4_3d_point_class &p,
i4_transform_class * transform)
{
return (point_classify(p,transform)==0);
}
i4_bool g1_render_class::sphere_in_frustrum(const i4_3d_point_class center,
i4_float size,
i4_transform_class * transform)
{
//check wheter all 8 vertices of the cube lie on the same
//side of the frustrum (otherwise, it might be that the cube
//is larger than the frustrum and we need to draw anyway)
//remember that we use this code to check all nodes of the octree,
//not only the leaves. And it is very probable that the root-node
//is REALLY large.
i4_float s=size/2;
//if the andcode becomes zero at one point, at least one part
//of the cube lies in the frustrum
w8 ANDCODE=0xff;
ANDCODE&=point_classify(i4_3d_point_class(center.x+s,center.y+s,center.z+s),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-s,center.y+s,center.z+s),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x+s,center.y-s,center.z+s),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-s,center.y-s,center.z+s),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x+s,center.y+s,center.z-s),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-s,center.y+s,center.z-s),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x+s,center.y-s,center.z-s),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-s,center.y-s,center.z-s),
transform);
if (!ANDCODE)
{
return i4_T;
}
return i4_F;
}
i4_bool g1_render_class::cube_in_frustrum(const i4_3d_point_class center,
i4_float xsize,
i4_float ysize,
i4_float zsize,
i4_transform_class * transform)
{
//check wheter all 8 vertices of the cube lie on the same
//side of the frustrum (otherwise, it might be that the cube
//is larger than the frustrum and we need to draw anyway)
//remember that we use this code to check all nodes of the octree,
//not only the leaves. And it is very probable that the root-node
//is REALLY large.
i4_float xs=xsize/2;
i4_float ys=ysize/2;
i4_float zs=zsize/2;
//if the andcode becomes zero at one point, at least one part
//of the cube lies in the frustrum
w8 ANDCODE=0xff;
ANDCODE&=point_classify(i4_3d_point_class(center.x+xs,center.y+ys,center.z+zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-xs,center.y+ys,center.z+zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x+xs,center.y-ys,center.z+zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-xs,center.y-ys,center.z+zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x+xs,center.y+ys,center.z-zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-xs,center.y+ys,center.z-zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x+xs,center.y-ys,center.z-zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
ANDCODE&=point_classify(i4_3d_point_class(center.x-xs,center.y-ys,center.z-zs),
transform);
if (!ANDCODE)
{
return i4_T;
}
return i4_F;
}
void g1_render_class::cube_in_frustrum(const i4_3d_point_class center,
i4_float xsize,
i4_float ysize,
i4_float zsize,
i4_transform_class * transform,
w8 &ANDCODE,
w8 &ORCODE)
{
//check wheter all 8 vertices of the cube lie on the same
//side of the frustrum (otherwise, it might be that the cube
//is larger than the frustrum and we need to draw anyway)
//remember that we use this code to check all nodes of the octree,
//not only the leaves. And it is very probable that the root-node
//is REALLY large.
i4_float xs=xsize/2;
i4_float ys=ysize/2;
i4_float zs=zsize/2;
//if the andcode becomes zero at one point, at least one part
//of the cube lies in the frustrum
ANDCODE=0xff;
ORCODE=0x0;
w8 code;
code=point_classify(i4_3d_point_class(center.x+xs,center.y+ys,center.z+zs),
transform);
ANDCODE&=code;
ORCODE|=code;
code=point_classify(i4_3d_point_class(center.x-xs,center.y+ys,center.z+zs),
transform);
ANDCODE&=code;
ORCODE|=code;
code=point_classify(i4_3d_point_class(center.x+xs,center.y-ys,center.z+zs),
transform);
ANDCODE&=code;
ORCODE|=code;
code=point_classify(i4_3d_point_class(center.x-xs,center.y-ys,center.z+zs),
transform);
ANDCODE&=code;
ORCODE|=code;
code=point_classify(i4_3d_point_class(center.x+xs,center.y+ys,center.z-zs),
transform);
ANDCODE&=code;
ORCODE|=code;
code=point_classify(i4_3d_point_class(center.x-xs,center.y+ys,center.z-zs),
transform);
ANDCODE&=code;
ORCODE|=code;
code=point_classify(i4_3d_point_class(center.x+xs,center.y-ys,center.z-zs),
transform);
ANDCODE&=code;
ORCODE|=code;
code=point_classify(i4_3d_point_class(center.x-xs,center.y-ys,center.z-zs),
transform);
}
void g1_render_class::draw_rectangle(int sx1, int sy1, int sx2, int sy2, i4_color col,
i4_draw_context_class &context)
{
sw32 x1,y1,x2,y2;
if (sx1<sx2)
{
x1=sx1;
x2=sx2;
}
else
{
x1=sx2;
x2=sx1;
}
if (sy1<sy2)
{
y1=sy1;
y2=sy2;
}
else
{
y1=sy2;
y2=sy1;
}
r_api->set_shading_mode(R1_SHADE_DISABLED);
r1_clip_clear_area(x1,y1,x2,y1, col, 0.01f, context, r_api);
r1_clip_clear_area(x2,y1,x2,y2, col, 0.01f, context, r_api);
r1_clip_clear_area(x1,y2,x2,y2, col, 0.01f, context, r_api);
r1_clip_clear_area(x1,y1,x1,y2, col, 0.01f, context, r_api);
}
void g1_setup_tri_texture_coords(r1_vert * tri1, r1_vert * tri2,
int cell_rotation, int cell_is_mirrored)
{
float u[4]={
1,0,0,1
};
float v[4]={
1,1,0,0
};
int on_remap[4]={
1,0,3,2
};
int dir=cell_is_mirrored ? 1 : 3, on=on_remap[cell_rotation];
tri1[0].s=u[on];
tri1[0].t=v[on];
on=(on+dir)&3;
tri1[1].s=u[on];
tri1[1].t=v[on];
on=(on+dir)&3;
tri1[2].s=u[on];
tri1[2].t=v[on];
on=on_remap[cell_rotation];
tri2[0].s=u[on];
tri2[0].t=v[on];
on=(on+dir+dir)&3;
tri2[1].s=u[on];
tri2[1].t=v[on];
on=(on+dir)&3;
tri2[2].s=u[on];
tri2[2].t=v[on];
}
void g1_render_class::render_sprite(const i4_3d_vector &p,
r1_texture_handle tex,
float sprite_width, float sprite_height,
float s1, float t1, float s2, float t2)
{
if (p.z >= r1_near_clip_z)
{
if (g1_t_post_draw_sprites<G1_MAX_SPRITES)
{
g1_post_draw_sprite_struct * s=g1_post_draw_sprites + g1_t_post_draw_sprites;
float ooz = r1_ooz(p.z);
i4_float xs = g1_render.center_x * ooz * g1_render.scale_x;
i4_float ys = g1_render.center_y * ooz * g1_render.scale_y;
float cx=g1_render.center_x + p.x*xs;
float cy=g1_render.center_y + p.y*ys;
float w=sprite_width * g1_render.center_x * ooz;
float h=sprite_height * g1_render.center_x * ooz;
s->x1=cx-w/2;
s->y1=cy-h/2;
s->x2=cx+w/2;
s->y2=cy+h/2;
s->z=p.z;
s->tex=tex;
s->s1=s1;
s->t1=t1;
s->s2=s2;
s->t2=t2;
g1_t_post_draw_sprites++;
}
}
}
void g1_render_class::render_near_sprite(float px, float py,
r1_texture_handle tex,
float sprite_width, float sprite_height,
float s1, float t1, float s2, float t2)
{
if (g1_t_post_draw_sprites<G1_MAX_SPRITES)
{
g1_post_draw_sprite_struct * s=g1_post_draw_sprites + g1_t_post_draw_sprites;
s->x1=px-sprite_width/2;
s->y1=py-sprite_height/2;
s->x2=px+sprite_width/2;
s->y2=py+sprite_height/2;
s->z=r1_near_clip_z*1.1f;
s->tex=tex;
s->s1=s1;
s->t1=t1;
s->s2=s2;
s->t2=t2;
g1_t_post_draw_sprites++;
}
}
| 25.010377 | 139 | 0.605088 | [
"render",
"object",
"vector",
"transform"
] |
33aa9b2a81c8f79602c605fd31e7b0e403ae14fa | 7,075 | cpp | C++ | GRT/CoreModules/PostProcessing.cpp | ramakrishnanachariya/gestureReg | 3ee7ffef4aad3163a207b4e1a982614fdc002f6a | [
"MIT",
"Unlicense"
] | null | null | null | GRT/CoreModules/PostProcessing.cpp | ramakrishnanachariya/gestureReg | 3ee7ffef4aad3163a207b4e1a982614fdc002f6a | [
"MIT",
"Unlicense"
] | null | null | null | GRT/CoreModules/PostProcessing.cpp | ramakrishnanachariya/gestureReg | 3ee7ffef4aad3163a207b4e1a982614fdc002f6a | [
"MIT",
"Unlicense"
] | null | null | null | /*
GRT MIT License
Copyright (c) <2012> <Nicholas Gillian, Media Lab, MIT>
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.
*/
#define GRT_DLL_EXPORTS
#include "PostProcessing.h"
GRT_BEGIN_NAMESPACE
PostProcessing::StringPostProcessingMap* PostProcessing::stringPostProcessingMap = NULL;
UINT PostProcessing::numPostProcessingInstances = 0;
PostProcessing* PostProcessing::createInstanceFromString(std::string const &postProcessingType){
StringPostProcessingMap::iterator iter = getMap()->find( postProcessingType );
if( iter == getMap()->end() ){
return NULL;
}
return iter->second();
}
PostProcessing::PostProcessing(void){
postProcessingType = "NOT_SET";
postProcessingInputMode = INPUT_MODE_NOT_SET;
postProcessingOutputMode = OUTPUT_MODE_NOT_SET;
initialized = false;
numInputDimensions = 0;
numOutputDimensions = 0;
numPostProcessingInstances++;
}
PostProcessing::~PostProcessing(void){
if( --numPostProcessingInstances == 0 ){
delete stringPostProcessingMap;
stringPostProcessingMap = NULL;
}
}
bool PostProcessing::copyBaseVariables(const PostProcessing *postProcessingModule){
if( postProcessingModule == NULL ){
errorLog << "copyBaseVariables(const PostProcessing *postProcessingModule) - postProcessingModule pointer is NULL!" << std::endl;
return false;
}
if( !this->copyMLBaseVariables( postProcessingModule ) ){
return false;
}
this->postProcessingType = postProcessingModule->postProcessingType;
this->postProcessingInputMode = postProcessingModule->postProcessingInputMode;
this->postProcessingOutputMode = postProcessingModule->postProcessingOutputMode;
this->initialized = postProcessingModule->initialized;
this->numInputDimensions = postProcessingModule->numInputDimensions;
this->numOutputDimensions = postProcessingModule->numOutputDimensions;
this->processedData = postProcessingModule->processedData;
this->debugLog = postProcessingModule->debugLog;
this->errorLog = postProcessingModule->errorLog;
this->warningLog = postProcessingModule->warningLog;
return true;
}
bool PostProcessing::init(){
if( numOutputDimensions == 0 ){
errorLog << "init() - Failed to init module, the number of output dimensions is zero!" << std::endl;
initialized = false;
return false;
}
//Setup the output vector
processedData.resize( numOutputDimensions );
//Flag the module has been initialized
initialized = true;
return true;
}
bool PostProcessing::saveModelToFile(std::string filename) const{
std::fstream file;
file.open(filename.c_str(), std::ios::out);
if( !saveModelToFile( file ) ){
return false;
}
file.close();
return true;
}
bool PostProcessing::loadModelFromFile(std::string filename){
std::fstream file;
file.open(filename.c_str(), std::ios::in);
if( !loadModelFromFile( file ) ){
return false;
}
//Close the file
file.close();
return true;
}
bool PostProcessing::savePostProcessingSettingsToFile(std::fstream &file) const{
if( !file.is_open() ){
errorLog << "savePostProcessingSettingsToFile(fstream &file) - The file is not open!" << std::endl;
return false;
}
if( !MLBase::saveBaseSettingsToFile( file ) ) return false;
file << "Initialized: " << initialized << std::endl;
return true;
}
bool PostProcessing::loadPostProcessingSettingsFromFile(std::fstream &file){
if( !file.is_open() ){
errorLog << "loadPostProcessingSettingsFromFile(fstream &file) - The file is not open!" << std::endl;
return false;
}
//Try and load the base settings from the file
if( !MLBase::loadBaseSettingsFromFile( file ) ){
return false;
}
std::string word;
//Load if the filter has been initialized
file >> word;
if( word != "Initialized:" ){
errorLog << "loadPostProcessingSettingsFromFile(fstream &file) - Failed to read Initialized header!" << std::endl;
clear();
return false;
}
file >> initialized;
//If the module has been initalized then call the init function to setup the processed data vector
if( initialized ){
return init();
}
return true;
}
PostProcessing* PostProcessing::createNewInstance() const{
return createInstanceFromString(postProcessingType);
}
std::string PostProcessing::getPostProcessingType() const{
return postProcessingType;
}
UINT PostProcessing::getPostProcessingInputMode() const{
return postProcessingInputMode;
}
UINT PostProcessing::getPostProcessingOutputMode() const{
return postProcessingOutputMode;
}
UINT PostProcessing::getNumInputDimensions() const{
return numInputDimensions;
}
UINT PostProcessing::getNumOutputDimensions() const{
return numOutputDimensions;
}
bool PostProcessing::getInitialized() const{
return initialized;
}
bool PostProcessing::getIsPostProcessingInputModePredictedClassLabel() const{
return postProcessingInputMode==INPUT_MODE_PREDICTED_CLASS_LABEL;
}
bool PostProcessing::getIsPostProcessingInputModeClassLikelihoods() const{
return postProcessingInputMode==INPUT_MODE_CLASS_LIKELIHOODS;
}
bool PostProcessing::getIsPostProcessingOutputModePredictedClassLabel() const{
return postProcessingOutputMode==OUTPUT_MODE_PREDICTED_CLASS_LABEL;
}
bool PostProcessing::getIsPostProcessingOutputModeClassLikelihoods() const{
return postProcessingOutputMode==OUTPUT_MODE_CLASS_LIKELIHOODS;
}
VectorFloat PostProcessing::getProcessedData() const{
return processedData;
}
GRT_END_NAMESPACE
| 32.159091 | 138 | 0.69371 | [
"vector"
] |
33ad0efe0352c1ba72b8b02782f7642eee7e3220 | 3,233 | cpp | C++ | 3rdParty/boost/1.71.0/libs/math/test/cardinal_quadratic_b_spline_test.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | 3rdParty/boost/1.71.0/libs/math/test/cardinal_quadratic_b_spline_test.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | 3rdParty/boost/1.71.0/libs/math/test/cardinal_quadratic_b_spline_test.cpp | rajeev02101987/arangodb | 817e6c04cb82777d266f3b444494140676da98e2 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | /*
* Copyright Nick Thompson, 2019
* Use, modification and distribution are 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 "math_unit_test.hpp"
#include <numeric>
#include <utility>
#include <boost/math/interpolators/cardinal_quadratic_b_spline.hpp>
using boost::math::interpolators::cardinal_quadratic_b_spline;
template<class Real>
void test_constant()
{
Real c = 7.2;
Real t0 = 0;
Real h = Real(1)/Real(16);
size_t n = 512;
std::vector<Real> v(n, c);
auto qbs = cardinal_quadratic_b_spline<Real>(v.data(), v.size(), t0, h);
size_t i = 0;
while (i < n) {
Real t = t0 + i*h;
CHECK_ULP_CLOSE(c, qbs(t), 2);
CHECK_MOLLIFIED_CLOSE(0, qbs.prime(t), 100*std::numeric_limits<Real>::epsilon());
++i;
}
i = 0;
while (i < n) {
Real t = t0 + i*h + h/2;
CHECK_ULP_CLOSE(c, qbs(t), 2);
CHECK_MOLLIFIED_CLOSE(0, qbs.prime(t), 300*std::numeric_limits<Real>::epsilon());
t = t0 + i*h + h/4;
CHECK_ULP_CLOSE(c, qbs(t), 2);
CHECK_MOLLIFIED_CLOSE(0, qbs.prime(t), 150*std::numeric_limits<Real>::epsilon());
++i;
}
}
template<class Real>
void test_linear()
{
Real m = 8.3;
Real b = 7.2;
Real t0 = 0;
Real h = Real(1)/Real(16);
size_t n = 512;
std::vector<Real> y(n);
for (size_t i = 0; i < n; ++i) {
Real t = i*h;
y[i] = m*t + b;
}
auto qbs = cardinal_quadratic_b_spline<Real>(y.data(), y.size(), t0, h);
size_t i = 0;
while (i < n) {
Real t = t0 + i*h;
CHECK_ULP_CLOSE(m*t+b, qbs(t), 2);
CHECK_ULP_CLOSE(m, qbs.prime(t), 820);
++i;
}
i = 0;
while (i < n) {
Real t = t0 + i*h + h/2;
CHECK_ULP_CLOSE(m*t+b, qbs(t), 2);
CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 1500*std::numeric_limits<Real>::epsilon());
t = t0 + i*h + h/4;
CHECK_ULP_CLOSE(m*t+b, qbs(t), 3);
CHECK_MOLLIFIED_CLOSE(m, qbs.prime(t), 1500*std::numeric_limits<Real>::epsilon());
++i;
}
}
template<class Real>
void test_quadratic()
{
Real a = 8.2;
Real b = 7.2;
Real c = -9.2;
Real t0 = 0;
Real h = Real(1)/Real(16);
size_t n = 513;
std::vector<Real> y(n);
for (size_t i = 0; i < n; ++i) {
Real t = i*h;
y[i] = a*t*t + b*t + c;
}
Real t_max = t0 + (n-1)*h;
auto qbs = cardinal_quadratic_b_spline<Real>(y, t0, h, b, 2*a*t_max + b);
size_t i = 0;
while (i < n) {
Real t = t0 + i*h;
CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 2);
++i;
}
i = 0;
while (i < n) {
Real t = t0 + i*h + h/2;
CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 47);
t = t0 + i*h + h/4;
if (!CHECK_ULP_CLOSE(a*t*t + b*t + c, qbs(t), 104)) {
std::cerr << " Problem abscissa t = " << t << "\n";
}
++i;
}
}
int main()
{
test_constant<float>();
test_constant<double>();
test_constant<long double>();
test_linear<float>();
test_linear<double>();
test_linear<long double>();
test_quadratic<double>();
test_quadratic<long double>();
return boost::math::test::report_errors();
}
| 24.679389 | 88 | 0.550572 | [
"vector"
] |
33af0ee4e985720b6b3967ebe2b04c31792af794 | 10,857 | cpp | C++ | Player.cpp | numpad/mines | ad475fcc6470576cc16a1b9c13510edcf2c250bd | [
"MIT"
] | null | null | null | Player.cpp | numpad/mines | ad475fcc6470576cc16a1b9c13510edcf2c250bd | [
"MIT"
] | null | null | null | Player.cpp | numpad/mines | ad475fcc6470576cc16a1b9c13510edcf2c250bd | [
"MIT"
] | null | null | null | #include "Player.hpp"
Player::Player(Vec2 screenSize) : Entity("assets/player/skin.png"), textFont("assets/font/font.png", Vec2(5, 8)) {
/* Offset body --> feet */
Player::feetOffset = Vec2(7.0, 37.0);
Player::headOffset = Vec2(6.0, -28.0);
Player::legAnimation = 0.0;
Player::armfAngle = 0.0;
Player::armfAnimation = 0.0;
/* Jumping, Walking Speed */
Player::jumpstrength = 9.5; // TODO: Make a little random
Player::acc = Vec2(0.75, 0.0);
Player::maxvel = Vec2(3.5, 7.75);
/* define render order */
Player::limb_z_index = std::vector<size_t>();
Player::limb_z_index.push_back( 1);
Player::limb_z_index.push_back( 4);
Player::limb_z_index.push_back( 3);
Player::limb_z_index.push_back(-1);
Player::limb_z_index.push_back( 0);
Player::limb_z_index.push_back( 2);
/* Inventory */
Player::setPlaceMode(Player::PLACE_FOREGROUND);
Player::currentItemSelected = 0;
Player::showInventory = false;
if (!Player::inventoryHotbarTexture.loadFromFile("assets/gui/inventory.png")) {
puts("[Player] failed loading 'assets/gui/inventory.png'!");
}
Player::inventoryHotbarSprite.setTexture(Player::inventoryHotbarTexture);
Player::inventoryHotbarSprite.setPosition(screenSize.x / 2.0 - (float)Player::inventoryHotbarTexture.getSize().x / 2.0, screenSize.y - (float)Player::inventoryHotbarTexture.getSize().y * 1.25);
/* Full inventory */
if (!Player::inventoryFullTexture.loadFromFile("assets/gui/inventory_full.png")) {
puts("[Player] failed loading 'assets/gui/inventory_full.png'!");
}
Player::inventoryFullSprite.setTexture(Player::inventoryFullTexture);
Player::inventoryFullSprite.setOrigin(Player::inventoryFullTexture.getSize().x / 2.0, Player::inventoryFullTexture.getSize().y / 2.0);
Player::inventoryFullSprite.setPosition(screenSize.x / 2.0, screenSize.y / 2.0);
Vec2 gridStart(4, 124);
Vec2 hotbarStart(4, 264);
Vec2 gridStepX(40, 0);
Vec2 gridStepY(0, 40);
for (size_t x = 0; x < 10; ++x) {
Vec2 gridCellPos = hotbarStart + (gridStepX * x);
Player::inventoryGui.addCell(gridCellPos);
}
for (size_t y = 0; y < 3; ++y) {
for (size_t x = 0; x < 10; ++x) {
Vec2 gridCellPos = gridStart + (gridStepX * x) + (gridStepY * y);
Player::inventoryGui.addCell(gridCellPos);
}
}
/* Create Limbs and attach to body */
Player::addLimb( Limb(Entity::skin, sf::IntRect( 5, 29, 8, 24), Vec2(0.5, 0.5), Vec2( 0, 1)));
Player::addChildLimb(Limb(Player::skin, sf::IntRect( 5, 5, 22, 22), Vec2(0.5, 0.9), Vec2( 0, -4)));
Player::addChildLimb(Limb(Player::skin, sf::IntRect(33, 29, 8, 24), Vec2(0.5, 0.1), Vec2( 0, -2)));
Player::addChildLimb(Limb(Player::skin, sf::IntRect(19, 29, 8, 24), Vec2(0.5, 0.1), Vec2( 0, -2)));
Player::addChildLimb(Limb(Player::skin, sf::IntRect(33, 3, 8, 24), Vec2(0.5, 0.1), Vec2( 0, 7)));
Player::addChildLimb(Limb(Player::skin, sf::IntRect(46, 3, 8, 24), Vec2(0.5, 0.1), Vec2( 0, 7)));
/* Keep pointers to provide easy access */
Player::head = &Player::body.getChild(0);
Player::armb = &Player::body.getChild(1);
Player::armf = &Player::body.getChild(2);
Player::legf = &Player::body.getChild(3);
Player::legb = &Player::body.getChild(4);
Player::key_up = sf::Keyboard::W;
Player::key_down = sf::Keyboard::S;
Player::key_left = sf::Keyboard::A;
Player::key_right = sf::Keyboard::D;
Player::key_place_background = sf::Keyboard::Y;
Player::key_place_foreground = sf::Keyboard::X;
Player::key_inventory = sf::Keyboard::Tab;
}
void Player::handleInput() {
if (sf::Keyboard::isKeyPressed(Player::key_up)) {
Player::jump(1.1);
}
if (sf::Keyboard::isKeyPressed(Player::key_left)) {
Player::walk(Entity::WalkState::LEFT);
}
if (sf::Keyboard::isKeyPressed(Player::key_right)) {
Player::walk(Entity::WalkState::RIGHT);
}
if ((!sf::Keyboard::isKeyPressed(Player::key_left) && !sf::Keyboard::isKeyPressed(Player::key_right)) || (sf::Keyboard::isKeyPressed(Player::key_left) && sf::Keyboard::isKeyPressed(Player::key_right))) {
Player::walkstate = Entity::WalkState::STANDING;
}
if (sf::Keyboard::isKeyPressed(Player::key_place_background)) {
Player::setPlaceMode(Player::PLACE_BACKGROUND);
} else if (sf::Keyboard::isKeyPressed(Player::key_place_foreground)) {
Player::setPlaceMode(Player::PLACE_FOREGROUND);
}
if (Input::isKeyClicked(Player::key_inventory)) {
Player::showInventory = !Player::showInventory;
}
for (int i = 0; i < 10; ++i) {
if (sf::Keyboard::isKeyPressed(
/* Don't make me explain this, it works. No idea why (i - 5) works, but it does. */
static_cast<sf::Keyboard::Key>((static_cast<int>(sf::Keyboard::Num0) + (i - 5)) % 10 + static_cast<int>(sf::Keyboard::Num0))
)) {
Player::selectItem(i);
}
}
}
void Player::animate(Grid& grid) {
if (Player::walkstate == Entity::WalkState::WALKING) {
Player::legAnimation += Player::walkdir;
Player::legf->getAngle() = sin(Player::legAnimation / 6.0) * 30.0;
Player::legb->getAngle() = -Player::legf->getAngle();
Player::armf->getAngle() = cos(Player::legAnimation / 7.0) * 20.0;
Player::armb->getAngle() = -Player::armf->getAngle();
} else if (Player::walkstate == Entity::WalkState::STANDING) {
if (fabs(Player::vel.x) > 0.0) {
Player::legAnimation += Player::walkdir * 1.5;
} else {
Player::legAnimation = 0.0;
}
/* Shake arm when building/removing blocks */
if (Player::armfAnimation > 0.0) {
Player::armfAnimation -= 1.0;
Player::armf->getAngle() = Player::armfAngle + sin(Player::armfAnimation * 0.5) * 17.0;
}
Player::legf->getAngle() *= 0.75;
Player::legb->getAngle() = -Player::legf->getAngle();
}
}
void Player::update(Grid& grid) {
Player::body.update();
Player::physicsUpdate(grid);
Player::animate(grid);
Player::head->flipx = Player::walkdir;
Player::armb->flipx = Player::walkdir;
Player::armf->flipx = Player::walkdir;
Player::legb->flipx = Player::walkdir;
Player::legf->flipx = Player::walkdir;
Player::body.flipx = Player::walkdir;
}
void Player::render(sf::RenderWindow& window, Vec2 off) {
Player::body.renderAll(window, Player::limb_z_index, Player::pos + off);
}
void Player::render(sf::RenderWindow& window, sf::Shader& shader, Vec2 off) {
Player::body.renderAll(window, Player::limb_z_index, shader, Player::pos + off);
}
/* Inventory Management */
void Player::renderInventory(sf::RenderWindow &window, std::vector<Item> &droppedItems, Vec2 off) {
/* Render full inventory */
if (Player::showInventory) {
const float previousScale = Player::textFont.getScale();
Player::textFont.setScale(2.0);
window.draw(Player::inventoryFullSprite);
sf::Vector2f invPosLeftCorner = Player::inventoryFullSprite.getPosition() - Player::inventoryFullSprite.getOrigin();
Vec2 invTextPos(invPosLeftCorner.x + 3.0, invPosLeftCorner.y + 4.0);
Player::textFont.write(window, invTextPos + Vec2(1.0, 1.0), L"Crafting", sf::Color(167, 167, 167));
Player::textFont.write(window, invTextPos, L"Crafting", sf::Color(67, 67, 67));
invTextPos.y += 103;
Player::textFont.write(window, invTextPos + Vec2(1.0, 1.0), L"Inventory", sf::Color(167, 167, 167));
Player::textFont.write(window, invTextPos, L"Inventory", sf::Color(67, 67, 67));
Player::textFont.setScale(previousScale);
inventoryGui.render(window,
Vec2(
Player::inventoryFullSprite.getPosition().x - Player::inventoryFullSprite.getOrigin().x,
Player::inventoryFullSprite.getPosition().y - Player::inventoryFullSprite.getOrigin().y
) + off,
Player::textFont);
} else {
if (!Player::inventoryGui.getSelectedItem().isFree()) {
Random throwVelx(2.5, 3.45);
Random throwVely(1.5, 4.5);
blockid thrownItem;
while ((thrownItem = Player::inventoryGui.getSelectedItem().take()) != BLOCK_AIR) {
droppedItems.push_back(Item(Player::pos, thrownItem, Vec2(throwVelx() * Player::walkdir, -throwVely())));
}
Player::inventoryGui.getSelectedItem() = InventoryStack();
}
window.draw(Player::inventoryHotbarSprite);
for (size_t i = 0; i < MIN(10, Player::inventoryGui.getItems().getSize()); ++i) {
Block invblock(Player::inventoryGui.getItems().at(i).get());
if (invblock.id < 0)
continue;
Vec2 invblockPos;
float yoff = 0;
if (i == Player::currentItemSelected) {
float elapsed = Player::timeAlive.getElapsedTime().asSeconds();
yoff = -fabs(sin(elapsed * 4.0) * 7.0);
}
invblockPos = Vec2(Player::inventoryHotbarSprite.getPosition().x + 4.0, Player::inventoryHotbarSprite.getPosition().y + 4.0) + Vec2(i * 40, yoff);
Player::inventoryGui.getItems().at(i).render(window, Player::textFont, invblockPos);
}
}
}
blockid Player::getItem() {
return Player::inventoryGui.getItems().at(Player::currentItemSelected).get();
}
blockid Player::takeItem() {
return Player::inventoryGui.getItems().at(Player::currentItemSelected).take();
}
bool Player::canCollect(blockid type) {
return Player::inventoryGui.getItems().hasSpaceFor(type);
}
size_t Player::collectItems(blockid type, size_t count) {
Player::inventoryGui.getItems().add(InventoryStack(count, type));
return 0;
}
void Player::selectItem(size_t index) {
Player::currentItemSelected = index;
}
void Player::setPlaceMode(Player::PlaceMode pm) {
Player::placeMode = pm;
}
bool Player::getPlaceMode() {
return static_cast<bool>(Player::placeMode);
}
bool Player::canCollectItem(Item &item, float radius) {
if (!item.collectTimeoutReached())
return false;
if (!Player::canCollect(item.getType()))
return false;
return (item.pos - Player::pos).length() < radius;
}
void Player::animateArm(float angle, float time) {
Player::armfAngle = angle;
if (Player::armfAnimation > 0.025)
return;
Player::armfAnimation = time;
}
bool Player::load(const char *fn) {
FILE *fp = fopen(fn, "r");
if (!fp) {
return false;
}
float loaded_position[2];
fread(loaded_position, sizeof(float), 2, fp);
for (size_t i = 0; i < Player::inventoryGui.getSize(); ++i) {
size_t blockCount;
blockid blockId;
fread(&blockCount, sizeof(size_t), 1, fp);
fread(&blockId, sizeof(blockid), 1, fp);
//Player::collectItems(blockId, blockCount);
Player::inventoryGui.getItems().add(InventoryStack());
Player::inventoryGui.getItems().at(i).count = blockCount;
Player::inventoryGui.getItems().at(i).type = blockId;
}
Player::setPos(Vec2(loaded_position[0], loaded_position[1]));
fclose(fp);
return true;
}
void Player::save(const char *fn) {
FILE *fp = fopen(fn, "w+");
if (!fp) {
printf("Cannot save to \"%s\"!\n", fn);
return;
}
fwrite(&(Player::pos.x), sizeof(float), 1, fp);
fwrite(&(Player::pos.y), sizeof(float), 1, fp);
for (size_t i = 0; i < Player::inventoryGui.getItems().getSize(); ++i) {
fwrite(&(Player::inventoryGui.getItems().at(i).count), sizeof(size_t), 1, fp);
const int blockId = Player::inventoryGui.getItems().at(i).get();
fwrite(&(blockId), sizeof(blockid), 1, fp);
}
fclose(fp);
} | 33 | 204 | 0.682693 | [
"render",
"vector"
] |
33afc7d7cbf7f847a42e8848f6039491d369ad96 | 8,192 | cpp | C++ | VC/NotUsedCpps/CSAMutation.cpp | hkujy/VC | 54b79fac4ecf4ac225b54325d879a580a9b17be6 | [
"MIT"
] | null | null | null | VC/NotUsedCpps/CSAMutation.cpp | hkujy/VC | 54b79fac4ecf4ac225b54325d879a580a9b17be6 | [
"MIT"
] | null | null | null | VC/NotUsedCpps/CSAMutation.cpp | hkujy/VC | 54b79fac4ecf4ac225b54325d879a580a9b17be6 | [
"MIT"
] | null | null | null | #include "CommonHeaders.h"
#include <assert.h>
#include <math.h> /* pow */
// #include "MutationFuncHeader.h"
#include "RandomFuncs.h"
using namespace std;
// void increasdof(double &NowDof, vector<double> DofVarSet){
void increasdof(double &NowDof, double &NowDofProb, vector<pair<double,double>> DofVarSet){
// if (isEqual(NowDof, DofVarSet.back())) return;
if (isEqual(NowDof, DofVarSet.back().first)) return;
for (unsigned int i = 0; i < DofVarSet.size();i++)
{
if (isEqual(NowDof,DofVarSet.at(i).first))
{
NowDof = DofVarSet.at(i + 1).first;
NowDofProb = DofVarSet.at(i + 1).second;
return;
}
}
}
void decreaseDof(double &NowDof,double &NowDofProb, vector<pair<double, double>> DofVarSet){
if (isEqual(NowDof, DofVarSet.begin()->first)) return;
for (unsigned int i = 0; i < DofVarSet.size();i++)
{
if (isEqual(NowDof,DofVarSet.at(i).first))
{
NowDof = DofVarSet.at(i - 1).first;
NowDofProb = DofVarSet.at(i-1).second;
}
}
}
void SetDofAndProb(const std::vector<pair<double, double>> &Vec,
double &setdof, double &setdofprob, bool isExlcudeZero = false);
int CaseIndex(double Fit, double MaxFit, double MinFit){
double Fp = MaxFit - MinFit;
assert(Fp >= 0.0f);
if (Fit <= MaxFit&&Fit > MaxFit - 0.05f*Fp) return 0;
if (Fit <= MaxFit - 0.05f*Fp&&Fit > MaxFit - 0.2f*Fp) return 1;
if (Fit <= MaxFit - 0.20f*Fp&&Fit > MaxFit - 0.4f*Fp) return 2;
if (Fit <= MaxFit - 0.4f*Fp&&Fit > MaxFit - 0.6f*Fp) return 3;
if (Fit <= MaxFit - 0.6f*Fp&&Fit > MaxFit - 0.8f*Fp) return 4;
if (Fit <= MaxFit - 0.8f*Fp&&Fit >= MinFit) return 5;
return InvaildInt;
}
void Algorithms::FirstProcedure(CHROME &Chrom){
double dof, dofprob;
for (unsigned int i = 0; i < Chrom.VulnerableLinks.size(); i++)
{
SetDofAndProb(LinkDofSet[i],dof, dofprob);
Chrom.VulnerableLinkDof.at(i) = dof;
Chrom.VulnerableLinkDofProb.at(i) =dofprob;
}
}
void Algorithms::addNewNode(CHROME &Chrom){
vector<int> ZeroDofLinkSet;
for (unsigned int i = 0; i < Chrom.VulnerableLinkDof.size(); i++)
{
if (isEqual(Chrom.VulnerableLinkDof.at(i), 0.0f))
{
ZeroDofLinkSet.push_back(Chrom.VulnerableLinks.at(i));
}
}
if (ZeroDofLinkSet.size() == 0)
{
int pos = -1;
int Rnode = GenRandomInt(Chrom.VulnerableLinks,pos);// random select a node
double OldValue = Chrom.VulnerableLinkDof.at(pos);
double dof, dofprob;
do
{
SetDofAndProb(LinkDofSet[pos],dof,dofprob);
} while (isEqual(OldValue, dof));
Chrom.VulnerableLinkDof.at(pos) = dof;
Chrom.VulnerableLinkDofProb.at(pos) = dofprob;
}
else
{
int pos = -1;
int Rnode = GenRandomInt(ZeroDofLinkSet, pos);// random select a node
//int pos = InvaildInt;
double dof, dofprob;
for (unsigned int i = 0; i < Chrom.VulnerableLinks.size(); i++)
{
if (Chrom.VulnerableLinks.at(i) == Rnode) {
do
{
SetDofAndProb(LinkDofSet[i],dof,dofprob,true);
Chrom.VulnerableLinkDof.at(i) = dof;
Chrom.VulnerableLinkDofProb.at(i) = dofprob;
} while (isEqual(Chrom.VulnerableLinkDof.at(i), 0.0f) );// generate non zero
}
}
}
}
void Algorithms::removeNodeDof(CHROME &Chrom){
try
{
int Pos = GenRandomPos((int)Chrom.VulnerableLinks.size());// 0 to size
Chrom.VulnerableLinkDof.at(Pos) = 0.0f;
Chrom.VulnerableLinkDofProb.at(Pos) = LinkDofSet.at(Pos).at(0).second;
/*Remark: the first Dof level must equals to zero*/
assert(isEqual(LinkDofSet[Pos].at(0).first,0.0));
}
catch (exception &e){
TRACE("%s", e);
}
}
void Algorithms::exchangeNodeDof(CHROME &Chrom){
// if (isUseNodeMatrix) exchangeNodeDofFunc(Chrom,this->NodeDofVarSet);
// exchangeNodeDofFunc(Chrom,this->LinkDofVarSet);
vector<int> ZeroSet, PostiveSet;
ZeroSet.reserve(NumLinks); PostiveSet.reserve(NumLinks);
for (unsigned int i = 0; i < Chrom.VulnerableLinkDof.size(); i++)
{
if (isEqual(Chrom.VulnerableLinkDof.at(i), 0.0f)) ZeroSet.push_back(i);
else PostiveSet.push_back(i);
}
int A, B;
if (ZeroSet.size()==0)
{
int Pos;
B = GenRandomInt(PostiveSet,Pos);
Chrom.VulnerableLinkDof.at(B) = 0.0f;
Chrom.VulnerableLinkDofProb.at(B) = LinkDofSet.at(B).at(0).second;
}
if (PostiveSet.size()==0)
{
int pos;
A = GenRandomInt(ZeroSet,pos);
double dof, dofprob;
SetDofAndProb(LinkDofSet[A],dof, dofprob);
Chrom.VulnerableLinkDof.at(A) = dof;
Chrom.VulnerableLinkDofProb.at(A) = dofprob;
// Chrom.VulnerableLinkDofProb.at(A) = GenRandomFloat(DofVarSet);
}
if (PostiveSet.size()!=0&&ZeroSet.size()!=0)
{
int pos;
A = GenRandomInt(ZeroSet,pos);
B = GenRandomInt(PostiveSet,pos);
Chrom.VulnerableLinkDof[A] = Chrom.VulnerableLinkDof[B];
Chrom.VulnerableLinkDofProb[A] = Chrom.VulnerableLinkDofProb[B];
Chrom.VulnerableLinkDof[B] = 0.0f;
Chrom.VulnerableLinkDofProb[B] = LinkDofSet[B].at(0).second;
}
}
void Algorithms::SecondProcedure(CHROME &Chrom, double Ratio){
int NumOfRepeate = (int)((double)NumNodes*Ratio);
std::vector<int> v = { 1, 2, 3 }; //a,b,c, three operators
for (int i = 0; i < NumOfRepeate; i++)
{
int pos;
int Index = GenRandomInt(v,pos);
//cout << "index = " << Index<<endl;
switch (Index)
{
//add a new failed node and assign it dof value
case 1: addNewNode(Chrom); break;
case 2: removeNodeDof(Chrom); break;
case 3: exchangeNodeDof(Chrom); break;
default:
TRACE("SecondProcedure generate wrong Index");
system("PAUSE");
break;
}
}
}
int getMutationIndex(const double f)
{
int MutatorIndex = -1;
if (f < double(1.0f / 6.0f))
{
MutatorIndex = 0;
}
if (f < double(2.0f / 6.0f) && f >= double(1.0f / 6.0f))
{
MutatorIndex = 1;
}
if (f < double(3.0f / 6.0f) && f >= double(2.0f / 6.0f))
{
MutatorIndex = 2;
}
if (f < double(4.0f / 6.0f) && f >= double(3.0f / 6.0f))
{
MutatorIndex = 3;
}
if (f < double(5.0f / 6.0f) && f >= double(4.0f / 6.0f))
{
MutatorIndex = 4;
}
if (f <= double(6.0f / 6.0f) && f >= double(5.0f / 6.0f))
{
MutatorIndex = 5;
}
return MutatorIndex;
}
void Algorithms::HyperMutateMain(CHROME &Chrom){
// Remark: 21-Oct-2019: It seems both GA and CSA use the same mutation index
int MutatorIndex; // from 1 to 5
double f;
switch (AlgorithmIndex)
{
case CSA:
f = GenRandomReal();
MutatorIndex = getMutationIndex(f); break;
case GA:
f = GenRandomReal();
MutatorIndex = getMutationIndex(f); break;
#pragma region oldMutationIndex
// if (f < double(1.0f / 6.0f))
// {
// MutatorIndex = 0; break;
// }
// if (f < double(2.0f / 6.0f) && f >= double(1.0f / 6.0f))
// {
// MutatorIndex = 1; break;
// }
// if (f < double(3.0f / 6.0f) && f >= double(2.0f / 6.0f))
// {
// MutatorIndex = 2; break;
// }
// if (f < double(4.0f / 6.0f) && f >= double(3.0f / 6.0f))
// {
// MutatorIndex = 3; break;
// }
// if (f < double(5.0f / 6.0f) && f >= double(4.0f / 6.0f))
// {
// MutatorIndex = 4; break;
// }
// if (f <= double(6.0f / 6.0f) && f >= double(5.0f / 6.0f))
// {
// MutatorIndex = 5;
// break;
// }
#pragma endregion
default:
cerr << "Algorithm index is not proper defined" << endl;
system("PAUSE");
break;
}
switch (MutatorIndex)
{
case 0:
// random increase or decrease
for (unsigned int i = 0; i < Chrom.VulnerableLinkDof.size();i++)
{
if (GenRandomReal()>=0.5f)
{
increasdof(Chrom.VulnerableLinkDof.at(i), Chrom.VulnerableLinkDofProb.at(i), LinkDofSet.at(i));
}
else decreaseDof(Chrom.VulnerableLinkDof.at(i), Chrom.VulnerableLinkDofProb.at(i), LinkDofSet.at(i));
}
break;
case 1:
if (GenRandomReal() <= 0.1f) this->FirstProcedure(Chrom);
else this->SecondProcedure(Chrom, 0.2f);
break;
case 2:
if (GenRandomReal() <= 0.2f) this->FirstProcedure(Chrom);
else this->SecondProcedure(Chrom, 0.4f);
break;
case 3:
if (GenRandomReal() <= 0.3f) this->FirstProcedure(Chrom);
else this->SecondProcedure(Chrom, 0.6f);
break;
case 4:
if (GenRandomReal() <= 0.4f) this->FirstProcedure(Chrom);
else this->SecondProcedure(Chrom, 0.8f);
break;
case 5:
if (GenRandomReal() <= 0.5f) this->FirstProcedure(Chrom);
else this->SecondProcedure(Chrom, 1.0f);
break;
default:
TRACE("CSA Hypermutation main generates wrong Index");
system("PAUSE");
break;
}
}; | 27.215947 | 104 | 0.647949 | [
"vector"
] |
33afe4b7a7768067dcb2388d409ee5b5c288d337 | 331 | cpp | C++ | Chandra HAL/main.cpp | martinjaymckee/Chandra-HAL | 337a0cc5d19b20af979145c07cf1d7351754bb27 | [
"MIT"
] | null | null | null | Chandra HAL/main.cpp | martinjaymckee/Chandra-HAL | 337a0cc5d19b20af979145c07cf1d7351754bb27 | [
"MIT"
] | null | null | null | Chandra HAL/main.cpp | martinjaymckee/Chandra-HAL | 337a0cc5d19b20af979145c07cf1d7351754bb27 | [
"MIT"
] | null | null | null | #include <iostream>
#include "inertial.h"
int main(void) {
chandra::drivers::InertialTransform<double,3> transform;
std::cout << transform.c << '\n';
std::cout << "gain = ";
transform.A.dump();
std::cout << '\n';
std::cout << "offset = ";
transform.x0.dump();
std::cout << '\n';
return 0;
}
| 18.388889 | 60 | 0.55287 | [
"transform"
] |
33b0555c7e420f5bd893287a5c67668efee7fc29 | 17,992 | cpp | C++ | src/menus/materia_menu/materia_init_callbacks.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | src/menus/materia_menu/materia_init_callbacks.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | src/menus/materia_menu/materia_init_callbacks.cpp | Kor-Hal/SisterRay | 4e8482525a5d7f77dee186f438ddb16523a61e7e | [
"BSD-3-Clause"
] | null | null | null | #include "materia_init_callbacks.h"
#include "../../impl.h"
#include "../../party/party_utils.h"
#include "../../widgets/updaters.h"
using namespace MateriaWidgetNames;
void initMateraCharDataWidget(const MenuInitEvent* event) {
const char * menuText;
auto menuObject = event->menu;
auto mainWidget = menuObject->menuWidget;
TextWidget* textWidget;
DrawTextParams textParams;
BoxWidget* boxWidget;
DrawBoxParams boxParams;
PortraitWidget* portraitWidget;
auto currentMateriaWidget = createWidget(CHAR_DATA_WIDGET_NAME);
boxParams = {
0,
0,
640,
148,
0.3f
};
boxWidget = createBoxWidget(boxParams, CHAR_DATA_BOX_NAME);
addChildWidget(currentMateriaWidget, (Widget*)boxWidget, CHAR_DATA_BOX_NAME);
drawPortraitParams portraitParams = { 17, 19, 0, 0.2f };
portraitWidget = createPortraitWidget(portraitParams, PORTRAIT_WIDGET_NAME);
addChildWidget(currentMateriaWidget, (Widget*)portraitWidget, PORTRAIT_WIDGET_NAME);
drawHPBarParams hpBarParams = { 103, 30, 0, 0.2f };
auto HPBarWidget = createHPBarWidget(hpBarParams, HPBAR_WIDGET_NAME);
addChildWidget(currentMateriaWidget, (Widget*)HPBarWidget, HPBAR_WIDGET_NAME);
std::vector<std::string> gearNames = { GEAR_SLOT_1_NAME, GEAR_SLOT_2_NAME };
std::vector<std::string> equippedGearNames = { EQUIPPED_WEAPON, EQUIPPED_ARMOR };
std::vector<std::string> viewNames = { CHECK_NAME, ARRANGE_NAME };
std::vector <std::string> slotNames = { GEAR_1_SLOTS, GEAR_2_SLOTS };
for (int row = 0; row < gearNames.size(); row++) {
menuText = gContext.gameStrings.materiaMenuTexts.get_string(row);
setTextParams(&textParams, 280, 59 + (50 * row), menuText, COLOR_WHITE, 0.1f);
textWidget = createTextWidget(textParams, viewNames[row]);
addChildWidget(currentMateriaWidget, (Widget*)textWidget, viewNames[row]);
setTextParams(&textParams, 320, 32 + (52 * row), menuText, COLOR_TEAL, 0.1f);
textWidget = createTextWidget(textParams, equippedGearNames[row]);
addChildWidget(currentMateriaWidget, (Widget*)textWidget, equippedGearNames[row]);
menuText = gContext.gameStrings.materiaMenuTexts.get_string(row + 2);
setTextParams(&textParams, 267, 32 + (52 * row), menuText, COLOR_WHITE, 0.1f);
textWidget = createTextWidget(textParams, gearNames[row]);
addChildWidget(currentMateriaWidget, (Widget*)textWidget, gearNames[row]);
/*There is a good chance the slot widget will have to be rewritten, since we want to expand the number of materia*/
drawSlotsParams slotsParams = { 357, 59 + (50 * row), nullptr, nullptr };
auto slotsWidget = createSlotsWidget(slotsParams, slotNames[row]);
addChildWidget(currentMateriaWidget, (Widget*)slotsWidget, slotNames[row]);
}
addChildWidget(mainWidget, currentMateriaWidget, CHAR_DATA_WIDGET_NAME);
}
void initMateriaDescWidget(const MenuInitEvent* event) {
const char* materiaDescription;
u16 materiaID;
auto characterID = getCharacterRecordIndex(*MAT_MENU_PARTY_INDEX);
TextWidget* textWidget;
DrawTextParams textParams;
BoxWidget* boxWidget;
DrawBoxParams boxParams;
auto menuObject = event->menu;
auto mainWidget = menuObject->menuWidget;
auto MatDescWidget = createWidget(MATERIA_DESC_WIDGET_NAME);
boxParams = {
0,
148,
640,
50,
0.3f
};
boxWidget = createBoxWidget(boxParams, MATERIA_DESC_BOX);
addChildWidget(mainWidget, (Widget*)boxWidget, MATERIA_DESC_BOX);
materiaID = getMateriaID(characterID, 0, 0);
materiaDescription = gContext.gameStrings.materia_descriptions.get_string(materiaID);
setTextParams(&textParams, 16, 160, materiaDescription, COLOR_WHITE, 0.1f);
textWidget = createTextWidget(textParams, MATERIA_DESC);
addChildWidget(MatDescWidget, (Widget*)textWidget, MATERIA_DESC);
addChildWidget(mainWidget, MatDescWidget, MATERIA_DESC_WIDGET_NAME);
}
//Handles the base display
void initMateriaViewWidget(const MenuInitEvent* event) {
auto materiaChoiceCursor = getStateCursor(event->menu, 2);
CursorGridWidget* gridWidget;
BoxWidget* boxWidget;
DrawBoxParams boxParams;
auto menuObject = event->menu;
auto mainWidget = menuObject->menuWidget;
auto materiaViewWidget = createWidget(MATERIA_GRID_WIDGET_NAME);
boxParams = {
380,
190,
260,
300,
0.3f
};
boxWidget = createBoxWidget(boxParams, MATERIA_GRID_BOX);
addChildWidget(materiaViewWidget, (Widget*)boxWidget, MATERIA_GRID_BOX);
auto normalMateriaViewWidget = createWidget(MATERIA_GRID);
drawGridParams gridParams = { MATERIA_MENU_NAME.c_str(), 2, &materiaEntryUpdater, 427, 210, &allocateMateriaRow, 0 };
gridWidget = createGridWidget(gridParams, MATERIA_GRID_NAMES);
addChildWidget(normalMateriaViewWidget, (Widget*)gridWidget, MATERIA_GRID_NAMES);
addChildWidget(materiaViewWidget, normalMateriaViewWidget, MATERIA_GRID);
addChildWidget(mainWidget, materiaViewWidget, MATERIA_GRID_WIDGET_NAME);
}
Widget* allocateMateriaRow(const char* name, i32 xCoordinate, i32 yCoordinate) {
auto materiaWidget = createWidget(name);
moveWidget(materiaWidget, xCoordinate, yCoordinate);
DrawTextParams textParams = { xCoordinate, yCoordinate, getDefaultString(), COLOR_WHITE, 0.1f };
addChildWidget(materiaWidget, (Widget*)createTextWidget(textParams, std::string("TXT")), std::string("TXT"));
DrawGameAssetParams assetInitParams = MateriaSphere(xCoordinate - 20, yCoordinate, 0, 0.1f);
addChildWidget(materiaWidget, (Widget*)createGameAssetWidget(assetInitParams, std::string("SPH")), std::string("SPH"));
return materiaWidget;
}
void materiaEntryUpdater(CollectionWidget* self, Widget*widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto textWidget = getChild(widget, std::string("TXT"));
auto sphereWidget = getChild(widget, std::string("SPH"));
auto materiaID = gContext.materiaInventory->getResource(flatIndex).item_id;
if (materiaID != 0xFFFF) {
enableWidget(textWidget);
const char* name = gContext.gameStrings.materia_names.get_string(materiaID);
updateText(textWidget, name);
updateTextColor(textWidget, COLOR_WHITE);
enableWidget(sphereWidget);
transformAsset(sphereWidget, 128, 32, 16, 16);
auto materiaAssetType = getMateriaColorType(materiaID);
updateAssetType(sphereWidget, materiaAssetType);
}
else {
disableWidget(textWidget);
disableWidget(sphereWidget);
}
}
void initMateriaDataWidget(const MenuInitEvent* event) {
DrawTextParams textParams;
DrawBoxParams boxParams;
DrawGameAssetParams gameAssetParams;
DrawNumberParams numberParams;
DrawStaticGridParams staticGridParams;
const char* menuText;
auto menuObject = event->menu;
auto mainWidget = menuObject->menuWidget;
auto materiaDataWidget = createWidget(MATERIA_DATA_WIDGET_NAME);
auto standardDisplayWidget = createWidget(STANDARD_DISPLAY);
boxParams = {
0,
190,
680,
300,
0.4f
};
addChildWidget(materiaDataWidget, (Widget*)createBoxWidget(boxParams, MATERIA_DATA_BOX), MATERIA_DATA_BOX);
//Stuff that can change
setTextParams(&textParams, 40, 214, nullptr, COLOR_WHITE, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createTextWidget(textParams, MATERIA_NAME), MATERIA_NAME);
setTextParams(&textParams, 40, 244, nullptr, COLOR_GREEN, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createTextWidget(textParams, MATERIA_ELEMENT), MATERIA_ELEMENT);
gameAssetParams = MateriaSphere(13, 212, 0xA, 0.01f);
addChildWidget(standardDisplayWidget, (Widget*)createGameAssetWidget(gameAssetParams, MATERIA_SPHERE), MATERIA_SPHERE);
setNumberParams(&numberParams, 238, 244, 0, 7, COLOR_WHITE, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createNumberWidget(numberParams, CURRENT_AP), CURRENT_AP);
setNumberParams(&numberParams, 250, 270, 0, 7, COLOR_WHITE, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createNumberWidget(numberParams, TO_LEVEL_AP), TO_LEVEL_AP);
setStaticGridParams(&staticGridParams, 207, 212, 5, 1, 25, 0, nullptr, nullptr);
StaticGridWidget* starWidget = createStaticGridWidget(staticGridParams, MATERIA_STARS);
moveWidget((Widget*)starWidget, 207, 212);
for (auto row = 0; row < 5; ++row) {
auto name = std::to_string(row);
gameAssetParams = MateriaStar(207, 212, 0xA, 0.1f, false);
addChildWidget((Widget*)starWidget, (Widget*)createGameAssetWidget(gameAssetParams, name), name);
}
addChildWidget(standardDisplayWidget, (Widget*)starWidget, MATERIA_STARS);
/*Static Texts*/
menuText = gContext.gameStrings.materiaMenuTexts.get_string(4);
setTextParams(&textParams, 108, 270, menuText, COLOR_TEAL, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createTextWidget(textParams, NEXT_LVL_TEXT), NEXT_LVL_TEXT);
menuText = gContext.gameStrings.materiaMenuTexts.get_string(5);
setTextParams(&textParams, 207, 244, menuText, COLOR_TEAL, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createTextWidget(textParams, AP_TEXT), AP_TEXT);
menuText = gContext.gameStrings.materiaMenuTexts.get_string(8);
setTextParams(&textParams, 250, 244, menuText, COLOR_WHITE, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createTextWidget(textParams, MASTERED), MASTERED);
menuText = gContext.gameStrings.materiaMenuTexts.get_string(7);
setTextParams(&textParams, 187, 300, menuText, COLOR_TEAL, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createTextWidget(textParams, ABILITIES_LIST_TXT), ABILITIES_LIST_TXT);
menuText = gContext.gameStrings.materiaMenuTexts.get_string(6);
setTextParams(&textParams, 8, 300, menuText, COLOR_TEAL, 0.1f);
addChildWidget(standardDisplayWidget, (Widget*)createTextWidget(textParams, EQUIP_EFFECT_TXT), EQUIP_EFFECT_TXT);
/*Static Array Widgets*/
auto rowCount = 5;
setStaticGridParams(&staticGridParams, 25, 326, 1, rowCount, 0, 26, nullptr, nullptr); //consider whether to use an updater here or not for updating the texts being displayed
StaticGridWidget* abilityListWidget = createStaticGridWidget(staticGridParams, ABILITIES_LIST);
for (auto row = 0; row < rowCount; ++row) {
auto name = std::to_string(row);
auto statEffectRow = createWidget(name); //contains a percent sign, a plus sign, a colored number, and a stat name
moveWidget(statEffectRow, 25, 326);
setTextParams(&textParams, 25, 326, menuText, COLOR_WHITE, 0.1f);
addChildWidget(statEffectRow, (Widget*)createTextWidget(textParams, std::string("TXT")), std::string("TXT"));
setNumberParams(&numberParams, 110, 330, 0, 3, COLOR_WHITE, 0.1f);
addChildWidget(statEffectRow, (Widget*)createNumberWidget(numberParams, std::string("AMT")), std::string("AMT"));
auto simpleAssetParams = Sign(98, 330, COLOR_WHITE, 0.1f, true);
addChildWidget(statEffectRow, (Widget*)createSimpleGameAssetWidget(simpleAssetParams, std::string("SIGN")), std::string("SIGN"));
simpleAssetParams = Percent(145, 330, COLOR_WHITE, 0.1f);
addChildWidget(statEffectRow, (Widget*)createSimpleGameAssetWidget(simpleAssetParams, std::string("PCNT")), std::string("PCNT"));
addChildWidget((Widget*)abilityListWidget, (Widget*)statEffectRow, name);
}
addChildWidget(standardDisplayWidget, (Widget*)abilityListWidget, ABILITIES_LIST);
setStaticGridParams(&staticGridParams, 200, 326, 1, rowCount, 0, 26, nullptr, nullptr);
StaticGridWidget* equipEffectWidget = createStaticGridWidget(staticGridParams, EQUIP_EFFECTS);
moveWidget((Widget*)equipEffectWidget, 200, 326);
for (auto row = 0; row < rowCount; ++row) {
auto name = std::to_string(row);
auto statEffectRow = createWidget(name);
setTextParams(&textParams, 200, 326, menuText, COLOR_WHITE, 0.1f);
addChildWidget(statEffectRow, (Widget*)createTextWidget(textParams, std::string("TXT")), std::string("TXT"));
setNumberParams(&numberParams, 313, 326, 0, 3, COLOR_WHITE, 0.1f);
addChildWidget(statEffectRow, (Widget*)createNumberWidget(numberParams, std::string("AMT")), std::string("AMT"));
auto simpleAssetParams = Sign(300, 326, COLOR_WHITE, 0.1f);
addChildWidget(statEffectRow, (Widget*)createSimpleGameAssetWidget(simpleAssetParams, std::string("SIGN")), std::string("SIGN"));
simpleAssetParams = Percent(337, 326, COLOR_WHITE, 0.1f);
addChildWidget(statEffectRow, (Widget*)createSimpleGameAssetWidget(simpleAssetParams, std::string("PCNT")), std::string("PCNT"));
addChildWidget((Widget*)equipEffectWidget, (Widget*)statEffectRow, name);
}
addChildWidget(standardDisplayWidget, (Widget*)equipEffectWidget, EQUIP_EFFECTS);
addChildWidget(materiaDataWidget, standardDisplayWidget, STANDARD_DISPLAY);
addChildWidget(mainWidget, materiaDataWidget, MATERIA_DATA_WIDGET_NAME);
}
/*Initializes the command view widget used */
void initCommandViewWidget(const MenuInitEvent* event) {
auto commandChoiceCursor = getStateCursor(event->menu, 3);
drawGridParams gridParams;
CursorGridWidget* gridWidget;
BoxWidget* boxWidget;
DrawBoxParams boxParams;
auto menuObject = event->menu;
auto mainWidget = menuObject->menuWidget;
auto commandViewWidget = createWidget(COMMAND_VIEW_WIDGET_NAME);
boxParams = {
0x2F,
0xD6,
98,
0x78,
0.3f
};
boxWidget = createBoxWidget(boxParams, CMD_GRID_BOX);
addChildWidget(commandViewWidget, (Widget*)boxWidget, CMD_GRID_BOX);
gridParams = { MATERIA_MENU_NAME.c_str(), 3, &commandNameViewUpdater, 0x2F + 10, 0xD6 + 11, nullptr, 0 };
gridWidget = createGridWidget(gridParams, CMD_GRID, TextWidgetKlass());
addChildWidget(commandViewWidget, (Widget*)gridWidget, CMD_GRID);
addChildWidget(mainWidget, commandViewWidget, COMMAND_VIEW_WIDGET_NAME);
}
/*Temporary function until we also provide infrastructure for extending the number of commands*/
void commandNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto commands = PARTY_STRUCT_ARRAY[*MAT_MENU_PARTY_INDEX].enabledCommandArray;
auto commandID = commands[flatIndex].commandID;
if (commandID == 0xFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
updateText(widget, gContext.gameStrings.command_names.get_string(commandID));
updateTextColor(widget, COLOR_WHITE);
}
/*Initializes the spell view Widget used*/
void initSpellViewWidget(const MenuInitEvent* event) {
drawGridParams gridParams;
CursorGridWidget* gridWidget;
BoxWidget* boxWidget;
DrawBoxParams boxParams;
auto mainWidget = event->menu->menuWidget;
auto spellViewWidget = createWidget(SPELL_VIEW_WIDGET_NAME);
boxParams = {
0x2F,
0x157,
0x1A2,
0x78,
0.203f
};
boxWidget = createBoxWidget(boxParams, SPELL_VIEW_BOX);
addChildWidget(spellViewWidget, (Widget*)boxWidget, SPELL_VIEW_BOX);
gridParams = { MATERIA_MENU_NAME.c_str(), 4, &spellNameViewUpdater, 0x2F + 35, 0x157 + 13, nullptr, 0 };
addChildWidget(spellViewWidget, (Widget*)createGridWidget(gridParams, SPELL_GRID, TextWidgetKlass()), SPELL_GRID);
gridParams = { MATERIA_MENU_NAME.c_str(), 5, &summonNameViewUpdater, 0x2F + 93, 0x157 + 13, nullptr, 0 };
addChildWidget(spellViewWidget, (Widget*)createGridWidget(gridParams, SUMMON_GRID, TextWidgetKlass()) , SUMMON_GRID);
gridParams = { MATERIA_MENU_NAME.c_str(), 6, &eskillNameViewUpdater, 0x2F + 40 , 0x157 + 13, nullptr, 0 };
addChildWidget(spellViewWidget, (Widget*)createGridWidget(gridParams, ESKILL_GRID, TextWidgetKlass()), ESKILL_GRID);
addChildWidget(mainWidget, spellViewWidget, SPELL_VIEW_WIDGET_NAME);
}
void spellNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto& magics = getSrPartyMember(*MAT_MENU_PARTY_INDEX).srPartyMember->actorMagics;
if (magics[flatIndex].magicIndex == 0xFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
updateText(widget, getCommandAction(CMD_MAGIC, magics[flatIndex].magicIndex).attackName.str());
updateTextColor(widget, COLOR_WHITE);
}
void summonNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto summons = getSrPartyMember(*MAT_MENU_PARTY_INDEX).srPartyMember->actorSummons;
if (summons[flatIndex].magicIndex == 0xFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
updateText(widget, getCommandAction(CMD_SUMMON, summons[flatIndex].magicIndex).attackName.str());
updateTextColor(widget, COLOR_WHITE);
}
void eskillNameViewUpdater(CollectionWidget* self, Widget* widget, u16 flatIndex) {
if (self->collectionType != GridWidgetClass()) {
return;
}
auto typedPtr = (CursorGridWidget*)self;
auto eSkills = getSrPartyMember(*MAT_MENU_PARTY_INDEX).srPartyMember->actorEnemySkills;
if (eSkills[flatIndex].magicIndex == 0xFF) {
disableWidget(widget);
return;
}
enableWidget(widget);
updateText(widget, getCommandAction(CMD_ENEMY_SKILL, eSkills[flatIndex].magicIndex).attackName.str());
updateTextColor(widget, COLOR_WHITE);
}
| 45.20603 | 178 | 0.726378 | [
"vector"
] |
33b353b25d3929caf5221e329ba572aed90e18fa | 22,201 | cc | C++ | src/listmerger/utilities.cc | mahmoudimus/flamingo | 61b46a9f57c9aa4050b0dd8b95a44e1abef0d006 | [
"Unlicense"
] | 4 | 2018-08-23T08:05:33.000Z | 2019-06-13T09:23:27.000Z | src/listmerger/utilities.cc | mahmoudimus/flamingo | 61b46a9f57c9aa4050b0dd8b95a44e1abef0d006 | [
"Unlicense"
] | null | null | null | src/listmerger/utilities.cc | mahmoudimus/flamingo | 61b46a9f57c9aa4050b0dd8b95a44e1abef0d006 | [
"Unlicense"
] | null | null | null | /*
$Id: utilities.cc 5149 2010-03-24 23:37:18Z abehm $
Copyright (C) 2010 by The Regents of the University of California
Redistribution of this file is permitted under the terms of
the BSD license.
Author: Jiaheng Lu
Date: 05/11/2007
*/
#include "utilities.h"
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <functional>
#include <iterator>
#include <list>
#include <algorithm>
#include <cassert>
#include "heap.h"
#include "showutil.h"
using namespace std;
typedef set<unsigned, less<unsigned> > UnsignedSet;
unsigned
getTotalLogSize(const vector<Array<unsigned>*> &lists)
{
unsigned totalSize = 0;
unsigned numberOfLists = lists.size();
for (unsigned i = 0; i < numberOfLists; i++)
totalSize += (unsigned) ceil(log(lists.at(i)->size()));
return totalSize;
}//end getTotalSize
unsigned
getTotalSize(const vector<Array<unsigned>*> &lists)
{
unsigned totalSize = 0;
unsigned numberOfLists = lists.size();
for (unsigned i = 0; i < numberOfLists; i++) {
totalSize += lists.at(i)->size();
// cout <<"i is " << i <<
//" size is "<< lists.at(i)->size() <<endl;
}//end for
return totalSize;
}//end getTotalSize
/*
This function is for the test of
consistent of two different merge
algorithms.
The order of results does not matter.
*/
bool
testConsistent(const vector<unsigned> &result1,
const vector<unsigned> &result2)
{
if (result1.size() != result2.size())
return false;
UnsignedSet s1(result1.begin(), result1.end());
UnsignedSet s2(result2.begin(), result2.end());
UnsignedSet::iterator ite1 = s1.begin();
UnsignedSet::iterator ite2 = s2.begin();
while (ite1 != s1.end()) {
if (*ite1 != *ite2)
return false;
ite1++;
ite2++;
}//end while
return true;
}// end testConsistent
bool
binarySearch(Array<unsigned> *v,
unsigned value,
unsigned start,
unsigned end)
{
int low = start;
int high = end - 1;
int middle = (low + high + 1) / 2;
bool found = false;
do {
if (value == v->at(middle))
return true;
else if (value < v->at(middle))
high = middle - 1;
else
low = middle + 1;
middle = (low + high + 1) / 2;
} while ((low <= high) &&
(found == false)
);
return found;
}//end binarySearch
/*
Get statics data frbom running
*/
void
getStatistics(const vector<Array<unsigned>*> &arrays,
unsigned threshold,
unsigned longListsSize,
const vector<unsigned> &partialResults,
const vector<unsigned> &results)
{
cout << "~~~~~~~~~~~~~~" << endl;
cout << "Partial results size is " << partialResults.size() << endl;
cout << "Final results size is " << results.size() << endl;
cout << "Threshold is " << threshold << "; Long lists size is " << longListsSize << endl;
cout << "# of lists is " << arrays.size() << endl;
cout << "**************" << endl;
}//end getStatistics
/*
This function is for DividedSkip algorithm
Seperate to long and short lists sets.
For short lists, use binarySearch;
For long lists, use hash to search.
*/
void
splitTwoSets(vector<Array<unsigned>*> *longLists,
vector<Array<unsigned>*> *shortLists,
const unsigned threshold,
const vector<Array<unsigned>*> &originalLists,
unsigned sortedIndex[],
unsigned longListsSize)
{
unsigned originalListSize = originalLists.size();
for (unsigned i = 0; i < originalListSize; i++) {
if (i < longListsSize)
longLists->push_back(originalLists.at(sortedIndex[originalListSize - i - 1]));
else
shortLists->push_back(originalLists.at(sortedIndex[originalListSize - i - 1]));
}//end for
}//end splitTwoSets
void
splitTwoSizeSets(vector<unsigned> *longLists,
vector<unsigned> *shortLists,
const unsigned threshold,
const vector<unsigned> &originalLists,
unsigned sortedIndex[],
unsigned longListsSize)
{
unsigned originalListSize = originalLists.size();
for (unsigned i = 0; i < originalListSize; i++) {
if (i < longListsSize)
longLists->push_back(originalLists.at(sortedIndex[originalListSize - i - 1]));
else
shortLists->push_back(originalLists.at(sortedIndex[originalListSize - i - 1]));
}//end for
}//end splitTwoSets
void
splitTwoSetsWithDuplicates(vector<Array<unsigned>*> &longLists,
vector<Array<unsigned>*> &shortLists,
vector<unsigned> &longListsWeights,
vector<unsigned> &shortListsWeights,
const vector<Array<unsigned>*> &originalLists,
const vector<unsigned> &originalWeights,
const unsigned shortListsSize)
{
unsigned originalListSize = originalLists.size();
for (unsigned i = 0; i < originalListSize; i++) {
if (i < shortListsSize) {
shortLists.push_back(originalLists.at(i));
shortListsWeights.push_back(originalWeights.at(i));
} else {
longLists.push_back(originalLists.at(i));
longListsWeights.push_back(originalWeights.at(i));
}
}//end for
// ORIGINAL CODE BELOW BY JIAHENG
// FIXED BY ALEX (ABOVE CODE)
/*
unsigned originalListSize = originalLists.size();
unsigned currentWeight = 0;
unsigned i = 0;
while ((currentWeight+originalWeights.at(i)) < shortListsSize )
{
currentWeight += originalWeights.at(i);
shortLists.push_back(originalLists.at(i));
shortListsWeights.push_back(originalWeights.at(i));
i++;
}//end for
shortLists.push_back(originalLists.at(i));
shortListsWeights.push_back(shortListsSize-currentWeight);
unsigned listSizeforLonger =
currentWeight+originalWeights.at(i)-shortListsSize;
if ( listSizeforLonger >0)
{
longLists.push_back(originalLists.at(i));
longListsWeights.push_back(listSizeforLonger);
}
i++;
for(; i<originalListSize;i++)
{
longLists.push_back(originalLists.at(i));
longListsWeights.push_back(originalWeights.at(i));
}//end for
*/
}//end splitTwoSetsWithDuplicates
/*
This function is for MergeOpt algorithm
Seperate to long and short lists sets.
*/
void
separateTwoSets(vector<Array<unsigned>*> *longLists,
vector<Array<unsigned>*> *shortLists,
const unsigned threshold,
const vector<Array<unsigned>*> &originalLists,
unsigned sortedIndex[])
{
unsigned originalListSize = originalLists.size();
for (unsigned i = 0; i < originalListSize; i++) {
if (i < threshold - 1)
longLists->push_back(originalLists.at(sortedIndex[originalListSize - i - 1]));
else
shortLists->push_back(originalLists.at(sortedIndex[originalListSize - i - 1]));
}//end for
}//end separateTwoSets
/*
Use binray search to search the value
in search set of lists;
change the count
*/
void
binarySearchSet(unsigned &count,
vector<Array<unsigned>* > *lists,
unsigned data)
{
vector<Array<unsigned>*>::iterator ite =
lists->begin();
while (ite != lists->end()) {
Array<unsigned> *v = *ite;
if (binarySearch(v, data, 0, v->size()))
count++;
ite++;
}//end while
}//end binarySearchSet
void
sortBySize(const vector<unsigned> &allLists,
unsigned sortedIndex [])
{
vector<unsigned>::const_iterator ite = allLists.begin();
unsigned sizeHeap[allLists.size()];
unsigned indexHeap[allLists.size()];
unsigned index = 0;
unsigned heapSize = 0;
while (ite != allLists.end()) {
unsigned sizeOfList = *ite;
heapInsert(sizeOfList, index++, sizeHeap, indexHeap, heapSize);
ite++;
}//end while
index = 0;
while (heapSize > 0) {
sortedIndex[index++] = indexHeap[0];
heapDelete(sizeHeap, indexHeap, heapSize);
}//end while
}//end sortInvertedList
/*
Sort the inverted list with increasing order
according to the their sizes
by heapSort
This function is used in MergeOpt.
*/
void
sortBySizeOfLists(const vector<Array<unsigned>*> &allLists,
unsigned sortedIndex [])
{
vector<Array<unsigned>*>::const_iterator ite = allLists.begin();
unsigned sizeHeap[allLists.size()];
unsigned indexHeap[allLists.size()];
unsigned index = 0;
unsigned heapSize = 0;
while (ite != allLists.end()) {
unsigned sizeOfList = (*ite)->size();
heapInsert(sizeOfList, index++, sizeHeap, indexHeap, heapSize);
ite++;
}//end while
index = 0;
while (heapSize > 0) {
sortedIndex[index++] = indexHeap[0];
heapDelete(sizeHeap, indexHeap, heapSize);
}//end while
}//end sortInvertedList
/* Insert items to heap
This function is used in binarySearchMerger
*/
void
insertToHeaps(unsigned dataHeap[],
unsigned indexHeap[],
unsigned &heapSize,
const vector< Array<unsigned>* > &lists,
unsigned pointersIndexList[],
unsigned vectorIndexContainer[],
unsigned containerSize)
{
for (unsigned i = 0; i < containerSize; i++) {
unsigned index = vectorIndexContainer[i];
unsigned position = pointersIndexList[index];
unsigned newData =
(lists.at(index))->at(position);
heapInsert(newData, index, dataHeap, indexHeap, heapSize);
}//end for
}//end insertToHeaps
/*
This fucntion skips nodes
for mergebinarySeach algorithm
*/
void
skipNodes(const vector<Array<unsigned>* > &lists,
unsigned vectorIndexContainer[],
unsigned containerSize,
unsigned pivotData,
unsigned pointersIndexList[])
{
for (unsigned i = 0; i < containerSize; i++) {
unsigned j = vectorIndexContainer[i];
unsigned oldPosition = pointersIndexList[j];
pointersIndexList[j] =
lists.at(j)->binarySearch(pivotData, oldPosition);
// cout<< "new data" << lists.at(j)->at( pointersIndexList[j]) <<
// " old data " << pivotData <<endl;
//assert(lists.at(j)->at( pointersIndexList[j]) >= pivotData);
}//end for
}//end skipNodes
/*
This function can be deleted for the final release
*/
void
CountSkipNodes(const vector<Array<unsigned>* > &lists,
unsigned vectorIndexContainer[],
unsigned containerSize,
unsigned pivotData,
unsigned pointersIndexList[],
unsigned &elementScanned)
{
for (unsigned i = 0; i < containerSize; i++) {
unsigned j = vectorIndexContainer[i];
unsigned oldPosition = pointersIndexList[j];
pointersIndexList[j] =
lists.at(j)->binarySearch(pivotData, oldPosition);
elementScanned += (unsigned) ceil(0.01 * log(lists.at(j)->size()));
// cout<< "new data" << lists.at(j)->at( pointersIndexList[j]) <<
// " old data " << pivotData <<endl;
//assert(lists.at(j)->at( pointersIndexList[j]) >= pivotData);
}//end for
}//end skipNodes
unsigned
max(unsigned s1, unsigned s2)
{
if (s1 > s2)
return s1;
else
return s2;
}//end max
/*
This function selects the shorest
string for computing the thresholds
in filters.
*/
unsigned
shorestStringSize(const vector<string> &strings
)
{
unsigned minSize = ~0;
for (unsigned i = 0; i < (unsigned) strings.size(); i++) {
unsigned s = strings.at(i).length();
if (s < minSize)
minSize = s;
}//end for
return minSize;
}//end
/*
This function is only for MergeSkip algorithm.
Use MergeSkip algorithm to process
short lists in DivideSkip algorithm.
*/
void
mergeSkipShortLists(const vector<Array<unsigned>*> &arrays,
const unsigned threshold,
vector<unsigned> &results,
vector<unsigned> &counters)
{
//const unsigned maxUnsigned = 0x10000000 - 2;
const unsigned maxUnsigned = 0xFFFFFFFF;
unsigned numberOfInvertedList = arrays.size();
if (threshold > numberOfInvertedList)
return; // no answer
unsigned pointersIndex [numberOfInvertedList];
for (unsigned k = 0; k < numberOfInvertedList; k++)
pointersIndex[k] = 0;
addMAXUnsigned2EachList(arrays, maxUnsigned);
unsigned dataHeap [numberOfInvertedList];
unsigned indexHeap [numberOfInvertedList];
makeInitialHeap(dataHeap, indexHeap, arrays);
unsigned sizeOfHeaps = numberOfInvertedList;
unsigned pivot = threshold - 1;
while (dataHeap[0] < maxUnsigned) {
//cout<< " Current heaps are : " << endl;
//printArrayUnsigned (dataHeap, sizeOfHeaps);
//printArrayUnsigned (indexHeap, sizeOfHeaps);
// Container of vector indexes which should be moved to the next position
unsigned vectorIndexContainer[numberOfInvertedList];
unsigned containerSize = 0;
// Check if we can get the result
unsigned minData = dataHeap[0];
while (minData == dataHeap[0] && containerSize < numberOfInvertedList) {
vectorIndexContainer[containerSize++] = indexHeap[0];
heapDelete(dataHeap, indexHeap, sizeOfHeaps);
}//end while
if (containerSize >= threshold) // we got the result
{
counters.push_back(containerSize);
results.push_back(minData);
//cout<< "We get a result, rule ID is " << minData <<", count is " << containerSize <<endl;
//move to the next element
for (unsigned i = 0; i < containerSize; i++) {
unsigned j = vectorIndexContainer[i];
pointersIndex[j]++;
}//end for
insertToHeaps(dataHeap, indexHeap,
sizeOfHeaps,
arrays, pointersIndex,
vectorIndexContainer,
containerSize);
continue;
}//end if
// pop more elements from heap
// and skip nodes
while (containerSize < pivot) {
vectorIndexContainer[containerSize++] = indexHeap[0];
heapDelete(dataHeap, indexHeap, sizeOfHeaps);
}//end while (containerSize < pivot )
//printArray( vectorIndexContainer,containerSize);
// cout<< "Pivot node is " << dataHeap[0] << endl;
skipNodes(arrays, vectorIndexContainer, containerSize,
dataHeap[0], pointersIndex);
//cout<<"After skip, current nodes are : " <<endl;
//showCurrentNodes(&pointersNode, &pointersIndex, numberOfInvertedList);
insertToHeaps(dataHeap,
indexHeap,
sizeOfHeaps,
arrays,
pointersIndex,
vectorIndexContainer,
containerSize);
}//end while ( thresholdHeap[0] < MAX)
deleteMAXUnsignedfromEachList(arrays);
}//end mergeSkipShortLists
void
mergeSkipShortListsWithDuplicate(const vector<Array<unsigned>*> &arrays,
const vector<unsigned> &weights,
const unsigned threshold,
vector<unsigned> &results,
vector<unsigned> &counters)
{
const unsigned maxUnsigned = 0xFFFFFFFF;
unsigned numberOfInvertedList = arrays.size();
unsigned pointersIndex [numberOfInvertedList];
for (unsigned k = 0; k < numberOfInvertedList; k++)
pointersIndex[k] = 0;
addMAXUnsigned2EachList(arrays, maxUnsigned);
unsigned dataHeap [numberOfInvertedList];
unsigned indexHeap [numberOfInvertedList];
makeInitialHeap(dataHeap, indexHeap, arrays);
unsigned sizeOfHeaps = numberOfInvertedList;
unsigned pivot = threshold - 1;
while (dataHeap[0] < maxUnsigned) {
//cout<< " Current heaps are : " << endl;
//printArrayUnsigned (dataHeap, sizeOfHeaps);
//printArrayUnsigned (indexHeap, sizeOfHeaps);
// Container of vector indexes which should be moved to the next position
unsigned vectorIndexContainer[numberOfInvertedList];
unsigned containerWeight = 0, containerSize = 0;
// Check if we can get the result
unsigned minData = dataHeap[0];
while (minData == dataHeap[0] && containerSize < numberOfInvertedList) {
vectorIndexContainer[containerSize++] = indexHeap[0];
containerWeight += weights[indexHeap[0]];
heapDelete(dataHeap, indexHeap, sizeOfHeaps);
}//end while
if (containerWeight >= threshold) // we got the result
{
counters.push_back(containerWeight);
results.push_back(minData);
//cout<< "We get a result, rule ID is " << minData <<", count is " << containerSize <<endl;
//move to the next element
for (unsigned i = 0; i < containerSize; i++) {
unsigned j = vectorIndexContainer[i];
pointersIndex[j]++;
}//end for
insertToHeaps(dataHeap, indexHeap,
sizeOfHeaps,
arrays, pointersIndex,
vectorIndexContainer,
containerSize);
continue;
}//end if
// pop more elements from heap
// and skip nodes
while (containerWeight < pivot) {
// FIX BY ALEX
// it is possible for a list to have a weight equals to T
if (containerWeight + weights[indexHeap[0]] > pivot) break;
vectorIndexContainer[containerSize++] = indexHeap[0];
containerWeight += weights[indexHeap[0]];
heapDelete(dataHeap, indexHeap, sizeOfHeaps);
}//end while (containerWeight < pivot )
//printArray( vectorIndexContainer,containerSize);
// cout<< "Pivot node is " << dataHeap[0] << endl;
skipNodes(arrays, vectorIndexContainer, containerSize,
dataHeap[0], pointersIndex);
//cout<<"After skip, current nodes are : " <<endl;
//showCurrentNodes(&pointersNode, &pointersIndex, numberOfInvertedList);
insertToHeaps(dataHeap,
indexHeap,
sizeOfHeaps,
arrays,
pointersIndex,
vectorIndexContainer,
containerSize);
}//end while ( thresholdHeap[0] < MAX)
deleteMAXUnsignedfromEachList(arrays);
}//end mergeSkipShortListsWithDuplicate
/*
void detectDuplicateLists(const vector<Array<unsigned>*> &arrays,
vector<Array<unsigned>*> &newArrays,
vector<unsigned> &newWeights)
{
unsigned sizeOfInvertedLists = arrays.size();
unsigned sortedIndex[sizeOfInvertedLists];
sortBySizeOfLists(arrays,sortedIndex);//increasing order
Array<unsigned> *currentArray=arrays.at(sortedIndex[0]);
unsigned currentCount = 1;
for(unsigned i=1;i<sizeOfInvertedLists;i++)
{
Array<unsigned> *iArray = arrays.at(sortedIndex[i]);
if (iArray == currentArray)
currentCount++;
else
{
newArrays.push_back(currentArray);
newWeights.push_back(currentCount);
currentCount = 1;
currentArray = iArray;
}//end if
}//end for
newArrays.push_back(currentArray);
newWeights.push_back(currentCount);
}//end detectDuplicateLists
*/
// BUGFIX BY ALEX
void
detectDuplicateLists(const vector<Array<unsigned>*> &arrays,
vector<Array<unsigned>*> &newArrays,
vector<unsigned> &newWeights)
{
unsigned sizeOfInvertedLists = arrays.size();
unsigned sortedIndex[sizeOfInvertedLists];
sortBySizeOfLists(arrays, sortedIndex);
// we need to take care of unequal lists with the same size
// do exhaustive search within each list length group
set<uintptr_t> arraysAdded;
for (unsigned i = 0; i < sizeOfInvertedLists; i++) {
Array<unsigned> *currentArray = arrays.at(sortedIndex[i]);
uintptr_t arrAddr = reinterpret_cast<uintptr_t>(currentArray);
unsigned currentCount = 1;
// if the array has not been added previously
if (arraysAdded.find(arrAddr) == arraysAdded.end()) {
// search all arrays with the same length for identical pointers
for (unsigned j = i + 1; j < sizeOfInvertedLists; j++) {
Array<unsigned> *iArray = arrays.at(sortedIndex[j]);
if (iArray->size() != currentArray->size()) break;
if (iArray == currentArray) currentCount++;
}
// add the array
newArrays.push_back(currentArray);
newWeights.push_back(currentCount);
arraysAdded.insert(arrAddr);
}
}
// ALEX DEBUG
/*
unsigned weightSum = 0;
for(unsigned i = 0; i < newArrays.size(); i++) {
Array<unsigned>* tmp = newArrays.at(i);
bool contains = false;
for(unsigned j = 0; j < tmp->size(); j++) {
if(tmp->at(j) == 49) {
contains = true;
break;
}
}
if(contains) {
cout << "LIST: " << (unsigned)newArrays.at(i) << " " << newWeights.at(i) << endl;
weightSum += newWeights.at(i);
}
}
cout << "WEIGHTSUM: " << weightSum << endl;
*/
}
| 25.966082 | 103 | 0.594838 | [
"vector"
] |
33b4a7fb3b3606cb66fee81219d5695e5603dfba | 5,143 | hh | C++ | src/BddToHDL.hh | mkhaled87/BDD2Implement | 4cacf10432d259f53c8a06e8f650eb66e3185a93 | [
"BSD-3-Clause"
] | 2 | 2019-10-10T21:39:43.000Z | 2020-12-21T20:34:12.000Z | src/BddToHDL.hh | mkhaled87/BDD2Implement | 4cacf10432d259f53c8a06e8f650eb66e3185a93 | [
"BSD-3-Clause"
] | null | null | null | src/BddToHDL.hh | mkhaled87/BDD2Implement | 4cacf10432d259f53c8a06e8f650eb66e3185a93 | [
"BSD-3-Clause"
] | null | null | null | #ifndef BDDTOHDL_HH_
#define BDDTOHDL_HH_
#include "cuddObj.hh"
#include "BddReader.hh"
#include "BddToString.hh"
#include "BddDecomposer.hh"
#include "utils.hh"
/*
* a class to construct HDL codes from the BDD
*/
class BddToHDL{
Cudd* cuddManager;
size_t STATES_BDDVARSCOUNT;
size_t ACTION_BDDVARSCOUNT;
bool useLocalReader;
BDDReader *reader;
BDD passedBDD;
public:
BddToHDL(Cudd& _mgr, const char* filename, BDD_FILE_TYPE type, size_t state_bddVar_count, size_t action_bddVar_count){
STATES_BDDVARSCOUNT = state_bddVar_count;
ACTION_BDDVARSCOUNT = action_bddVar_count;
cuddManager = &_mgr;
reader = new BDDReader(*cuddManager, filename, type);
passedBDD = cuddManager->bddZero();
useLocalReader = true;
}
BddToHDL(Cudd& _mgr, const BDD& givenBdd, size_t state_bddVar_count, size_t action_bddVar_count){
STATES_BDDVARSCOUNT = state_bddVar_count;
ACTION_BDDVARSCOUNT = action_bddVar_count;
cuddManager = &_mgr;
passedBDD = givenBdd;
useLocalReader = false;
}
vector<BDD> getDecomposedBdds(bool check, int verbosity=0){
BDD mainBdd;
if(useLocalReader)
mainBdd = reader->ReadBdd();
else
mainBdd = passedBDD;
if (mainBdd == cuddManager->bddZero()){
ostringstream os;
os << "Error: BddToVhdlBooleanFunction::GenerateVHDL: invalid BDD ! BDD is zero function.";
throw invalid_argument(os.str().c_str());
}
if(verbosity > 0)
std::cout << "Decomposing the BDD to multi-functions ... " << std::endl;
BddOutputDecomposer decomposer(*cuddManager, mainBdd, STATES_BDDVARSCOUNT, ACTION_BDDVARSCOUNT);
vector<BDD> subBdds = decomposer.Decompose(verbosity);
if(check){
BDD composed_back = decomposer.Compose(subBdds);
if(verbosity > 1){
BDDUtils::PrintBDD("mainBdd", mainBdd);
BDDUtils::PrintBDD("composed_back", composed_back);
BDDUtils::PrintBDD("mainBdd*composed_back", mainBdd*composed_back);
}
if(mainBdd == mainBdd*composed_back)
std::cout << "Checking decomposed BDD succceeded !" << std::endl;
else
std::cout << "Checking decomposed BDD failed !" << std::endl;
}
return subBdds;
}
void GenerateRawVHDL(string outFilename, bool check=false, int verbosity=0){
const string template_file = "../../templates/BooleanFunctions.vhdl";
vector<BDD> subBdds = getDecomposedBdds(check, verbosity);
BddToStringConverter converter(*cuddManager, "and", "or", "not");
if(verbosity > 0)
std::cout << "Converting to VHDL code ... ";
stringstream inPorts, outPorts, outFuncs;
for(size_t i=0; i<STATES_BDDVARSCOUNT; i++){
inPorts << "x" << i << ": in std_logic;" << endl;
}
for(size_t i=0; i<ACTION_BDDVARSCOUNT; i++){
outPorts << "f" << i << ": out std_logic";
if(i != ACTION_BDDVARSCOUNT-1)
outPorts << ";" << endl;
}
for(size_t i=0; i<subBdds.size(); i++){
string bddAsString = converter.asShannonForm(subBdds[i]);
outFuncs << "f" << i << " <= " << bddAsString << ";" << endl;
}
string templateText = IOUtils::ReadAllFileText(template_file);
string OutText = StringManipulator::ReplaceString(templateText, "#$ENTITY_INPUT_PORTS$#", inPorts.str());
OutText = StringManipulator::ReplaceString(OutText, "#$ENTITY_OUTPUT_PORTS$#", outPorts.str());
OutText = StringManipulator::ReplaceString(OutText, "#$BEHAVIORAL_OUTPUT_FUNCTIONS$#", outFuncs.str());
OutText = StringManipulator::ReplaceString(OutText, "#$DATES$#", StopWatch::GetCurrentDateTime());
IOUtils::FileWriteAllText(outFilename, OutText);
if(verbosity > 0)
std::cout << "saved to the file: " << outFilename << std::endl;
}
void GenerateRawVerilog(string outFilename, bool check=false, int verbosity=0){
const string template_file = "../../templates/BooleanFunctions.v";
vector<BDD> subBdds = getDecomposedBdds(check, verbosity);
BddToStringConverter converter(*cuddManager, " & ", " | ", "~");
if(verbosity > 0)
std::cout << "Converting to Verilog code ... ";
stringstream inPorts, outPorts, outFuncs;
for(size_t i=0; i<STATES_BDDVARSCOUNT; i++){
inPorts << "input x" << i << "," << endl;
}
for(size_t i=0; i<ACTION_BDDVARSCOUNT; i++){
outPorts << "output f" << i;
if(i != ACTION_BDDVARSCOUNT-1)
outPorts << "," << endl;
}
for(size_t i=0; i<subBdds.size(); i++){
string bddAsString = converter.asShannonForm(subBdds[i]);
outFuncs << "assign f" << i << " = " << bddAsString << ";" << endl;
}
string templateText = IOUtils::ReadAllFileText(template_file);
string OutText = StringManipulator::ReplaceString(templateText, "#$MODULE_INPUT_PORTS$#", inPorts.str());
OutText = StringManipulator::ReplaceString(OutText, "#$MODULE_OUTPUT_PORTS$#", outPorts.str());
OutText = StringManipulator::ReplaceString(OutText, "#$ASSIGN_OUTPUT_FUNCTIONS$#", outFuncs.str());
OutText = StringManipulator::ReplaceString(OutText, "#$DATES$#", StopWatch::GetCurrentDateTime());
IOUtils::FileWriteAllText(outFilename, OutText);
if(verbosity > 0)
std::cout << "saved to the file: " << outFilename << std::endl;
}
~BddToHDL(){
if(useLocalReader)
delete reader;
}
};
#endif
| 31.944099 | 119 | 0.687148 | [
"vector"
] |
33b9f063d03b5b8e6c1eca68bae4470b8ef3fd1b | 3,729 | cpp | C++ | examples/wave_tank/ex1/GravityForcing.cpp | hongk45/IBAMR | 698d419fc6688470a8b9400822ba893da9d07ae2 | [
"BSD-3-Clause"
] | null | null | null | examples/wave_tank/ex1/GravityForcing.cpp | hongk45/IBAMR | 698d419fc6688470a8b9400822ba893da9d07ae2 | [
"BSD-3-Clause"
] | 1 | 2020-11-30T14:22:45.000Z | 2020-12-01T21:28:24.000Z | tests/wave_tank/GravityForcing.cpp | hongk45/IBAMR | 698d419fc6688470a8b9400822ba893da9d07ae2 | [
"BSD-3-Clause"
] | null | null | null | // ---------------------------------------------------------------------
//
// Copyright (c) 2019 - 2019 by the IBAMR developers
// All rights reserved.
//
// This file is part of IBAMR.
//
// IBAMR is free software and is distributed under the 3-clause BSD
// license. The full text of the license can be found in the file
// COPYRIGHT at the top level directory of IBAMR.
//
// ---------------------------------------------------------------------
#include "GravityForcing.h"
/////////////////////////////// INCLUDES /////////////////////////////////////
#include <SAMRAI_config.h>
// SAMRAI INCLUDES
#include <HierarchyDataOpsManager.h>
/////////////////////////////// STATIC ///////////////////////////////////////
/////////////////////////////// PUBLIC ///////////////////////////////////////
GravityForcing::GravityForcing(const std::string& object_name,
Pointer<INSVCStaggeredHierarchyIntegrator> ins_hierarchy_integrator,
std::vector<double> grav_const)
: d_object_name(object_name), d_ins_hierarchy_integrator(ins_hierarchy_integrator), d_grav_const(grav_const)
{
// intentionally blank
return;
} // GravityForcing
bool
GravityForcing::isTimeDependent() const
{
return true;
} // isTimeDependent
void
GravityForcing::setDataOnPatchHierarchy(const int data_idx,
Pointer<Variable<NDIM> > /*var*/,
Pointer<PatchHierarchy<NDIM> > hierarchy,
const double /*data_time*/,
const bool /*initial_time*/,
const int coarsest_ln_in,
const int finest_ln_in)
{
const int coarsest_ln = (coarsest_ln_in == -1 ? 0 : coarsest_ln_in);
const int finest_ln = (finest_ln_in == -1 ? hierarchy->getFinestLevelNumber() : finest_ln_in);
// Get interpolated density variable
const int rho_ins_idx = d_ins_hierarchy_integrator->getLinearOperatorRhoPatchDataIndex();
#if !defined(NDEBUG)
TBOX_ASSERT(rho_ins_idx >= 0);
#endif
for (int ln = coarsest_ln; ln <= finest_ln; ++ln)
{
Pointer<PatchLevel<NDIM> > level = hierarchy->getPatchLevel(ln);
for (PatchLevel<NDIM>::Iterator p(level); p; p++)
{
Pointer<Patch<NDIM> > patch = level->getPatch(p());
const Box<NDIM>& box = patch->getBox();
Pointer<SideData<NDIM, double> > f_data = patch->getPatchData(data_idx);
const Pointer<SideData<NDIM, double> > rho_data = patch->getPatchData(rho_ins_idx);
for (int axis = 0; axis < NDIM; ++axis)
{
for (Box<NDIM>::Iterator it(SideGeometry<NDIM>::toSideBox(box, axis)); it; it++)
{
SideIndex<NDIM> s_i(it(), axis, SideIndex<NDIM>::Lower);
(*f_data)(s_i) = ((*rho_data)(s_i)) * d_grav_const[axis];
}
}
}
}
return;
} // setDataOnPatchHierarchy
void
GravityForcing::setDataOnPatch(const int data_idx,
Pointer<Variable<NDIM> > /*var*/,
Pointer<Patch<NDIM> > patch,
const double /*data_time*/,
const bool initial_time,
Pointer<PatchLevel<NDIM> > /*patch_level*/)
{
if (initial_time)
{
Pointer<SideData<NDIM, double> > f_data = patch->getPatchData(data_idx);
f_data->fillAll(0.0);
}
// Intentionally left blank
} // setDataOnPatch
//////////////////////////////////////////////////////////////////////////////
| 37.29 | 112 | 0.508984 | [
"vector"
] |
33bd2a527519fba928ec862f20ab8744a83070e2 | 11,125 | cpp | C++ | sift_1b.cpp | AmberLJC/hnswlib | 6cff39a9fb61881b9adbdca18ecf8157cfbeecce | [
"Apache-2.0"
] | null | null | null | sift_1b.cpp | AmberLJC/hnswlib | 6cff39a9fb61881b9adbdca18ecf8157cfbeecce | [
"Apache-2.0"
] | null | null | null | sift_1b.cpp | AmberLJC/hnswlib | 6cff39a9fb61881b9adbdca18ecf8157cfbeecce | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <queue>
#include <chrono>
#include "hnswlib/hnswlib.h"
#include <unordered_set>
using namespace std;
using namespace hnswlib;
class StopW {
std::chrono::steady_clock::time_point time_begin;
public:
StopW() {
time_begin = std::chrono::steady_clock::now();
}
float getElapsedTimeMicro() {
std::chrono::steady_clock::time_point time_end = std::chrono::steady_clock::now();
return (std::chrono::duration_cast<std::chrono::microseconds>(time_end - time_begin).count());
}
void reset() {
time_begin = std::chrono::steady_clock::now();
}
};
/*
* Author: David Robert Nadeau
* Site: http://NadeauSoftware.com/
* License: Creative Commons Attribution 3.0 Unported License
* http://creativecommons.org/licenses/by/3.0/deed.en_US
*/
#if defined(_WIN32)
#include <windows.h>
#include <psapi.h>
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>
#include <sys/resource.h>
#if defined(__APPLE__) && defined(__MACH__)
#include <mach/mach.h>
#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
#include <fcntl.h>
#include <procfs.h>
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
#endif
#else
#error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS."
#endif
/**
* Returns the peak (maximum so far) resident set size (physical
* memory use) measured in bytes, or zero if the value cannot be
* determined on this OS.
*/
static size_t getPeakRSS() {
#if defined(_WIN32)
/* Windows -------------------------------------------------- */
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
return (size_t)info.PeakWorkingSetSize;
#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
/* AIX and Solaris ------------------------------------------ */
struct psinfo psinfo;
int fd = -1;
if ((fd = open("/proc/self/psinfo", O_RDONLY)) == -1)
return (size_t)0L; /* Can't open? */
if (read(fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo))
{
close(fd);
return (size_t)0L; /* Can't read? */
}
close(fd);
return (size_t)(psinfo.pr_rssize * 1024L);
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
/* BSD, Linux, and OSX -------------------------------------- */
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
#if defined(__APPLE__) && defined(__MACH__)
return (size_t)rusage.ru_maxrss;
#else
return (size_t) (rusage.ru_maxrss * 1024L);
#endif
#else
/* Unknown OS ----------------------------------------------- */
return (size_t)0L; /* Unsupported. */
#endif
}
/**
* Returns the current resident set size (physical memory use) measured
* in bytes, or zero if the value cannot be determined on this OS.
*/
static size_t getCurrentRSS() {
#if defined(_WIN32)
/* Windows -------------------------------------------------- */
PROCESS_MEMORY_COUNTERS info;
GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info));
return (size_t)info.WorkingSetSize;
#elif defined(__APPLE__) && defined(__MACH__)
/* OSX ------------------------------------------------------ */
struct mach_task_basic_info info;
mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO,
(task_info_t)&info, &infoCount) != KERN_SUCCESS)
return (size_t)0L; /* Can't access? */
return (size_t)info.resident_size;
#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
/* Linux ---------------------------------------------------- */
long rss = 0L;
FILE *fp = NULL;
if ((fp = fopen("/proc/self/statm", "r")) == NULL)
return (size_t) 0L; /* Can't open? */
if (fscanf(fp, "%*s%ld", &rss) != 1) {
fclose(fp);
return (size_t) 0L; /* Can't read? */
}
fclose(fp);
return (size_t) rss * (size_t) sysconf(_SC_PAGESIZE);
#else
/* AIX, BSD, Solaris, and Unknown OS ------------------------ */
return (size_t)0L; /* Unsupported. */
#endif
}
static void
get_gt(unsigned int *massQA, unsigned char *massQ, unsigned char *mass, size_t vecsize, size_t qsize, L2SpaceI &l2space,
size_t vecdim, vector<std::priority_queue<std::pair<int, labeltype >>> &answers, size_t k) {
(vector<std::priority_queue<std::pair<int, labeltype >>>(qsize)).swap(answers);
DISTFUNC<int> fstdistfunc_ = l2space.get_dist_func();
cout << qsize << "\n";
for (int i = 0; i < qsize; i++) {
for (int j = 0; j < k; j++) {
answers[i].emplace(0.0f, massQA[1000 * i + j]);
}
}
}
static float
test_approx(unsigned char *massQ, size_t vecsize, size_t qsize, HierarchicalNSW<int> &appr_alg, size_t vecdim,
vector<std::priority_queue<std::pair<int, labeltype >>> &answers, size_t k) {
size_t correct = 0;
size_t total = 0;
//uncomment to test in parallel mode:
//#pragma omp parallel for
for (int i = 0; i < qsize; i++) {
std::priority_queue<std::pair<int, labeltype >> result = appr_alg.searchKnn(massQ + vecdim * i, k);
std::priority_queue<std::pair<int, labeltype >> gt(answers[i]);
unordered_set<labeltype> g;
total += gt.size();
while (gt.size()) {
g.insert(gt.top().second);
gt.pop();
}
while (result.size()) {
if (g.find(result.top().second) != g.end()) {
correct++;
} else {
}
result.pop();
}
}
return 1.0f * correct / total;
}
static void
test_vs_recall(unsigned char *massQ, size_t vecsize, size_t qsize, HierarchicalNSW<int> &appr_alg, size_t vecdim,
vector<std::priority_queue<std::pair<int, labeltype >>> &answers, size_t k) {
vector<size_t> efs;// = { 10,10,10,10,10 };
for (int i = k; i < 30; i++) {
efs.push_back(i);
}
for (int i = 30; i < 100; i += 10) {
efs.push_back(i);
}
for (int i = 100; i < 500; i += 40) {
efs.push_back(i);
}
for (size_t ef : efs) {
appr_alg.setEf(ef);
StopW stopw = StopW();
float recall = test_approx(massQ, vecsize, qsize, appr_alg, vecdim, answers, k);
float time_us_per_query = stopw.getElapsedTimeMicro() / qsize;
cout << ef << "\t" << recall << "\t" << time_us_per_query << " us\n";
if (recall > 1.0) {
cout << recall << "\t" << time_us_per_query << " us\n";
break;
}
}
}
inline bool exists_test(const std::string &name) {
ifstream f(name.c_str());
return f.good();
}
void sift_test1B() {
int subset_size_milllions = 200;
int efConstruction = 40;
int M = 16;
size_t vecsize = subset_size_milllions * 1000000;
size_t qsize = 10000;
size_t vecdim = 128;
char path_index[1024];
char path_gt[1024];
char *path_q = "bigann/bigann_query.bvecs";
char *path_data = "bigann/bigann_base.bvecs";
sprintf(path_index, "sift1b_%dm_ef_%d_M_%d.bin", subset_size_milllions, efConstruction, M);
sprintf(path_gt, "bigann/gnd/idx_%dM.ivecs", subset_size_milllions);
cout << "path_gt :"<<path_gt << endl;
cout << "path_index :"<<path_index << endl;
unsigned char *massb = new unsigned char[vecdim];
cout << "Loading GT:\n";
ifstream inputGT(path_gt, ios::binary);
unsigned int *massQA = new unsigned int[qsize * 1000];
for (int i = 0; i < qsize; i++) {
int t;
inputGT.read((char *) &t, 4);
inputGT.read((char *) (massQA + 1000 * i), t * 4);
if (t != 1000) {
cout << "err";
return;
}
}
cout << "Loading queries:\n";
unsigned char *massQ = new unsigned char[qsize * vecdim];
ifstream inputQ(path_q, ios::binary);
for (int i = 0; i < qsize; i++) {
int in = 0;
inputQ.read((char *) &in, 4);
if (in != 128) {
cout << "file error";
exit(1);
}
inputQ.read((char *) massb, in);
for (int j = 0; j < vecdim; j++) {
massQ[i * vecdim + j] = massb[j];
// cout<<massb[j]<<", ";
}
}
inputQ.close();
unsigned char *mass = new unsigned char[vecdim];
ifstream input(path_data, ios::binary);
int in = 0;
L2SpaceI l2space(vecdim);
HierarchicalNSW<int> *appr_alg;
if (exists_test(path_index)) {
cout << "Loading index from " << path_index << ":\n";
appr_alg = new HierarchicalNSW<int>(&l2space, path_index, false);
cout << "Actual memory usage: " << getCurrentRSS() / 1000000 << " Mb \n";
} else {
cout << "Building index:\n";
appr_alg = new HierarchicalNSW<int>(&l2space, vecsize, M, efConstruction);
input.read((char *) &in, 4);
if (in != 128) {
cout << "file error";
exit(1);
}
input.read((char *) massb, in);
for (int j = 0; j < vecdim; j++) {
mass[j] = massb[j] * (1.0f);
}
appr_alg->addPoint((void *) (massb), (size_t) 0);
int j1 = 0;
StopW stopw = StopW();
StopW stopw_full = StopW();
size_t report_every = 100000;
#pragma omp parallel for
for (int i = 1; i < vecsize; i++) {
unsigned char mass[128];
#pragma omp critical
{
input.read((char *) &in, 4);
if (in != 128) {
cout << "file error";
exit(1);
}
input.read((char *) massb, in);
for (int j = 0; j < vecdim; j++) {
mass[j] = massb[j];
}
j1++;
if (j1 % report_every == 0) {
cout << j1 / (0.01 * vecsize) << " %, "
<< report_every / (1000.0 * 1e-6 * stopw.getElapsedTimeMicro()) << " kips " << " Mem: "
<< getCurrentRSS() / 1000000 << " Mb \n";
stopw.reset();
}
}
appr_alg->addPoint((void *) (mass), (size_t) j1);
}
input.close();
cout << "Build time:" << 1e-6 * stopw_full.getElapsedTimeMicro() << " seconds\n";
appr_alg->saveIndex(path_index);
}
vector<std::priority_queue<std::pair<int, labeltype >>> answers;
size_t k = 1;
cout << "Parsing gt:\n";
get_gt(massQA, massQ, mass, vecsize, qsize, l2space, vecdim, answers, k);
cout << "Loaded gt\n";
for (int i = 0; i < 1; i++)
test_vs_recall(massQ, vecsize, qsize, *appr_alg, vecdim, answers, k);
cout << "Actual memory usage: " << getCurrentRSS() / 1000000 << " Mb \n";
return;
}
| 30.479452 | 144 | 0.553978 | [
"vector"
] |
33c1a6f48520de78e951f32d2bd18f3efbc2d702 | 93,091 | cpp | C++ | hphp/runtime/ext/ext_soap.cpp | renesugar/hiphop-php | 4eb05b745fd3018a6d9e51464cae06a4465ee142 | [
"PHP-3.01",
"Zend-2.0"
] | 2 | 2019-04-11T01:39:44.000Z | 2019-11-21T16:06:13.000Z | hphp/runtime/ext/ext_soap.cpp | rmasters/hiphop-php | 218e4718a7b68bf49b9a98caad9bd5f1cb2abe31 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/ext/ext_soap.cpp | rmasters/hiphop-php | 218e4718a7b68bf49b9a98caad9bd5f1cb2abe31 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2019-04-11T01:39:45.000Z | 2019-04-11T01:39:45.000Z | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/ext/ext_soap.h"
#include "hphp/runtime/base/http-client.h"
#include "hphp/runtime/server/http-protocol.h"
#include "hphp/runtime/base/class-info.h"
#include "hphp/runtime/ext/soap/soap.h"
#include "hphp/runtime/ext/soap/packet.h"
#include "hphp/runtime/base/string-util.h"
#include "hphp/runtime/ext/ext_zlib.h"
#include "hphp/runtime/ext/ext_network.h"
#include "hphp/runtime/ext/ext_array.h"
#include "hphp/runtime/ext/ext_function.h"
#include "hphp/runtime/ext/ext_class.h"
#include "hphp/runtime/ext/ext_output.h"
#include "hphp/runtime/ext/ext_stream.h"
#include "hphp/runtime/ext/ext_string.h"
#include "hphp/system/systemlib.h"
namespace HPHP {
const StaticString s___dorequest("__dorequest");
IMPLEMENT_DEFAULT_EXTENSION(soap);
///////////////////////////////////////////////////////////////////////////////
// helper classes for setting/resetting globals within a method call
class SoapScope {
public:
SoapScope() {
USE_SOAP_GLOBAL;
m_old_handler = SOAP_GLOBAL(use_soap_error_handler);
m_old_error_code = SOAP_GLOBAL(error_code);
m_old_error_object = SOAP_GLOBAL(error_object);
m_old_soap_version = SOAP_GLOBAL(soap_version);
SOAP_GLOBAL(use_soap_error_handler) = true;
}
~SoapScope() {
USE_SOAP_GLOBAL;
SOAP_GLOBAL(use_soap_error_handler) = m_old_handler;
SOAP_GLOBAL(error_code) = m_old_error_code;
SOAP_GLOBAL(error_object) = m_old_error_object;
SOAP_GLOBAL(soap_version) = m_old_soap_version;
}
private:
bool m_old_handler;
const char *m_old_error_code;
Object m_old_error_object;
int m_old_soap_version;
};
class SoapServerScope : public SoapScope {
public:
explicit SoapServerScope(c_SoapServer *server) {
USE_SOAP_GLOBAL;
SOAP_GLOBAL(error_code) = "Server";
SOAP_GLOBAL(error_object) = Object(server);
}
};
class SoapClientScope : public SoapScope {
public:
explicit SoapClientScope(c_SoapClient *client) {
USE_SOAP_GLOBAL;
SOAP_GLOBAL(error_code) = "Client";
SOAP_GLOBAL(error_object) = Object(client);
}
};
class SoapServiceScope {
public:
explicit SoapServiceScope(c_SoapServer *server) {
save();
USE_SOAP_GLOBAL;
SOAP_GLOBAL(soap_version) = server->m_version;
SOAP_GLOBAL(sdl) = server->m_sdl;
SOAP_GLOBAL(encoding) = server->m_encoding;
SOAP_GLOBAL(classmap) = server->m_classmap;
SOAP_GLOBAL(typemap) = server->m_typemap;
SOAP_GLOBAL(features) = server->m_features;
}
explicit SoapServiceScope(c_SoapClient *client) {
save();
USE_SOAP_GLOBAL;
SOAP_GLOBAL(soap_version) = client->m_soap_version;
SOAP_GLOBAL(sdl) = client->m_sdl;
SOAP_GLOBAL(encoding) = client->m_encoding;
SOAP_GLOBAL(classmap) = client->m_classmap;
SOAP_GLOBAL(typemap) = client->m_typemap;
SOAP_GLOBAL(features) = client->m_features;
}
~SoapServiceScope() {
USE_SOAP_GLOBAL;
SOAP_GLOBAL(soap_version) = m_old_soap_version;
SOAP_GLOBAL(encoding) = m_old_encoding;
SOAP_GLOBAL(sdl) = m_old_sdl;
SOAP_GLOBAL(classmap) = m_old_classmap;
SOAP_GLOBAL(typemap) = m_old_typemap;
SOAP_GLOBAL(features) = m_old_features;
}
private:
sdl *m_old_sdl;
xmlCharEncodingHandlerPtr m_old_encoding;
Array m_old_classmap;
encodeMap *m_old_typemap;
int64_t m_old_features;
int m_old_soap_version;
void save() {
USE_SOAP_GLOBAL;
m_old_soap_version = SOAP_GLOBAL(soap_version);
m_old_sdl = SOAP_GLOBAL(sdl);
m_old_encoding = SOAP_GLOBAL(encoding);
m_old_classmap = SOAP_GLOBAL(classmap);
m_old_typemap = SOAP_GLOBAL(typemap);
m_old_features = SOAP_GLOBAL(features);
}
};
///////////////////////////////////////////////////////////////////////////////
// forward declarations
static void throw_soap_server_fault(litstr code, litstr fault);
static void model_to_string(sdlContentModelPtr model, StringBuffer &buf,
int level);
///////////////////////////////////////////////////////////////////////////////
// client helpers
static Object create_soap_fault(CStrRef code, CStrRef fault) {
return Object(SystemLib::AllocSoapFaultObject(code, fault));
}
static Object create_soap_fault(Exception &e) {
USE_SOAP_GLOBAL;
return create_soap_fault(SOAP_GLOBAL(error_code), String(e.getMessage()));
}
static sdlParamPtr get_param(sdlFunction *function, const char *param_name,
int index, bool response) {
sdlParamVec *ht;
if (!function) {
return sdlParamPtr();
}
if (!response) {
ht = &function->requestParameters;
} else {
ht = &function->responseParameters;
}
if (ht->empty()) {
return sdlParamPtr();
}
if (param_name) {
for (unsigned int i = 0; i < ht->size(); i++) {
sdlParamPtr p = (*ht)[i];
if (p->paramName == param_name) return p;
}
} else {
if (index >= 0 && index < (int)ht->size()) {
return (*ht)[index];
}
}
return sdlParamPtr();
}
static xmlNodePtr serialize_zval(CVarRef val, sdlParamPtr param,
const char *paramName, int style,
xmlNodePtr parent) {
xmlNodePtr xmlParam;
encodePtr enc;
Variant v = val;
if (param != NULL) {
enc = param->encode;
if (val.isNull()) {
if (param->element) {
if (!param->element->fixed.empty()) {
v = String(param->element->fixed);
} else if (!param->element->def.empty() && !param->element->nillable) {
v = String(param->element->def);
}
}
}
} else {
enc = encodePtr();
}
xmlParam = master_to_xml(enc, val, style, parent);
if (!strcmp((char*)xmlParam->name, "BOGUS")) {
xmlNodeSetName(xmlParam, BAD_CAST(paramName));
}
return xmlParam;
}
static xmlNodePtr serialize_parameter(sdlParamPtr param, Variant value,
int index, const char *name, int style,
xmlNodePtr parent) {
if (!value.isNull() && value.isObject()) {
c_SoapParam *p = value.toObject().getTyped<c_SoapParam>(true, true);
if (p) {
value = p->m_data;
name = p->m_name.c_str();
}
}
if (param && !param->paramName.empty()) {
name = param->paramName.c_str();
} else {
if (name == NULL) {
char paramNameBuf[10];
snprintf(paramNameBuf, sizeof(paramNameBuf), "param%d", index);
name = paramNameBuf;
}
}
return serialize_zval(value, param, name, style, parent);
}
static xmlDocPtr serialize_function_call
(c_SoapClient *client, sdlFunctionPtr function, const char *function_name,
const char *uri, CArrRef arguments, CArrRef soap_headers) {
xmlNodePtr envelope = NULL, body, method = NULL, head = NULL;
xmlNsPtr ns = NULL;
int style, use;
sdlSoapBindingFunctionHeaderMap *hdrs = NULL;
encode_reset_ns();
xmlDoc *doc = xmlNewDoc(BAD_CAST("1.0"));
doc->encoding = xmlCharStrdup("UTF-8");
doc->charset = XML_CHAR_ENCODING_UTF8;
if (client->m_soap_version == SOAP_1_1) {
envelope = xmlNewDocNode(doc, NULL, BAD_CAST("Envelope"), NULL);
ns = xmlNewNs(envelope, BAD_CAST(SOAP_1_1_ENV_NAMESPACE),
BAD_CAST(SOAP_1_1_ENV_NS_PREFIX));
xmlSetNs(envelope, ns);
} else if (client->m_soap_version == SOAP_1_2) {
envelope = xmlNewDocNode(doc, NULL, BAD_CAST("Envelope"), NULL);
ns = xmlNewNs(envelope, BAD_CAST(SOAP_1_2_ENV_NAMESPACE),
BAD_CAST(SOAP_1_2_ENV_NS_PREFIX));
xmlSetNs(envelope, ns);
} else {
throw SoapException("Unknown SOAP version");
}
xmlDocSetRootElement(doc, envelope);
if (!soap_headers.empty()) {
head = xmlNewChild(envelope, ns, BAD_CAST("Header"), NULL);
}
body = xmlNewChild(envelope, ns, BAD_CAST("Body"), NULL);
if (function && function->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = function->bindingAttributes;
hdrs = &fnb->input.headers;
style = fnb->style;
/*FIXME: how to pass method name if style is SOAP_DOCUMENT */
/*style = SOAP_RPC;*/
use = fnb->input.use;
if (style == SOAP_RPC) {
ns = encode_add_ns(body, fnb->input.ns.c_str());
if (!function->requestName.empty()) {
method = xmlNewChild(body, ns,
BAD_CAST(function->requestName.c_str()), NULL);
} else {
method = xmlNewChild(body, ns,
BAD_CAST(function->functionName.c_str()), NULL);
}
}
} else {
use = client->m_use;
style = client->m_style;
/*FIXME: how to pass method name if style is SOAP_DOCUMENT */
/*style = SOAP_RPC;*/
if (style == SOAP_RPC) {
ns = encode_add_ns(body, uri);
if (function_name) {
method = xmlNewChild(body, ns, BAD_CAST(function_name), NULL);
} else if (function && !function->requestName.empty()) {
method = xmlNewChild(body, ns,
BAD_CAST(function->requestName.c_str()), NULL);
} else if (function && !function->functionName.empty()) {
method = xmlNewChild(body, ns,
BAD_CAST(function->functionName.c_str()), NULL);
} else {
method = body;
}
} else {
method = body;
}
}
int i = 0;
for (ArrayIter iter(arguments); iter; ++iter, ++i) {
xmlNodePtr param;
sdlParamPtr parameter;
if (function) {
parameter = get_param(function.get(), NULL, i, false);
}
if (style == SOAP_RPC) {
if (parameter) {
param = serialize_parameter(parameter, iter.second(), i, NULL,
use, method);
}
} else if (style == SOAP_DOCUMENT) {
param = serialize_parameter(parameter, iter.second(), i, NULL,
use, body);
if (function && function->binding->bindingType == BINDING_SOAP) {
if (parameter && parameter->element) {
ns = encode_add_ns(param, parameter->element->namens.c_str());
xmlNodeSetName(param, BAD_CAST(parameter->element->name.c_str()));
xmlSetNs(param, ns);
}
}
}
}
if (function && !function->requestParameters.empty()) {
int n = function->requestParameters.size();
if (n > arguments.size()) {
for (i = arguments.size(); i < n; i++) {
xmlNodePtr param;
sdlParamPtr parameter = get_param(function.get(), NULL, i, false);
if (style == SOAP_RPC) {
param = serialize_parameter(parameter, uninit_null(), i, NULL, use, method);
} else if (style == SOAP_DOCUMENT) {
param = serialize_parameter(parameter, uninit_null(), i, NULL, use, body);
if (function && function->binding->bindingType == BINDING_SOAP) {
if (parameter && parameter->element) {
ns = encode_add_ns(param, parameter->element->namens.c_str());
xmlNodeSetName(param,
BAD_CAST(parameter->element->name.c_str()));
xmlSetNs(param, ns);
}
}
}
}
}
}
if (head) {
for (ArrayIter iter(soap_headers); iter; ++iter) {
c_SoapHeader *header = iter.second().toObject().getTyped<c_SoapHeader>();
xmlNodePtr h;
xmlNsPtr nsptr;
int hdr_use = SOAP_LITERAL;
encodePtr enc;
if (hdrs) {
string key = header->m_namespace.data();
key += ':';
key += header->m_name.data();
sdlSoapBindingFunctionHeaderMap::iterator iter = hdrs->find(key);
if (iter != hdrs->end()) {
sdlSoapBindingFunctionHeaderPtr hdr = iter->second;
hdr_use = hdr->use;
enc = hdr->encode;
if (hdr_use == SOAP_ENCODED) {
use = SOAP_ENCODED;
}
}
}
if (!header->m_data.isNull()) {
h = master_to_xml(enc, header->m_data, hdr_use, head);
xmlNodeSetName(h, BAD_CAST(header->m_name.data()));
} else {
h = xmlNewNode(NULL, BAD_CAST(header->m_name.data()));
xmlAddChild(head, h);
}
nsptr = encode_add_ns(h, header->m_namespace.data());
xmlSetNs(h, nsptr);
if (header->m_mustUnderstand) {
if (client->m_soap_version == SOAP_1_1) {
xmlSetProp(h, BAD_CAST(SOAP_1_1_ENV_NS_PREFIX":mustUnderstand"),
BAD_CAST("1"));
} else {
xmlSetProp(h, BAD_CAST(SOAP_1_2_ENV_NS_PREFIX":mustUnderstand"),
BAD_CAST("true"));
}
}
if (!header->m_actor.isNull()) {
if (header->m_actor.isString()) {
if (client->m_soap_version == SOAP_1_1) {
xmlSetProp(h, BAD_CAST(SOAP_1_1_ENV_NS_PREFIX":actor"),
BAD_CAST(header->m_actor.toString().data()));
} else {
xmlSetProp(h, BAD_CAST(SOAP_1_2_ENV_NS_PREFIX":role"),
BAD_CAST(header->m_actor.toString().data()));
}
} else if (header->m_actor.isInteger()) {
int64_t actor = header->m_actor.toInt64();
if (client->m_soap_version == SOAP_1_1) {
if (actor == SOAP_ACTOR_NEXT) {
xmlSetProp(h, BAD_CAST(SOAP_1_1_ENV_NS_PREFIX":actor"),
BAD_CAST(SOAP_1_1_ACTOR_NEXT));
}
} else {
if (actor == SOAP_ACTOR_NEXT) {
xmlSetProp(h, BAD_CAST(SOAP_1_2_ENV_NS_PREFIX":role"),
BAD_CAST(SOAP_1_2_ACTOR_NEXT));
} else if (actor == SOAP_ACTOR_NONE) {
xmlSetProp(h, BAD_CAST(SOAP_1_2_ENV_NS_PREFIX":role"),
BAD_CAST(SOAP_1_2_ACTOR_NONE));
} else if (actor == SOAP_ACTOR_UNLIMATERECEIVER) {
xmlSetProp(h, BAD_CAST(SOAP_1_2_ENV_NS_PREFIX":role"),
BAD_CAST(SOAP_1_2_ACTOR_UNLIMATERECEIVER));
}
}
}
}
}
}
if (use == SOAP_ENCODED) {
xmlNewNs(envelope, BAD_CAST(XSD_NAMESPACE), BAD_CAST(XSD_NS_PREFIX));
if (client->m_soap_version == SOAP_1_1) {
xmlNewNs(envelope, BAD_CAST(SOAP_1_1_ENC_NAMESPACE),
BAD_CAST(SOAP_1_1_ENC_NS_PREFIX));
xmlSetNsProp(envelope, envelope->ns, BAD_CAST("encodingStyle"),
BAD_CAST(SOAP_1_1_ENC_NAMESPACE));
} else if (client->m_soap_version == SOAP_1_2) {
xmlNewNs(envelope, BAD_CAST(SOAP_1_2_ENC_NAMESPACE),
BAD_CAST(SOAP_1_2_ENC_NS_PREFIX));
if (method) {
xmlSetNsProp(method, envelope->ns, BAD_CAST("encodingStyle"),
BAD_CAST(SOAP_1_2_ENC_NAMESPACE));
}
}
}
encode_finish();
return doc;
}
static bool do_request(c_SoapClient *client, xmlDoc *request,
const char *location, const char *action, int version,
bool one_way, Variant &response) {
char *buf; int buf_size;
xmlDocDumpMemory(request, (xmlChar**)&buf, &buf_size);
if (!buf) {
client->m_soap_fault =
create_soap_fault("HTTP", "Error build soap request");
return false;
}
if (client->m_trace) {
client->m_last_request = String((char*)buf, buf_size, CopyString);
}
response = client->o_invoke_few_args(s___dorequest, 5,
String(buf, buf_size, CopyString),
String(location, CopyString),
String(action, CopyString),
version, one_way);
if (!response.isString()) {
if (client->m_soap_fault.isNull()) {
client->m_soap_fault =
create_soap_fault("Client", "SoapClient::__doRequest() "
"returned non string value");
}
} else if (client->m_trace) {
client->m_last_response = response;
}
xmlFree(buf);
return client->m_soap_fault.isNull();
}
static void verify_soap_headers_array(Array &headers) {
for (ArrayIter iter(headers); iter; ++iter) {
Variant tmp = iter.second();
if (!tmp.isObject() || !tmp.toObject().is<c_SoapHeader>()) {
throw SoapException("Invalid SOAP header");
}
}
}
///////////////////////////////////////////////////////////////////////////////
// shared helpers
const StaticString
s_type_name("type_name"),
s_type_ns("type_ns"),
s_to_xml("to_xml"),
s_from_xml("from_xml");
static encodeMapPtr soap_create_typemap_impl(sdl *sdl, Array &ht) {
encodeMapPtr typemap(new encodeMap());
for (ArrayIter iter(ht); iter; ++iter) {
Variant tmp = iter.second();
if (!tmp.isArray()) {
raise_warning("Wrong 'typemap' option");
return typemap;
}
Array ht2 = tmp.toArray();
String type_name, type_ns;
Variant to_xml, to_zval;
for (ArrayIter it(ht2); it; ++it) {
tmp = it.second();
if (it.first().isString()) {
String name = it.first().toString();
if (name == s_type_name) {
if (tmp.isString()) type_name = tmp.toString();
} else if (name == s_type_ns) {
if (tmp.isString()) type_ns = tmp.toString();
} else if (name == s_to_xml) {
to_xml = tmp;
} else if (name == s_from_xml) {
to_zval = tmp;
}
}
}
encodePtr enc, new_enc;
if (!type_name.empty()) {
if (!type_ns.empty()) {
enc = get_encoder(sdl, type_ns.data(), type_name.data());
} else {
enc = get_encoder_ex(sdl, type_name.data());
}
new_enc = encodePtr(new encode());
if (enc) {
new_enc->details.type = enc->details.type;
new_enc->details.ns = enc->details.ns;
new_enc->details.type_str = enc->details.type_str;
new_enc->details.sdl_type = enc->details.sdl_type;
} else {
enc = get_conversion(UNKNOWN_TYPE);
new_enc->details.type = enc->details.type;
if (!type_ns.empty()) {
new_enc->details.ns = type_ns.data();
}
new_enc->details.type_str = type_name.data();
}
new_enc->to_xml = enc->to_xml;
new_enc->to_zval = enc->to_zval;
new_enc->details.map = soapMappingPtr(new soapMapping());
if (to_xml.toBoolean()) {
new_enc->details.map->to_xml = to_xml;
new_enc->to_xml = to_xml_user;
} else if (enc->details.map && !enc->details.map->to_xml.isNull()) {
new_enc->details.map->to_xml = enc->details.map->to_xml;
}
if (to_zval.toBoolean()) {
new_enc->details.map->to_zval = to_zval;
new_enc->to_zval = to_zval_user;
} else if (enc->details.map && !enc->details.map->to_zval.isNull()) {
new_enc->details.map->to_zval = enc->details.map->to_zval;
}
string nscat;
if (!type_ns.empty()) {
nscat += type_ns.data();
nscat += ':';
}
nscat += type_name.data();
(*typemap)[nscat] = new_enc;
}
}
return typemap;
}
static encodeMap *soap_create_typemap(sdl *sdl, Array &ht) {
return s_soap_data->register_typemap(soap_create_typemap_impl(sdl, ht));
}
static void output_xml_header(int soap_version) {
if (soap_version == SOAP_1_2) {
f_header("Content-Type: application/soap+xml; charset=utf-8");
} else {
f_header("Content-Type: text/xml; charset=utf-8");
}
}
///////////////////////////////////////////////////////////////////////////////
// server helpers
static void deserialize_parameters(xmlNodePtr params, sdlFunction *function,
Array ¶meters) {
int num_of_params = 0;
int cur_param = 0;
if (function) {
bool use_names = false;
num_of_params = function->requestParameters.size();
if (num_of_params == 0) return;
for (int i = 0; i < num_of_params; i++) {
sdlParamPtr param = function->requestParameters[i];
if (get_node(params, (char*)param->paramName.c_str())) {
use_names = true;
break;
}
}
if (use_names) {
for (int i = 0; i < num_of_params; i++, cur_param++) {
sdlParamPtr param = function->requestParameters[i];
xmlNodePtr val = get_node(params, (char*)param->paramName.c_str());
if (val) {
parameters.append(master_to_zval(param->encode, val));
}
}
return;
}
}
if (params) {
int num_of_params = 0;
xmlNodePtr trav = params;
while (trav != NULL) {
if (trav->type == XML_ELEMENT_NODE) {
num_of_params++;
}
trav = trav->next;
}
if (num_of_params == 1 && function && function->binding &&
function->binding->bindingType == BINDING_SOAP &&
function->bindingAttributes->style == SOAP_DOCUMENT &&
function->requestParameters.empty() &&
strcmp((char*)params->name, function->functionName.c_str()) == 0) {
num_of_params = 0;
} else if (num_of_params > 0) {
trav = params;
while (trav != 0 && cur_param < num_of_params) {
if (trav->type == XML_ELEMENT_NODE) {
encodePtr enc;
sdlParamPtr param;
if (function) {
if (cur_param >= (int)function->requestParameters.size()) {
throw_soap_server_fault("Client","Error cannot find parameter");
}
param = function->requestParameters[cur_param];
}
if (param == NULL) {
enc.reset();
} else {
enc = param->encode;
}
parameters.set(cur_param, master_to_zval(enc, trav));
cur_param++;
}
trav = trav->next;
}
}
}
if (num_of_params > cur_param) {
throw_soap_server_fault("Client","Missing parameter");
}
}
static sdlFunctionPtr get_doc_function(sdl *sdl, xmlNodePtr params) {
if (sdl) {
for (sdlFunctionMap::iterator iter = sdl->functions.begin();
iter != sdl->functions.end(); ++iter) {
sdlFunctionPtr tmp = iter->second;
if (tmp->binding && tmp->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = tmp->bindingAttributes;
if (fnb->style == SOAP_DOCUMENT) {
if (params == NULL) {
if (tmp->requestParameters.empty()) {
return tmp;
}
} else if (!tmp->requestParameters.empty()) {
bool ok = true;
xmlNodePtr node = params;
for (unsigned int i = 0; i < tmp->requestParameters.size(); i++) {
sdlParamPtr param = tmp->requestParameters[i];
if (param->element) {
if (param->element->name != (char*)node->name) {
ok = false;
break;
}
if (!param->element->namens.empty() && node->ns) {
if (param->element->namens != (char*)node->ns->href) {
ok = false;
break;
}
} else if ((param->element->namens.empty() && node->ns) ||
(!param->element->namens.empty() &&
node->ns == NULL)) {
ok = false;
break;
}
} else if (param->paramName != (char*)node->name) {
ok = false;
break;
}
node = node->next;
}
if (ok /*&& node == NULL*/) {
return tmp;
}
}
}
}
}
}
return sdlFunctionPtr();
}
static sdlFunctionPtr get_function(sdl *sdl, const char *function_name) {
if (sdl) {
String lowered = f_strtolower(function_name);
sdlFunctionMap::iterator iter = sdl->functions.find(lowered.data());
if (iter == sdl->functions.end()) {
iter = sdl->requests.find(lowered.data());
if (iter == sdl->requests.end()) {
return sdlFunctionPtr();
}
}
return iter->second;
}
return sdlFunctionPtr();
}
static sdlFunctionPtr find_function(sdl *sdl, xmlNodePtr func,
String &function_name) {
sdlFunctionPtr function = get_function(sdl, (char*)func->name);
if (function && function->binding &&
function->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = function->bindingAttributes;
if (fnb->style == SOAP_DOCUMENT) {
if (func->children != NULL || !function->requestParameters.empty()) {
function.reset();
}
}
}
if (sdl != NULL && function == NULL) {
function = get_doc_function(sdl, func);
}
if (function != NULL) {
function_name = String(function->functionName);
} else {
function_name = String((char *)func->name, CopyString);
}
return function;
}
static sdlFunctionPtr deserialize_function_call
(sdl *sdl, xmlDocPtr request, const char* actor, String &function_name,
Array ¶meters, int &version, Array &headers) {
USE_SOAP_GLOBAL;
char* envelope_ns = NULL;
xmlNodePtr trav,env,head,body,func;
xmlAttrPtr attr;
sdlFunctionPtr function;
encode_reset_ns();
/* Get <Envelope> element */
env = NULL;
trav = request->children;
while (trav != NULL) {
if (trav->type == XML_ELEMENT_NODE) {
if (env == NULL &&
node_is_equal_ex(trav,"Envelope",SOAP_1_1_ENV_NAMESPACE)) {
env = trav;
version = SOAP_1_1;
envelope_ns = SOAP_1_1_ENV_NAMESPACE;
SOAP_GLOBAL(soap_version) = SOAP_1_1;
} else if (env == NULL &&
node_is_equal_ex(trav,"Envelope",SOAP_1_2_ENV_NAMESPACE)) {
env = trav;
version = SOAP_1_2;
envelope_ns = SOAP_1_2_ENV_NAMESPACE;
SOAP_GLOBAL(soap_version) = SOAP_1_2;
} else {
throw_soap_server_fault("VersionMismatch", "Wrong Version");
}
}
trav = trav->next;
}
if (env == NULL) {
throw_soap_server_fault
("Client", "looks like we got XML without \"Envelope\" element");
}
attr = env->properties;
while (attr != NULL) {
if (attr->ns == NULL) {
throw_soap_server_fault("Client", "A SOAP Envelope element cannot have "
"non Namespace qualified attributes");
} else if (attr_is_equal_ex(attr,"encodingStyle",SOAP_1_2_ENV_NAMESPACE)) {
if (version == SOAP_1_2) {
throw_soap_server_fault("Client", "encodingStyle cannot be specified "
"on the Envelope");
} else if (strcmp((char*)attr->children->content,
SOAP_1_1_ENC_NAMESPACE) != 0) {
throw_soap_server_fault("Client", "Unknown data encoding style");
}
}
attr = attr->next;
}
/* Get <Header> element */
head = NULL;
trav = env->children;
while (trav != NULL && trav->type != XML_ELEMENT_NODE) {
trav = trav->next;
}
if (trav != NULL && node_is_equal_ex(trav,"Header",envelope_ns)) {
head = trav;
trav = trav->next;
}
/* Get <Body> element */
body = NULL;
while (trav != NULL && trav->type != XML_ELEMENT_NODE) {
trav = trav->next;
}
if (trav != NULL && node_is_equal_ex(trav,"Body",envelope_ns)) {
body = trav;
trav = trav->next;
}
while (trav != NULL && trav->type != XML_ELEMENT_NODE) {
trav = trav->next;
}
if (body == NULL) {
throw_soap_server_fault("Client", "Body must be present in a "
"SOAP envelope");
}
attr = body->properties;
while (attr != NULL) {
if (attr->ns == NULL) {
if (version == SOAP_1_2) {
throw_soap_server_fault("Client", "A SOAP Body element cannot have non"
" Namespace qualified attributes");
}
} else if (attr_is_equal_ex(attr,"encodingStyle",SOAP_1_2_ENV_NAMESPACE)) {
if (version == SOAP_1_2) {
throw_soap_server_fault("Client", "encodingStyle cannot be specified "
"on the Body");
} else if (strcmp((char*)attr->children->content,
SOAP_1_1_ENC_NAMESPACE) != 0) {
throw_soap_server_fault("Client", "Unknown data encoding style");
}
}
attr = attr->next;
}
if (trav != NULL && version == SOAP_1_2) {
throw_soap_server_fault("Client", "A SOAP 1.2 envelope can contain only "
"Header and Body");
}
func = NULL;
trav = body->children;
while (trav != NULL) {
if (trav->type == XML_ELEMENT_NODE) {
/*
if (func != NULL) {
throw_soap_server_fault("Client", "looks like we got \"Body\" with "
"several functions call", NULL, NULL, NULL);
}
*/
func = trav;
break; /* FIXME: the rest of body is ignored */
}
trav = trav->next;
}
if (func == NULL) {
function = get_doc_function(sdl, NULL);
if (function != NULL) {
function_name = String(function->functionName);
} else {
throw_soap_server_fault
("Client", "looks like we got \"Body\" without function call");
}
} else {
if (version == SOAP_1_1) {
attr = get_attribute_ex(func->properties,"encodingStyle",
SOAP_1_1_ENV_NAMESPACE);
if (attr && strcmp((char*)attr->children->content,
SOAP_1_1_ENC_NAMESPACE) != 0) {
throw_soap_server_fault("Client","Unknown Data Encoding Style");
}
} else {
attr = get_attribute_ex(func->properties,"encodingStyle",
SOAP_1_2_ENV_NAMESPACE);
if (attr && strcmp((char*)attr->children->content,
SOAP_1_2_ENC_NAMESPACE) != 0) {
throw_soap_server_fault
("DataEncodingUnknown","Unknown Data Encoding Style");
}
}
function = find_function(sdl, func, function_name);
if (sdl != NULL && function == NULL) {
if (version == SOAP_1_2) {
throw_soap_server_fault
("rpc:ProcedureNotPresent","Procedure not present");
} else {
throw SoapException("Procedure '%s' not present", func->name);
}
}
}
headers = Array::Create();
if (head) {
soapHeader *h = NULL;
attr = head->properties;
while (attr != NULL) {
if (attr->ns == NULL) {
throw_soap_server_fault("Client", "A SOAP Header element cannot have "
"non Namespace qualified attributes");
} else if (attr_is_equal_ex(attr,"encodingStyle",
SOAP_1_2_ENV_NAMESPACE)) {
if (version == SOAP_1_2) {
throw_soap_server_fault("Client", "encodingStyle cannot be specified"
" on the Header");
} else if (strcmp((char*)attr->children->content,
SOAP_1_1_ENC_NAMESPACE) != 0) {
throw_soap_server_fault("Client", "Unknown data encoding style");
}
}
attr = attr->next;
}
trav = head->children;
while (trav != NULL) {
if (trav->type == XML_ELEMENT_NODE) {
xmlNodePtr hdr_func = trav;
xmlAttrPtr attr;
int mustUnderstand = 0;
if (version == SOAP_1_1) {
attr = get_attribute_ex(hdr_func->properties,"encodingStyle",
SOAP_1_1_ENV_NAMESPACE);
if (attr && strcmp((char*)attr->children->content,
SOAP_1_1_ENC_NAMESPACE) != 0) {
throw_soap_server_fault("Client","Unknown Data Encoding Style");
}
attr = get_attribute_ex(hdr_func->properties,"actor",envelope_ns);
if (attr != NULL) {
if (strcmp((char*)attr->children->content,
SOAP_1_1_ACTOR_NEXT) != 0 &&
(actor == NULL ||
strcmp((char*)attr->children->content,actor) != 0)) {
goto ignore_header;
}
}
} else if (version == SOAP_1_2) {
attr = get_attribute_ex(hdr_func->properties,"encodingStyle",
SOAP_1_2_ENV_NAMESPACE);
if (attr && strcmp((char*)attr->children->content,
SOAP_1_2_ENC_NAMESPACE) != 0) {
throw_soap_server_fault
("DataEncodingUnknown","Unknown Data Encoding Style");
}
attr = get_attribute_ex(hdr_func->properties,"role",envelope_ns);
if (attr != NULL) {
if (strcmp((char*)attr->children->content,
SOAP_1_2_ACTOR_UNLIMATERECEIVER) != 0 &&
strcmp((char*)attr->children->content,
SOAP_1_2_ACTOR_NEXT) != 0 &&
(actor == NULL ||
strcmp((char*)attr->children->content,actor) != 0)) {
goto ignore_header;
}
}
}
attr = get_attribute_ex(hdr_func->properties,"mustUnderstand",
envelope_ns);
if (attr) {
if (strcmp((char*)attr->children->content,"1") == 0 ||
strcmp((char*)attr->children->content,"true") == 0) {
mustUnderstand = 1;
} else if (strcmp((char*)attr->children->content,"0") == 0 ||
strcmp((char*)attr->children->content,"false") == 0) {
mustUnderstand = 0;
} else {
throw_soap_server_fault("Client",
"mustUnderstand value is not boolean");
}
}
h = NEWOBJ(soapHeader)();
Resource hobj(h);
h->function = find_function(sdl, hdr_func, h->function_name).get();
h->mustUnderstand = mustUnderstand;
h->hdr = NULL;
if (!h->function && sdl && function && function->binding &&
function->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = function->bindingAttributes;
if (!fnb->input.headers.empty()) {
string key;
if (hdr_func->ns) {
key += (char*)hdr_func->ns->href;
key += ':';
}
key += (std::string)h->function_name;
sdlSoapBindingFunctionHeaderMap::iterator iter =
fnb->input.headers.find(key);
if (iter != fnb->input.headers.end()) {
h->hdr = iter->second.get();
}
}
}
if (h->hdr) {
h->parameters.append(master_to_zval(h->hdr->encode, hdr_func));
} else {
if (h->function && h->function->binding &&
h->function->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = h->function->bindingAttributes;
if (fnb->style == SOAP_RPC) {
hdr_func = hdr_func->children;
}
}
deserialize_parameters(hdr_func, h->function, h->parameters);
}
headers.append(hobj);
}
ignore_header:
trav = trav->next;
}
}
if (function && function->binding &&
function->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = function->bindingAttributes;
if (fnb->style == SOAP_RPC) {
func = func->children;
}
} else {
func = func->children;
}
deserialize_parameters(func, function.get(), parameters);
encode_finish();
return function;
}
static int serialize_response_call2(xmlNodePtr body, sdlFunction *function,
const char *function_name, const char *uri,
Variant &ret, int version, int main) {
xmlNodePtr method = NULL, param;
sdlParamPtr parameter;
int param_count;
int style, use;
xmlNsPtr ns = NULL;
if (function && function->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = function->bindingAttributes;
style = fnb->style;
use = fnb->output.use;
ns = encode_add_ns(body, fnb->output.ns.c_str());
if (style == SOAP_RPC) {
if (!function->responseName.empty()) {
method = xmlNewChild(body, ns,
BAD_CAST(function->responseName.c_str()), NULL);
} else if (!function->responseParameters.empty()) {
method = xmlNewChild(body, ns,
BAD_CAST(function->functionName.c_str()), NULL);
}
}
} else {
style = main?SOAP_RPC:SOAP_DOCUMENT;
use = main?SOAP_ENCODED:SOAP_LITERAL;
if (style == SOAP_RPC) {
ns = encode_add_ns(body, uri);
method = xmlNewChild(body, ns, BAD_CAST(function_name), NULL);
}
}
if (function) {
param_count = function->responseParameters.size();
} else {
param_count = 1;
}
if (param_count == 1) {
parameter = get_param(function, NULL, 0, true);
if (style == SOAP_RPC) {
xmlNode *rpc_result;
if (main && version == SOAP_1_2) {
xmlNs *rpc_ns = xmlNewNs(body, BAD_CAST(RPC_SOAP12_NAMESPACE),
BAD_CAST(RPC_SOAP12_NS_PREFIX));
rpc_result = xmlNewChild(method, rpc_ns, BAD_CAST("result"), NULL);
param = serialize_parameter(parameter, ret, 0, "return", use, method);
xmlNodeSetContent(rpc_result,param->name);
} else {
param = serialize_parameter(parameter, ret, 0, "return", use, method);
}
} else {
param = serialize_parameter(parameter, ret, 0, "return", use, body);
if (function && function->binding->bindingType == BINDING_SOAP) {
if (parameter && parameter->element) {
ns = encode_add_ns(param, parameter->element->namens.c_str());
xmlNodeSetName(param, BAD_CAST(parameter->element->name.c_str()));
xmlSetNs(param, ns);
}
} else if (strcmp((char*)param->name,"return") == 0) {
ns = encode_add_ns(param, uri);
xmlNodeSetName(param, BAD_CAST(function_name));
xmlSetNs(param, ns);
}
}
} else if (param_count > 1 && ret.isArray()) {
Array arr = ret.toArray();
int i = 0;
for (ArrayIter iter(arr); iter; ++iter, ++i) {
Variant data = iter.second();
Variant key = iter.first();
String param_name;
int64_t param_index = i;
if (key.isString()) {
param_name = key.toString();
} else {
param_index = key.toInt64();
}
parameter = get_param(function, param_name.c_str(), param_index, true);
if (style == SOAP_RPC) {
param = serialize_parameter(parameter, data, i, param_name.data(),
use, method);
} else {
param = serialize_parameter(parameter, data, i, param_name.data(),
use, body);
if (function && function->binding->bindingType == BINDING_SOAP) {
if (parameter && parameter->element) {
ns = encode_add_ns(param, parameter->element->namens.c_str());
xmlNodeSetName(param, BAD_CAST(parameter->element->name.c_str()));
xmlSetNs(param, ns);
}
}
}
}
}
if (use == SOAP_ENCODED && version == SOAP_1_2 && method) {
xmlSetNsProp(method, body->ns, BAD_CAST("encodingStyle"),
BAD_CAST(SOAP_1_2_ENC_NAMESPACE));
}
return use;
}
static xmlDocPtr serialize_response_call(sdlFunctionPtr function,
const char *function_name,
const char *uri, Variant &ret,
CArrRef headers, int version) {
xmlNodePtr envelope = NULL, body, param;
xmlNsPtr ns = NULL;
int use = SOAP_LITERAL;
xmlNodePtr head = NULL;
encode_reset_ns();
xmlDocPtr doc = xmlNewDoc(BAD_CAST("1.0"));
doc->charset = XML_CHAR_ENCODING_UTF8;
doc->encoding = xmlCharStrdup("UTF-8");
if (version == SOAP_1_1) {
envelope = xmlNewDocNode(doc, NULL, BAD_CAST("Envelope"), NULL);
ns = xmlNewNs(envelope, BAD_CAST(SOAP_1_1_ENV_NAMESPACE),
BAD_CAST(SOAP_1_1_ENV_NS_PREFIX));
xmlSetNs(envelope,ns);
} else if (version == SOAP_1_2) {
envelope = xmlNewDocNode(doc, NULL, BAD_CAST("Envelope"), NULL);
ns = xmlNewNs(envelope, BAD_CAST(SOAP_1_2_ENV_NAMESPACE),
BAD_CAST(SOAP_1_2_ENV_NS_PREFIX));
xmlSetNs(envelope,ns);
} else {
throw_soap_server_fault("Server", "Unknown SOAP version");
}
xmlDocSetRootElement(doc, envelope);
if (ret.isObject() &&
ret.toObject()->instanceof(SystemLib::s_SoapFaultClass)) {
ObjectData* obj = ret.getObjectData();
char *detail_name;
sdlFaultPtr fault;
string fault_ns;
if (!headers.empty()) {
xmlNodePtr head;
encodePtr hdr_enc;
int hdr_use = SOAP_LITERAL;
Variant hdr_ret = obj->o_get("headerfault");
soapHeader *h = headers[0].toResource().getTyped<soapHeader>();
const char *hdr_ns = h->hdr ? h->hdr->ns.c_str() : NULL;
const char *hdr_name = h->function_name.data();
head = xmlNewChild(envelope, ns, BAD_CAST("Header"), NULL);
if (hdr_ret.isObject() && hdr_ret.toObject().is<c_SoapHeader>()) {
c_SoapHeader *ht = hdr_ret.toObject().getTyped<c_SoapHeader>();
string key;
if (!ht->m_namespace.empty()) {
key += ht->m_namespace.data();
key += ':';
hdr_ns = ht->m_namespace.data();
}
if (!ht->m_name.empty()) {
key += ht->m_name.data();
hdr_name = ht->m_name.data();
}
if (h->hdr) {
sdlSoapBindingFunctionHeaderMap::iterator iter =
h->hdr->headerfaults.find(key);
if (iter != h->hdr->headerfaults.end()) {
sdlSoapBindingFunctionHeaderPtr hdr = iter->second;
hdr_enc = hdr->encode;
hdr_use = hdr->use;
}
}
hdr_ret = ht->m_data;
obj->o_set("headerfault", hdr_ret);
}
if (h->function) {
if (serialize_response_call2(head, h->function,
h->function_name.data(), uri,
hdr_ret, version, 0) == SOAP_ENCODED) {
obj->o_set("headerfault", hdr_ret);
use = SOAP_ENCODED;
}
} else {
xmlNodePtr xmlHdr = master_to_xml(hdr_enc, hdr_ret, hdr_use, head);
if (hdr_name) {
xmlNodeSetName(xmlHdr, BAD_CAST(hdr_name));
}
if (hdr_ns) {
xmlNsPtr nsptr = encode_add_ns(xmlHdr, hdr_ns);
xmlSetNs(xmlHdr, nsptr);
}
}
}
body = xmlNewChild(envelope, ns, BAD_CAST("Body"), NULL);
param = xmlNewChild(body, ns, BAD_CAST("Fault"), NULL);
fault_ns = obj->o_get("faultcodens").toString().data();
use = SOAP_LITERAL;
if (!obj->o_get("_name").toString().empty()) {
if (function) {
sdlFaultMap::iterator iter =
function->faults.find(obj->o_get("_name").toString().data());
if (iter != function->faults.end()) {
fault = iter->second;
if (function->binding &&
function->binding->bindingType == BINDING_SOAP &&
fault->bindingAttributes) {
sdlSoapBindingFunctionFaultPtr fb = fault->bindingAttributes;
use = fb->use;
if (fault_ns.empty()) {
fault_ns = fb->ns;
}
}
}
}
} else if (function && function->faults.size() == 1) {
fault = function->faults[0];
if (function->binding &&
function->binding->bindingType == BINDING_SOAP &&
fault->bindingAttributes) {
sdlSoapBindingFunctionFaultPtr fb = fault->bindingAttributes;
use = fb->use;
if (fault_ns.empty()) {
fault_ns = fb->ns;
}
}
}
if (fault_ns.empty() && fault && fault->details.size() == 1) {
sdlParamPtr sparam = fault->details[0];
if (sparam->element) {
fault_ns = sparam->element->namens;
}
}
if (version == SOAP_1_1) {
if (!obj->o_get("faultcode").toString().empty()) {
xmlNodePtr node = xmlNewNode(NULL, BAD_CAST("faultcode"));
String str = StringUtil::HtmlEncode(obj->o_get("faultcode"),
StringUtil::QuoteStyle::Double,
"UTF-8", true);
xmlAddChild(param, node);
if (!fault_ns.empty()) {
xmlNsPtr nsptr = encode_add_ns(node, fault_ns.c_str());
xmlChar *code = xmlBuildQName(BAD_CAST(str.data()), nsptr->prefix,
NULL, 0);
xmlNodeSetContent(node, code);
xmlFree(code);
} else {
xmlNodeSetContentLen(node, BAD_CAST(str.data()), str.size());
}
}
if (!obj->o_get("faultstring").toString().empty()) {
xmlNodePtr node = master_to_xml(get_conversion(KindOfString),
obj->o_get("faultstring"), SOAP_LITERAL,
param);
xmlNodeSetName(node, BAD_CAST("faultstring"));
}
if (!obj->o_get("faultactor").toString().empty()) {
xmlNodePtr node = master_to_xml(get_conversion(KindOfString),
obj->o_get("faultactor"), SOAP_LITERAL,
param);
xmlNodeSetName(node, BAD_CAST("faultactor"));
}
detail_name = "detail";
} else {
if (!obj->o_get("faultcode").toString().empty()) {
xmlNodePtr node = xmlNewChild(param, ns, BAD_CAST("Code"), NULL);
String str = StringUtil::HtmlEncode(obj->o_get("faultcode"),
StringUtil::QuoteStyle::Double,
"UTF-8", true);
node = xmlNewChild(node, ns, BAD_CAST("Value"), NULL);
if (!fault_ns.empty()) {
xmlNsPtr nsptr = encode_add_ns(node, fault_ns.c_str());
xmlChar *code = xmlBuildQName(BAD_CAST(str.data()), nsptr->prefix,
NULL, 0);
xmlNodeSetContent(node, code);
xmlFree(code);
} else {
xmlNodeSetContentLen(node, BAD_CAST(str.data()), str.size());
}
}
if (!obj->o_get("faultstring").toString().empty()) {
xmlNodePtr node = xmlNewChild(param, ns, BAD_CAST("Reason"), NULL);
node = master_to_xml(get_conversion(KindOfString), obj->o_get("faultstring"),
SOAP_LITERAL, node);
xmlNodeSetName(node, BAD_CAST("Text"));
xmlSetNs(node, ns);
}
detail_name = SOAP_1_2_ENV_NS_PREFIX":Detail";
}
if (fault && fault->details.size() == 1) {
xmlNodePtr node;
Variant detail;
sdlParamPtr sparam;
xmlNodePtr x;
if (!obj->o_get("detail").isNull()) {
detail = obj->o_get("detail");
}
node = xmlNewNode(NULL, BAD_CAST(detail_name));
xmlAddChild(param, node);
sparam = fault->details[0];
if (detail.isObject() && sparam->element) {
Variant prop = detail.toObject()->o_get(sparam->element->name.c_str());
if (!prop.isNull()) {
detail = prop;
}
}
x = serialize_parameter(sparam, detail, 1, NULL, use, node);
if (function &&
function->binding &&
function->binding->bindingType == BINDING_SOAP &&
function->bindingAttributes) {
sdlSoapBindingFunctionPtr fnb = function->bindingAttributes;
if (fnb->style == SOAP_RPC && !sparam->element) {
if (fault->bindingAttributes) {
sdlSoapBindingFunctionFaultPtr fb = fault->bindingAttributes;
if (!fb->ns.empty()) {
xmlNsPtr ns = encode_add_ns(x, fb->ns.c_str());
xmlSetNs(x, ns);
}
}
} else {
if (sparam->element) {
xmlNsPtr ns = encode_add_ns(x, sparam->element->namens.c_str());
xmlNodeSetName(x, BAD_CAST(sparam->element->name.c_str()));
xmlSetNs(x, ns);
}
}
}
if (use == SOAP_ENCODED && version == SOAP_1_2) {
xmlSetNsProp(x, envelope->ns, BAD_CAST("encodingStyle"),
BAD_CAST(SOAP_1_2_ENC_NAMESPACE));
}
} else if (!obj->o_get("detail").isNull()) {
serialize_zval(obj->o_get("detail"), sdlParamPtr(), detail_name, use, param);
}
} else {
if (!headers.empty()) {
head = xmlNewChild(envelope, ns, BAD_CAST("Header"), NULL);
for (ArrayIter iter(headers); iter; ++iter) {
soapHeader *h = iter.second().toResource().getTyped<soapHeader>();
if (!h->retval.isNull()) {
encodePtr hdr_enc;
int hdr_use = SOAP_LITERAL;
Variant &hdr_ret = h->retval;
const char *hdr_ns = h->hdr ? h->hdr->ns.c_str() : NULL;
const char *hdr_name = h->function_name.data();
if (h->retval.isObject() &&
h->retval.toObject().is<c_SoapHeader>()) {
c_SoapHeader *ht = h->retval.toObject().getTyped<c_SoapHeader>();
string key;
if (!ht->m_namespace.empty()) {
key += ht->m_namespace.data();
key += ':';
hdr_ns = ht->m_namespace.data();
}
if (!ht->m_name.empty()) {
key += ht->m_name.data();
hdr_name = ht->m_name.data();
}
if (function && function->binding &&
function->binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = function->bindingAttributes;
sdlSoapBindingFunctionHeaderMap::iterator iter =
fnb->output.headers.find(key);
if (iter != fnb->output.headers.end()) {
hdr_enc = iter->second->encode;
hdr_use = iter->second->use;
}
}
hdr_ret = ht->m_data;
}
if (h->function) {
if (serialize_response_call2(head, h->function,
h->function_name.data(), uri, hdr_ret,
version, 0) == SOAP_ENCODED) {
use = SOAP_ENCODED;
}
} else {
xmlNodePtr xmlHdr = master_to_xml(hdr_enc, hdr_ret, hdr_use, head);
if (hdr_name) {
xmlNodeSetName(xmlHdr, BAD_CAST(hdr_name));
}
if (hdr_ns) {
xmlNsPtr nsptr = encode_add_ns(xmlHdr,hdr_ns);
xmlSetNs(xmlHdr, nsptr);
}
}
}
}
if (head->children == NULL) {
xmlUnlinkNode(head);
xmlFreeNode(head);
}
}
body = xmlNewChild(envelope, ns, BAD_CAST("Body"), NULL);
if (serialize_response_call2(body, function.get(), function_name, uri, ret,
version, 1) == SOAP_ENCODED) {
use = SOAP_ENCODED;
}
}
if (use == SOAP_ENCODED) {
xmlNewNs(envelope, BAD_CAST(XSD_NAMESPACE), BAD_CAST(XSD_NS_PREFIX));
if (version == SOAP_1_1) {
xmlNewNs(envelope, BAD_CAST(SOAP_1_1_ENC_NAMESPACE),
BAD_CAST(SOAP_1_1_ENC_NS_PREFIX));
xmlSetNsProp(envelope, envelope->ns, BAD_CAST("encodingStyle"),
BAD_CAST(SOAP_1_1_ENC_NAMESPACE));
} else if (version == SOAP_1_2) {
xmlNewNs(envelope, BAD_CAST(SOAP_1_2_ENC_NAMESPACE),
BAD_CAST(SOAP_1_2_ENC_NS_PREFIX));
}
}
encode_finish();
if (function && function->responseName.empty() &&
body->children == NULL && head == NULL) {
xmlFreeDoc(doc);
return NULL;
}
return doc;
}
static void function_to_string(sdlFunctionPtr function, StringBuffer &sb) {
sdlParamPtr param;
sdlParamVec &res = function->responseParameters;
if (!res.empty()) {
if (res.size() == 1) {
param = res[0];
if (param->encode && !param->encode->details.type_str.empty()) {
sb.append(param->encode->details.type_str);
sb.append(' ');
} else {
sb.append("UNKNOWN ");
}
} else {
sb.append("list(");
bool started = false;
for (unsigned int i = 0; i < res.size(); i++) {
param = res[i];
if (started) {
sb.append(", ");
} else {
started = true;
}
if (param->encode && !param->encode->details.type_str.empty()) {
sb.append(param->encode->details.type_str);
} else {
sb.append("UNKNOWN");
}
sb.append(" $");
sb.append(param->paramName);
}
sb.append(") ");
}
} else {
sb.append("void ");
}
sb.append(function->functionName);
sb.append('(');
sdlParamVec &req = function->requestParameters;
bool started = false;
for (unsigned int i = 0; i < req.size(); i++) {
param = req[i];
if (started) {
sb.append(", ");
} else {
started = true;
}
if (param->encode && !param->encode->details.type_str.empty()) {
sb.append(param->encode->details.type_str);
} else {
sb.append("UNKNOWN");
}
sb.append(" $");
sb.append(param->paramName);
}
sb.append(')');
}
static void type_to_string(sdlType *type, StringBuffer &buf, int level) {
StringBuffer sbspaces;
for (int i = 0; i < level;i++) {
sbspaces.append(' ');
}
String spaces = sbspaces.detach();
buf.append(spaces);
switch (type->kind) {
case XSD_TYPEKIND_SIMPLE:
if (type->encode) {
buf.append(type->encode->details.type_str);
buf.append(' ');
} else {
buf.append("anyType ");
}
buf.append(type->name);
break;
case XSD_TYPEKIND_LIST:
buf.append("list ");
buf.append(type->name);
if (!type->elements.empty()) {
buf.append(" {");
buf.append(type->elements[0]->name);
buf.append('}');
}
break;
case XSD_TYPEKIND_UNION:
buf.append("union ");
buf.append(type->name);
if (!type->elements.empty()) {
bool first = true;
buf.append(" {");
for (unsigned int i = 0; i < type->elements.size(); i++) {
if (!first) {
buf.append(',');
first = false;
}
buf.append(type->elements[i]->name);
}
buf.append('}');
}
break;
case XSD_TYPEKIND_COMPLEX:
case XSD_TYPEKIND_RESTRICTION:
case XSD_TYPEKIND_EXTENSION:
if (type->encode &&
(type->encode->details.type == KindOfArray ||
type->encode->details.type == SOAP_ENC_ARRAY)) {
sdlAttributeMap::iterator iter;
sdlExtraAttributeMap::iterator iterExtra;
if (!type->attributes.empty() &&
((iter = type->attributes.find(SOAP_1_1_ENC_NAMESPACE":arrayType"))
!= type->attributes.end())) {
if ((iterExtra = iter->second->extraAttributes.find
(WSDL_NAMESPACE":arrayType"))
!= iter->second->extraAttributes.end()) {
sdlExtraAttributePtr ext = iterExtra->second;
const char *end = strchr(ext->val.c_str(), '[');
int len;
if (end == NULL) {
len = ext->val.size();
} else {
len = end- ext->val.c_str();
}
if (len == 0) {
buf.append("anyType");
} else {
buf.append(ext->val.c_str(), len);
}
buf.append(' ');
buf.append(type->name);
if (end) {
buf.append(end);
}
}
} else {
sdlTypePtr elementType;
sdlAttributeMap::iterator iter;
sdlExtraAttributeMap::iterator iterExtra;
if (!type->attributes.empty() &&
((iter = type->attributes.find(SOAP_1_2_ENC_NAMESPACE":itemType"))
!= type->attributes.end())) {
if ((iterExtra = iter->second->extraAttributes.find
(WSDL_NAMESPACE":itemType"))
!= iter->second->extraAttributes.end()) {
sdlExtraAttributePtr ext = iterExtra->second;
buf.append(ext->val);
buf.append(' ');
}
} else if (type->elements.size() == 1 &&
(elementType = type->elements[0]) != NULL &&
elementType->encode &&
!elementType->encode->details.type_str.empty()) {
buf.append(elementType->encode->details.type_str);
buf.append(' ');
} else {
buf.append("anyType ");
}
buf.append(type->name);
if (!type->attributes.empty() &&
((iter = type->attributes.find(SOAP_1_2_ENC_NAMESPACE":arraySize"))
!= type->attributes.end())) {
if ((iterExtra = iter->second->extraAttributes.find
(WSDL_NAMESPACE":itemType"))
!= iter->second->extraAttributes.end()) {
sdlExtraAttributePtr ext = iterExtra->second;
buf.append('[');
buf.append(ext->val);
buf.append(']');
}
} else {
buf.append("[]");
}
}
} else {
buf.append("struct ");
buf.append(type->name);
buf.append(' ');
buf.append("{\n");
if ((type->kind == XSD_TYPEKIND_RESTRICTION ||
type->kind == XSD_TYPEKIND_EXTENSION) && type->encode) {
encodePtr enc = type->encode;
while (enc && enc->details.sdl_type &&
enc != enc->details.sdl_type->encode &&
enc->details.sdl_type->kind != XSD_TYPEKIND_SIMPLE &&
enc->details.sdl_type->kind != XSD_TYPEKIND_LIST &&
enc->details.sdl_type->kind != XSD_TYPEKIND_UNION) {
enc = enc->details.sdl_type->encode;
}
if (enc) {
buf.append(spaces);
buf.append(' ');
buf.append(type->encode->details.type_str);
buf.append(" _;\n");
}
}
if (type->model) {
model_to_string(type->model, buf, level+1);
}
if (!type->attributes.empty()) {
for (sdlAttributeMap::iterator iter = type->attributes.begin();
iter != type->attributes.end(); ++iter) {
sdlAttributePtr attr = iter->second;
buf.append(spaces);
buf.append(' ');
if (attr->encode && !attr->encode->details.type_str.empty()) {
buf.append(attr->encode->details.type_str);
buf.append(' ');
} else {
buf.append("UNKNOWN ");
}
buf.append(attr->name);
buf.append(";\n");
}
}
buf.append(spaces);
buf.append('}');
}
break;
default:
break;
}
}
static void model_to_string(sdlContentModelPtr model, StringBuffer &buf,
int level) {
int i;
switch (model->kind) {
case XSD_CONTENT_ELEMENT:
type_to_string(model->u_element, buf, level);
buf.append(";\n");
break;
case XSD_CONTENT_ANY:
for (i = 0;i < level;i++) {
buf.append(' ');
}
buf.append("<anyXML> any;\n");
break;
case XSD_CONTENT_SEQUENCE:
case XSD_CONTENT_ALL:
case XSD_CONTENT_CHOICE: {
for (unsigned int i = 0; i < model->u_content.size(); i++) {
sdlContentModelPtr tmp = model->u_content[i];
model_to_string(tmp, buf, level);
}
break;
}
case XSD_CONTENT_GROUP:
model_to_string(model->u_group->model, buf, level);
default:
break;
}
}
///////////////////////////////////////////////////////////////////////////////
// soap fault functions
const StaticString
s_HTTP_USER_AGENT("HTTP_USER_AGENT"),
s__SERVER("_SERVER"),
s_Shockwave_Flash("Shockwave Flash");
static void send_soap_server_fault(sdlFunctionPtr function, Variant fault,
soapHeader *hdr) {
USE_SOAP_GLOBAL;
bool use_http_error_status = true;
GlobalVariables *g = get_global_variables();
if (g->get(s__SERVER)[s_HTTP_USER_AGENT].toString() == s_Shockwave_Flash) {
use_http_error_status = false;
}
if (use_http_error_status) {
f_header("HTTP/1.1 500 Internal Service Error");
}
output_xml_header(SOAP_GLOBAL(soap_version));
Array headers;
if (hdr) headers.append(Resource(hdr));
xmlDocPtr doc_return = serialize_response_call
(function, NULL, NULL, fault, headers, SOAP_GLOBAL(soap_version));
f_ob_end_clean(); // dump all buffered output
xmlChar *buf; int size;
xmlDocDumpMemory(doc_return, &buf, &size);
if (buf) {
echo(String((const char *)buf, size, CopyString));
xmlFree(buf);
}
xmlFreeDoc(doc_return);
}
static void send_soap_server_fault(sdlFunctionPtr function, Exception &e,
soapHeader *hdr) {
USE_SOAP_GLOBAL;
if (SOAP_GLOBAL(use_soap_error_handler)) {
send_soap_server_fault(sdlFunctionPtr(), create_soap_fault(e), NULL);
} else {
throw create_soap_fault(e); // assuming we are in "catch"
}
}
static void throw_soap_server_fault(litstr code, litstr fault) {
send_soap_server_fault(sdlFunctionPtr(), create_soap_fault(code, fault),
NULL);
throw ExitException(1);
}
bool f_use_soap_error_handler(bool handler /* = true */) {
USE_SOAP_GLOBAL;
bool old = SOAP_GLOBAL(use_soap_error_handler);
SOAP_GLOBAL(use_soap_error_handler) = handler;
return old;
}
bool f_is_soap_fault(CVarRef fault) {
return fault.instanceof(SystemLib::s_SoapFaultClass);
}
int64_t f__soap_active_version() {
USE_SOAP_GLOBAL;
return SOAP_GLOBAL(soap_version);
}
///////////////////////////////////////////////////////////////////////////////
// class SoapServer
c_SoapServer::c_SoapServer(Class* cb) :
ExtObjectData(cb),
m_type(SOAP_FUNCTIONS),
m_version(SOAP_1_1),
m_sdl(NULL),
m_encoding(NULL),
m_typemap(NULL),
m_features(0),
m_send_errors(1) {
}
c_SoapServer::~c_SoapServer() {
}
const StaticString
s_soap_version("soap_version"),
s_uri("uri"),
s_actor("actor"),
s_encoding("encoding"),
s_classmap("classmap"),
s_typemap("typemap"),
s_features("features"),
s_cache_wsdl("cache_wsdl"),
s_send_errors("send_errors"),
s_location("location"),
s_style("style"),
s_use("use"),
s_stream_context("stream_context"),
s_login("login"),
s_password("password"),
s_authentication("authentication"),
s_proxy_host("proxy_host"),
s_proxy_port("proxy_port"),
s_proxy_login("proxy_login"),
s_proxy_password("proxy_password"),
s_trace("trace"),
s_exceptions("exceptions"),
s_compression("compression"),
s_connection_timeout("connection_timeout"),
s_user_agent("user_agent"),
s_soapaction("soapaction");
void c_SoapServer::t___construct(CVarRef wsdl,
CArrRef options /* = null_array */) {
USE_SOAP_GLOBAL;
SoapServerScope ss(this);
try {
if (!wsdl.isString() && !wsdl.isNull()) {
throw SoapException("Invalid parameters");
}
m_send_errors = 1;
int64_t cache_wsdl = SOAP_GLOBAL(cache);
int version = SOAP_1_1;
Array typemap_ht;
if (!options.empty()) {
if (options[s_soap_version].isInteger()) {
int64_t tmp = options[s_soap_version].toInt64();
if (tmp == SOAP_1_1 || tmp == SOAP_1_2) {
version = tmp;
}
}
if (options[s_uri].isString()) {
m_uri = options[s_uri].toString();
} else if (wsdl.isNull()) {
throw SoapException("'uri' option is required in nonWSDL mode");
}
if (options[s_actor].isString()) {
m_actor = options[s_actor].toString();
}
if (options[s_encoding].isString()) {
String tmp = options[s_encoding].toString();
m_encoding = xmlFindCharEncodingHandler(tmp.data());
if (m_encoding == NULL) {
throw SoapException("Invalid 'encoding' option - '%s'", tmp.data());
}
s_soap_data->register_encoding(m_encoding);
}
if (options[s_classmap].isArray()) {
m_classmap = options[s_classmap].toArray();
}
if (options[s_typemap].isArray()) {
typemap_ht = options[s_typemap].toArray();
}
if (options[s_features].isInteger()) {
m_features = options[s_features].toInt64();
}
if (options[s_cache_wsdl].isInteger()) {
cache_wsdl = options[s_cache_wsdl].toInt64();
}
if (options[s_send_errors].isInteger() ||
options[s_send_errors].is(KindOfBoolean)) {
m_send_errors = options[s_send_errors].toInt64();
}
} else if (wsdl.isNull()) {
throw SoapException("'uri' option is required in nonWSDL mode");
}
m_version = version;
m_type = SOAP_FUNCTIONS;
m_soap_functions.functions_all = false;
if (!wsdl.isNull()) {
m_sdl = s_soap_data->get_sdl(wsdl.toString().data(), cache_wsdl);
if (m_uri.isNull()) {
if (!m_sdl->target_ns.empty()) {
m_uri = String(m_sdl->target_ns);
} else {
/*FIXME*/
m_uri = String("http://unknown-uri/");
}
}
}
if (!typemap_ht.empty()) {
m_typemap = soap_create_typemap(m_sdl, typemap_ht);
}
} catch (Exception &e) {
throw create_soap_fault(e);
}
}
void c_SoapServer::t_setclass(int _argc, CStrRef name,
CArrRef _argv /* = null_array */) {
SoapServerScope ss(this);
if (f_class_exists(name, true)) {
m_type = SOAP_CLASS;
m_soap_class.name = name;
m_soap_class.argv = _argv;
m_soap_class.persistance = SOAP_PERSISTENCE_REQUEST;
} else {
raise_warning("Tried to set a non existant class (%s)", name.data());
}
}
void c_SoapServer::t_setobject(CObjRef obj) {
SoapServerScope ss(this);
m_type = SOAP_OBJECT;
m_soap_object = obj;
}
void c_SoapServer::t_addfunction(CVarRef func) {
SoapServerScope ss(this);
Array funcs;
if (func.isString()) {
funcs.append(func);
} else if (func.isArray()) {
funcs = func.toArray();
} else if (func.isInteger()) {
if (func.toInt64() == SOAP_FUNCTIONS_ALL) {
m_soap_functions.ft.clear();
m_soap_functions.ftOriginal.clear();
m_soap_functions.functions_all = true;
} else {
raise_warning("Invalid value passed");
}
return;
}
if (m_type == SOAP_FUNCTIONS) {
for (ArrayIter iter(funcs); iter; ++iter) {
if (!iter.second().isString()) {
raise_warning("Tried to add a function that isn't a string");
return;
}
String function_name = iter.second().toString();
if (!f_function_exists(function_name)) {
raise_warning("Tried to add a non existant function '%s'",
function_name.data());
return;
}
m_soap_functions.ft.set(f_strtolower(function_name), 1);
m_soap_functions.ftOriginal.set(function_name, 1);
}
}
}
Variant c_SoapServer::t_getfunctions() {
SoapServerScope ss(this);
String class_name;
if (m_type == SOAP_OBJECT) {
class_name = m_soap_object->o_getClassName();
} else if (m_type == SOAP_CLASS) {
class_name = m_soap_class.name;
} else if (m_soap_functions.functions_all) {
return ClassInfo::GetSystemFunctions() + ClassInfo::GetUserFunctions();
} else if (!m_soap_functions.ft.empty()) {
return f_array_keys(m_soap_functions.ftOriginal);
}
ClassInfo::MethodVec methods;
ClassInfo::GetClassMethods(methods, class_name.data());
Array ret = Array::Create();
for (unsigned int i = 0; i < methods.size(); i++) {
ClassInfo::MethodInfo *info = methods[i];
if (info->attribute & ClassInfo::IsPublic) {
ret.append(info->name);
}
}
return ret;
}
static bool valid_function(c_SoapServer *server, Object &soap_obj,
CStrRef fn_name) {
HPHP::Class* cls = nullptr;
if (server->m_type == SOAP_OBJECT || server->m_type == SOAP_CLASS) {
cls = server->m_soap_object->getVMClass();
} else if (server->m_soap_functions.functions_all) {
return f_function_exists(fn_name);
} else if (!server->m_soap_functions.ft.empty()) {
return server->m_soap_functions.ft.exists(f_strtolower(fn_name));
}
HPHP::Func* f = cls->lookupMethod(fn_name.get());
return (f && f->isPublic());
}
const StaticString
s_HTTP_CONTENT_ENCODING("HTTP_CONTENT_ENCODING"),
s_gzip("gzip"),
s_xgzip("x-gzip"),
s_deflate("deflate");
void c_SoapServer::t_handle(CStrRef request /* = null_string */) {
USE_SOAP_GLOBAL;
SoapServerScope ss(this);
SOAP_GLOBAL(soap_version) = m_version;
// 0. serving WSDL
Transport *transport = g_context->getTransport();
if (transport && transport->getMethod() == Transport::Method::GET &&
transport->getCommand() == "wsdl") {
if (!m_sdl) {
throw_soap_server_fault("Server", "WSDL generation is not supported");
}
f_header("Content-Type: text/xml; charset=utf-8");
Variant ret = f_readfile(m_sdl->source.c_str());
if (same(ret, false)) {
throw_soap_server_fault("Server", "Couldn't find WSDL");
}
return;
}
if (!f_ob_start()) {
throw SoapException("ob_start failed");
}
// 1. process request
String req;
if (!request.isNull()) {
req = request;
} else {
int size;
const char *data = NULL;
if (transport) {
data = (const char *)transport->getPostData(size);
}
if (!data || !*data || !size) {
return;
}
req = String(data, size, CopyString);
GlobalVariables *g = get_global_variables();
if (g->get(s__SERVER).toArray().exists(s_HTTP_CONTENT_ENCODING)) {
String encoding = g->get(s__SERVER)[s_HTTP_CONTENT_ENCODING].toString();
Variant ret;
if (encoding == s_gzip || encoding == s_xgzip) {
ret = f_gzinflate(String(data, size, CopyString));
} else if (encoding == s_deflate) {
ret = f_gzuncompress(String(data, size, CopyString));
} else {
raise_warning("Request is encoded with unknown compression '%s'",
encoding.data());
return;
}
if (!ret.isString()) {
raise_warning("Can't uncompress compressed request");
return;
}
req = ret.toString();
}
}
xmlDocPtr doc_request = soap_xmlParseMemory(req.data(), req.size());
if (doc_request == NULL) {
throw_soap_server_fault("Client", "Bad Request");
}
if (xmlGetIntSubset(doc_request) != NULL) {
xmlNodePtr env = get_node(doc_request->children,"Envelope");
if (env && env->ns) {
if (strcmp((char*)env->ns->href, SOAP_1_1_ENV_NAMESPACE) == 0) {
SOAP_GLOBAL(soap_version) = SOAP_1_1;
} else if (strcmp((char*)env->ns->href,SOAP_1_2_ENV_NAMESPACE) == 0) {
SOAP_GLOBAL(soap_version) = SOAP_1_2;
}
}
xmlFreeDoc(doc_request);
throw_soap_server_fault("Server", "DTD are not supported by SOAP");
}
// 2. find out which PHP function to call with what params
SoapServiceScope sss(this);
String function_name;
Array params;
int soap_version = 0;
sdlFunctionPtr function;
try {
function = deserialize_function_call(m_sdl, doc_request, m_actor.c_str(),
function_name, params, soap_version,
m_soap_headers);
} catch (Exception &e) {
xmlFreeDoc(doc_request);
send_soap_server_fault(function, e, NULL);
return;
}
xmlFreeDoc(doc_request);
// 3. we may need an object
Object soap_obj;
if (m_type == SOAP_OBJECT) {
soap_obj = m_soap_object;
} else if (m_type == SOAP_CLASS) {
try {
soap_obj = create_object(m_soap_class.name,
m_soap_class.argv);
} catch (Exception &e) {
send_soap_server_fault(function, e, NULL);
return;
}
}
// 4. process soap headers
for (ArrayIter iter(m_soap_headers); iter; ++iter) {
soapHeader *h = iter.second().toResource().getTyped<soapHeader>();
if (m_sdl && !h->function && !h->hdr) {
if (h->mustUnderstand) {
throw_soap_server_fault("MustUnderstand","Header not understood");
}
continue;
}
String fn_name = h->function_name;
if (valid_function(this, soap_obj, fn_name)) {
try {
if (m_type == SOAP_CLASS || m_type == SOAP_OBJECT) {
h->retval = vm_call_user_func
(CREATE_VECTOR2(soap_obj, fn_name), h->parameters);
} else {
h->retval = vm_call_user_func(fn_name, h->parameters);
}
} catch (Exception &e) {
send_soap_server_fault(function, e, h);
return;
}
if (h->retval.isObject() &&
h->retval.getObjectData()->instanceof(SystemLib::s_SoapFaultClass)) {
send_soap_server_fault(function, h->retval, h);
return;
}
} else if (h->mustUnderstand) {
throw_soap_server_fault("MustUnderstand","Header not understood");
}
}
// 5. main call
String fn_name = function_name;
Variant retval;
if (valid_function(this, soap_obj, fn_name)) {
try {
if (m_type == SOAP_CLASS || m_type == SOAP_OBJECT) {
retval = vm_call_user_func
(CREATE_VECTOR2(soap_obj, fn_name), params);
} else {
retval = vm_call_user_func(fn_name, params);
}
} catch (Exception &e) {
send_soap_server_fault(function, e, NULL);
return;
}
if (retval.isObject() &&
retval.toObject()->instanceof(SystemLib::s_SoapFaultClass)) {
send_soap_server_fault(function, retval, NULL);
return;
}
} else {
throw SoapException("Function '%s' doesn't exist", fn_name.data());
}
// 6. serialize response
String response_name;
if (function && !function->responseName.empty()) {
response_name = function->responseName;
} else {
response_name = function_name + "Response";
}
xmlDocPtr doc_return = NULL;
try {
doc_return = serialize_response_call(function, response_name.data(),
m_uri.c_str(), retval, m_soap_headers,
soap_version);
} catch (Exception &e) {
send_soap_server_fault(function, e, NULL);
return;
}
// 7. throw away all buffered output so far, so we can send back a clean
// soap resposne
f_ob_end_clean();
// 8. special case
if (doc_return == NULL) {
f_header("HTTP/1.1 202 Accepted");
f_header("Content-Length: 0");
return;
}
// 9. XML response
xmlChar *buf; int size;
xmlDocDumpMemory(doc_return, &buf, &size);
xmlFreeDoc(doc_return);
if (buf == NULL || size == 0) {
if (buf) xmlFree(buf);
throw SoapException("Dump memory failed");
}
output_xml_header(soap_version);
if (buf) {
echo(String((char*)buf, size, CopyString));
xmlFree(buf);
}
}
void c_SoapServer::t_setpersistence(int64_t mode) {
SoapServerScope ss(this);
if (m_type == SOAP_CLASS) {
if (mode == SOAP_PERSISTENCE_SESSION || mode == SOAP_PERSISTENCE_REQUEST) {
m_soap_class.persistance = mode;
} else {
raise_warning("Tried to set persistence with bogus value (%" PRId64 ")",
mode);
}
} else {
raise_warning("Tried to set persistence when you are using you "
"SOAP SERVER in function mode, no persistence needed");
}
}
void c_SoapServer::t_fault(CVarRef code, CStrRef fault,
CStrRef actor /* = null_string */,
CVarRef detail /* = null */,
CStrRef name /* = null_string */) {
SoapServerScope ss(this);
Object obj(SystemLib::AllocSoapFaultObject(code, fault, actor, detail, name));
send_soap_server_fault(sdlFunctionPtr(), obj, NULL);
}
void c_SoapServer::t_addsoapheader(CObjRef fault) {
SoapServerScope ss(this);
soapHeader *p = NEWOBJ(soapHeader)();
Resource obj(p);
p->function = NULL;
p->mustUnderstand = false;
p->retval = fault;
p->hdr = NULL;
m_soap_headers.append(obj);
}
///////////////////////////////////////////////////////////////////////////////
// class SoapClient
c_SoapClient::c_SoapClient(Class* cb) :
ExtObjectDataFlags<ObjectData::HasCall>(cb),
m_soap_version(SOAP_1_1),
m_sdl(NULL),
m_encoding(NULL),
m_typemap(NULL),
m_features(0),
m_style(SOAP_RPC),
m_use(SOAP_LITERAL),
m_authentication(SOAP_AUTHENTICATION_BASIC),
m_proxy_port(0),
m_connection_timeout(0),
m_max_redirect(0),
m_use11(true),
m_compression(false),
m_exceptions(true),
m_trace(false) {
}
c_SoapClient::~c_SoapClient() {
}
void c_SoapClient::t___construct(CVarRef wsdl,
CArrRef options /* = null_array */) {
USE_SOAP_GLOBAL;
SoapClientScope ss(this);
try {
if (!wsdl.isString() && !wsdl.isNull()) {
throw SoapException("wsdl must be string or null");
}
int64_t cache_wsdl = SOAP_GLOBAL(cache);
if (!options.empty()) {
m_location = options[s_location];
if (wsdl.isNull()) {
/* Fetching non-WSDL mode options */
m_uri = options[s_uri];
m_style = options[s_style].toInt32(); // SOAP_RPC || SOAP_DOCUMENT
m_use = options[s_use].toInt32(); // SOAP_LITERAL || SOAP_ENCODED
if (m_uri.empty()) {
throw SoapException("'uri' option is required in nonWSDL mode");
}
if (m_location.empty()) {
throw SoapException("'location' option is required in nonWSDL mode");
}
}
if (options.exists(s_stream_context)) {
StreamContext *sc = NULL;
if (options[s_stream_context].isResource()) {
sc = options[s_stream_context].toResource()
.getTyped<StreamContext>();
}
if (!sc) {
throw SoapException("'stream_context' is not a StreamContext");
}
m_stream_context_options = sc->m_options;
}
if (options.exists(s_soap_version)) {
m_soap_version = options[s_soap_version].toInt32();
}
m_login = options[s_login].toString();
m_password = options[s_password].toString();
m_authentication = options[s_authentication].toInt32();
m_proxy_host = options[s_proxy_host].toString();
m_proxy_port = options[s_proxy_port].toInt32();
m_proxy_login = options[s_proxy_login].toString();
m_proxy_password = options[s_proxy_password].toString();
m_trace = options[s_trace].toBoolean();
if (options.exists(s_exceptions)) {
m_exceptions = options[s_exceptions].toBoolean();
}
if (options.exists(s_compression)) {
m_compression = options[s_compression].toBoolean();
}
String encoding = options[s_encoding].toString();
if (!encoding.empty()) {
m_encoding = xmlFindCharEncodingHandler(encoding.data());
if (m_encoding == NULL) {
throw SoapException("Invalid 'encoding' option - '%s'",
encoding.data());
}
s_soap_data->register_encoding(m_encoding);
}
m_classmap = options[s_classmap].toArray();
m_features = options[s_features].toInt32();
m_connection_timeout = options[s_connection_timeout].toInt64();
m_user_agent = options[s_user_agent].toString();
if (options.exists(s_cache_wsdl)) {
cache_wsdl = options[s_cache_wsdl].toInt64();
}
} else if (wsdl.isNull()) {
throw SoapException("'location' and 'uri' options are required in "
"nonWSDL mode");
}
if (!wsdl.isNull()) {
int old_soap_version = SOAP_GLOBAL(soap_version);
SOAP_GLOBAL(soap_version) = m_soap_version;
String swsdl = wsdl.toString();
if (swsdl.find("http://") == 0 || swsdl.find("https://") == 0) {
HttpClient http(m_connection_timeout, m_max_redirect, m_use11, true);
if (!m_proxy_host.empty() && m_proxy_port) {
http.proxy(m_proxy_host.data(), m_proxy_port, m_proxy_login.data(),
m_proxy_password.data());
}
if (!m_login.empty()) {
http.auth(m_login.data(), m_password.data(), !m_digest);
}
http.setStreamContextOptions(m_stream_context_options);
m_sdl = s_soap_data->get_sdl(swsdl.data(), cache_wsdl, &http);
} else {
m_sdl = s_soap_data->get_sdl(swsdl.data(), cache_wsdl);
}
SOAP_GLOBAL(soap_version) = old_soap_version;
}
Variant v = options[s_typemap];
if (v.isArray()) {
Array arr = v.toArray();
if (!arr.empty()) {
m_typemap = soap_create_typemap(m_sdl, arr);
}
}
} catch (Exception &e) {
throw create_soap_fault(e);
}
}
Variant c_SoapClient::t___call(Variant name, Variant args) {
return t___soapcall(name.toString(), args.toArray());
}
Variant c_SoapClient::t___soapcall(CStrRef name, CArrRef args,
CArrRef options /* = null_array */,
CVarRef input_headers /* = null_variant */,
VRefParam output_headers /* = null */) {
SoapClientScope ss(this);
String location, soap_action, uri;
if (!options.isNull()) {
if (options[s_location].isString()) {
location = options[s_location].toString();
if (location.isNull()) {
location = m_location;
}
}
if (options[s_soapaction].isString()) {
soap_action = options[s_soapaction].toString();
}
if (options[s_uri].isString()) {
uri = options[s_uri].toString();
}
}
Array soap_headers = Array::Create();
if (input_headers.isNull()) {
} else if (input_headers.isArray()) {
Array arr = input_headers.toArray();
verify_soap_headers_array(arr);
soap_headers = input_headers;
} else if (input_headers.isObject() &&
input_headers.toObject().is<c_SoapHeader>()) {
soap_headers = CREATE_VECTOR1(input_headers);
} else{
raise_warning("Invalid SOAP header");
return uninit_null();
}
if (!m_default_headers.isNull()) {
soap_headers.merge(m_default_headers.toArray());
}
output_headers = Array::Create();
if (m_trace) {
m_last_request.reset();
m_last_response.reset();
}
if (location.empty()) {
location = m_location;
}
m_soap_fault.reset();
SoapServiceScope sss(this);
Variant return_value;
bool ret = false;
xmlDocPtr request = NULL;
if (m_sdl) {
sdlFunctionPtr fn = get_function(m_sdl, name.data());
if (fn) {
sdlBindingPtr binding = fn->binding;
bool one_way = false;
if (fn->responseName.empty() && fn->responseParameters.empty() &&
soap_headers.empty()) {
one_way = true;
}
if (location.empty()) {
location = binding->location;
}
Variant response;
try {
if (binding->bindingType == BINDING_SOAP) {
sdlSoapBindingFunctionPtr fnb = fn->bindingAttributes;
request = serialize_function_call
(this, fn, NULL, fnb->input.ns.c_str(), args, soap_headers);
ret = do_request(this, request, location.data(),
fnb->soapAction.c_str(), m_soap_version, one_way,
response);
} else {
request = serialize_function_call
(this, fn, NULL, m_sdl->target_ns.c_str(), args, soap_headers);
ret = do_request(this, request, location.data(), NULL,
m_soap_version, one_way, response);
}
} catch (Exception &e) {
xmlFreeDoc(request);
throw create_soap_fault(e);
}
xmlFreeDoc(request);
if (ret && response.isString()) {
encode_reset_ns();
String sresponse = response.toString();
ret = parse_packet_soap(this, sresponse.data(), sresponse.size(),
fn, NULL, return_value, output_headers);
encode_finish();
}
} else {
StringBuffer error;
error.append("Function (\"");
error.append(name.data());
error.append("\") is not a valid method for this service");
m_soap_fault = create_soap_fault("Client", error.detach());
}
} else {
string action;
if (m_uri.empty()) {
m_soap_fault =
create_soap_fault("Client", "Error finding \"uri\" property");
} else if (location.empty()) {
m_soap_fault =
create_soap_fault("Client", "Error could not find \"location\" "
"property");
} else {
request = serialize_function_call
(this, sdlFunctionPtr(), name.data(), m_uri.data(), args,
soap_headers);
if (soap_action.empty()) {
action += m_uri.data();
action += '#';
action += name.data();
} else {
action += (std::string) soap_action;
}
Variant response;
try {
ret = do_request(this, request, location.c_str(), action.c_str(),
m_soap_version, 0, response);
} catch (Exception &e) {
xmlFreeDoc(request);
throw create_soap_fault(e);
}
xmlFreeDoc(request);
if (ret && response.isString()) {
encode_reset_ns();
String sresponse = response.toString();
ret = parse_packet_soap(this, sresponse.data(), sresponse.size(),
sdlFunctionPtr(), name.data(), return_value,
output_headers);
encode_finish();
}
}
}
if (!ret && m_soap_fault.isNull()) {
m_soap_fault = create_soap_fault("Client", "Unknown Error");
}
if (!m_soap_fault.isNull()) {
throw m_soap_fault.toObject();
}
return return_value;
}
Variant c_SoapClient::t___getlastrequest() {
return m_last_request;
}
Variant c_SoapClient::t___getlastresponse() {
return m_last_response;
}
Variant c_SoapClient::t___getlastrequestheaders() {
return m_last_request_headers;
}
Variant c_SoapClient::t___getlastresponseheaders() {
return m_last_response_headers;
}
Variant c_SoapClient::t___getfunctions() {
SoapClientScope ss(this);
if (m_sdl) {
Array ret = Array::Create();
for (sdlFunctionMap::iterator iter = m_sdl->functions.begin();
iter != m_sdl->functions.end(); ++iter) {
StringBuffer sb;
function_to_string(iter->second, sb);
ret.append(sb.detach());
}
return ret;
}
return uninit_null();
}
Variant c_SoapClient::t___gettypes() {
SoapClientScope ss(this);
if (m_sdl) {
Array ret = Array::Create();
for (unsigned int i = 0; i < m_sdl->types.size(); i++) {
StringBuffer sb;
type_to_string(m_sdl->types[i].get(), sb, 0);
ret.append(sb.detach());
}
return ret;
}
return uninit_null();
}
Variant c_SoapClient::t___dorequest(CStrRef buf, CStrRef location, CStrRef action,
int64_t version, bool oneway /* = false */) {
if (location.empty()) {
m_soap_fault =
Object(SystemLib::AllocSoapFaultObject("HTTP", "Unable to parse URL"));
return uninit_null();
}
USE_SOAP_GLOBAL;
SoapClientScope ss(this);
HeaderMap headers;
String buffer(buf);
// compression
if (m_compression > 0) {
if (m_compression & SOAP_COMPRESSION_ACCEPT) {
headers["Accept-Encoding"].push_back("gzip, deflate");
}
int level = m_compression & 0x0f;
if (level > 9) level = 9;
if (level > 0) {
Variant ret;
if (m_compression & SOAP_COMPRESSION_DEFLATE) {
ret = f_gzcompress(buffer, level);
headers["Content-Encoding"].push_back("deflate");
} else {
ret = f_gzencode(buffer, level);
headers["Content-Encoding"].push_back("gzip");
}
if (!ret.isString()) return uninit_null();
buffer = ret.toString();
}
}
// prepare more headers
if (!m_user_agent.empty()) {
headers["User-Agent"].push_back(m_user_agent.data());
}
string contentType;
if (version == SOAP_1_2) {
contentType = "application/soap+xml; charset=utf-8";
contentType += "; action=\"";
contentType += action.data();
contentType += "\"";
headers["Content-Type"].push_back(contentType);
} else {
contentType = "text/xml; charset=utf-8";
headers["Content-Type"].push_back(contentType);
headers["SOAPAction"].push_back(string("\"") + action.data() + "\"");
}
// post the request
HttpClient http(m_connection_timeout, m_max_redirect, m_use11, true);
if (!m_proxy_host.empty() && m_proxy_port) {
http.proxy(m_proxy_host.data(), m_proxy_port, m_proxy_login.data(),
m_proxy_password.data());
}
if (!m_login.empty()) {
http.auth(m_login.data(), m_password.data(), !m_digest);
}
http.setStreamContextOptions(m_stream_context_options);
StringBuffer response;
int code = http.post(location.data(), buffer.data(), buffer.size(), response,
&headers);
if (code == 0) {
String msg = "Failed Sending HTTP Soap request";
if (!http.getLastError().empty()) {
msg += ": " + http.getLastError();
}
m_soap_fault = Object(SystemLib::AllocSoapFaultObject(
"HTTP", msg));
return uninit_null();
}
if (code != 200) {
String msg = response.detach();
if (msg.empty()) {
msg = HttpProtocol::GetReasonString(code);
}
m_soap_fault = Object(SystemLib::AllocSoapFaultObject("HTTP", msg));
return uninit_null();
}
// return response
if (SOAP_GLOBAL(features) & SOAP_WAIT_ONE_WAY_CALLS) {
oneway = false;
}
if (oneway) {
return "";
}
return response.detach();
}
Variant c_SoapClient::t___setcookie(CStrRef name,
CStrRef value /* = null_string */) {
if (!value.isNull()) {
m_cookies.set(name, CREATE_VECTOR1(value));
} else {
const Variant* t = o_realProp("_cookies", RealPropUnchecked);
if (t && t->isInitialized()) {
m_cookies.remove(name);
}
}
return uninit_null();
}
Variant c_SoapClient::t___setlocation(CStrRef new_location /* = null_string */){
Variant ret = m_location;
m_location = new_location;
return ret;
}
bool c_SoapClient::t___setsoapheaders(CVarRef headers /* = null_variant */) {
if (headers.isNull()) {
m_default_headers = uninit_null();
} else if (headers.isArray()) {
Array arr = headers.toArray();
verify_soap_headers_array(arr);
m_default_headers = arr;
} else if (headers.isObject() && headers.toObject().is<c_SoapHeader>()) {
m_default_headers = CREATE_VECTOR1(headers);
} else {
raise_warning("Invalid SOAP header");
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// class SoapVar
c_SoapVar::c_SoapVar(Class* cb) : ExtObjectData(cb) {
}
c_SoapVar::~c_SoapVar() {
}
void c_SoapVar::t___construct(CVarRef data, CVarRef type,
CStrRef type_name /* = null_string */,
CStrRef type_namespace /* = null_string */,
CStrRef node_name /* = null_string */,
CStrRef node_namespace /* = null_string */) {
USE_SOAP_GLOBAL;
if (type.isNull()) {
m_type = UNKNOWN_TYPE;
} else {
std::map<int, encodePtr> &defEncIndex = SOAP_GLOBAL(defEncIndex);
int64_t ntype = type.toInt64();
if (defEncIndex.find(ntype) != defEncIndex.end()) {
m_type = ntype;
} else {
raise_warning("Invalid type ID");
return;
}
}
if (data.toBoolean()) m_value = data;
if (!type_name.empty()) m_stype = type_name;
if (!type_namespace.empty()) m_ns = type_namespace;
if (!node_name.empty()) m_name = node_name;
if (!node_namespace.empty()) m_namens = node_namespace;
}
///////////////////////////////////////////////////////////////////////////////
// class SoapParam
c_SoapParam::c_SoapParam(Class* cb) : ExtObjectData(cb) {
}
c_SoapParam::~c_SoapParam() {
}
void c_SoapParam::t___construct(CVarRef data, CStrRef name) {
if (name.empty()) {
raise_warning("Invalid parameter name");
return;
}
m_name = name;
m_data = data;
}
///////////////////////////////////////////////////////////////////////////////
// class SoapHeader
c_SoapHeader::c_SoapHeader(Class* cb) :
ExtObjectData(cb) {
}
c_SoapHeader::~c_SoapHeader() {
}
void c_SoapHeader::t___construct(CStrRef ns, CStrRef name,
CVarRef data /* = null */,
bool mustunderstand /* = false */,
CVarRef actor /* = null */) {
if (ns.empty()) {
raise_warning("Invalid namespace");
return;
}
if (name.empty()) {
raise_warning("Invalid header name");
return;
}
m_namespace = ns;
m_name = name;
m_data = data;
m_mustUnderstand = mustunderstand;
if (actor.isInteger() &&
(actor.toInt64() == SOAP_ACTOR_NEXT ||
actor.toInt64() == SOAP_ACTOR_NONE ||
actor.toInt64() == SOAP_ACTOR_UNLIMATERECEIVER)) {
m_actor = actor.toInt64();
} else if (actor.isString() && !actor.toString().empty()) {
m_actor = actor.toString();
} else if (!actor.isNull()) {
raise_warning("Invalid actor");
}
}
///////////////////////////////////////////////////////////////////////////////
}
| 32.289629 | 86 | 0.579132 | [
"object",
"model"
] |
33c54033c4a5a87b98417624efbdf0c11a079c33 | 2,246 | cpp | C++ | test/compressor_expander.cpp | christiancrowle/q | 51160338ff4920ee82b3572389f8e337594c6248 | [
"MIT"
] | 1 | 2020-09-16T10:46:27.000Z | 2020-09-16T10:46:27.000Z | test/compressor_expander.cpp | Pogo0o/q | 1999563fddf2ae41f0046ee8a64c3aa85852f2cc | [
"MIT"
] | null | null | null | test/compressor_expander.cpp | Pogo0o/q | 1999563fddf2ae41f0046ee8a64c3aa85852f2cc | [
"MIT"
] | 1 | 2021-03-10T05:50:02.000Z | 2021-03-10T05:50:02.000Z | /*=============================================================================
Copyright (c) 2014-2020 Joel de Guzman. All rights reserved.
Distributed under the MIT License [ https://opensource.org/licenses/MIT ]
=============================================================================*/
#include <q/support/literals.hpp>
#include <q/fx/envelope.hpp>
#include <q/fx/dynamic.hpp>
#include <q_io/audio_file.hpp>
#include <vector>
#include <string>
namespace q = cycfi::q;
using namespace q::literals;
void process(std::string name)
{
////////////////////////////////////////////////////////////////////////////
// Read audio file
q::wav_reader src{"audio_files/" + name + ".wav"};
std::uint32_t const sps = src.sps();
std::vector<float> in(src.length());
src.read(in);
////////////////////////////////////////////////////////////////////////////
constexpr auto n_channels = 4;
std::vector<float> out(src.length() * n_channels);
// Envelope
auto env = q::peak_envelope_follower{ 10_s, sps };
// Compressors
auto comp = q::compressor{ -18_dB, 1.0/4 };
auto comp2 = q::soft_knee_compressor{ -18_dB, 3_dB, 1.0/4 };
auto makeup_gain = 4.0f;
// Expander
auto exp = q::expander{ -18_dB, 2.0/1.0 };
for (auto i = 0; i != in.size(); ++i)
{
auto pos = i * n_channels;
auto ch1 = pos;
auto ch2 = pos+1;
auto ch3 = pos+2;
auto ch4 = pos+3;
auto s = in[i];
// Original signal
out[ch1] = s;
// Envelope
q::decibel env_out = env(std::abs(s));
// Compressor
auto gain = float(comp(env_out)) * makeup_gain;
out[ch2] = s * gain;
// Soft Knee Compressor
gain = float(comp2(env_out)) * makeup_gain;
out[ch3] = s * gain;
// Expander
gain = float(exp(env_out));
out[ch4] = s * gain;
}
////////////////////////////////////////////////////////////////////////////
// Write to a wav file
q::wav_writer wav(
"results/comp_exp_" + name + ".wav", n_channels, sps
);
wav.write(out);
}
int main()
{
process("1a-Low-E");
process("Tapping D");
process("Hammer-Pull High E");
process("Bend-Slide G");
process("GStaccato");
return 0;
} | 24.955556 | 79 | 0.486643 | [
"vector"
] |
33ccf4bb746d7ec393cf755022dadf46abd9c465 | 13,956 | cpp | C++ | fasta.cpp | niu-lab/gclust | aa7f5be22d8b5f7c9d1693269c1b764802b7e885 | [
"Apache-2.0"
] | 11 | 2020-02-01T17:50:58.000Z | 2022-03-23T19:42:56.000Z | fasta.cpp | niu-lab/gclust | aa7f5be22d8b5f7c9d1693269c1b764802b7e885 | [
"Apache-2.0"
] | 4 | 2020-02-18T14:52:04.000Z | 2022-03-24T06:52:42.000Z | fasta.cpp | niu-lab/gclust | aa7f5be22d8b5f7c9d1693269c1b764802b7e885 | [
"Apache-2.0"
] | 4 | 2017-12-06T13:12:22.000Z | 2021-09-30T07:55:29.000Z | #include <fstream>
#include <iostream>
#include <algorithm>
#include "fasta.hpp"
// Filter 'n' in genome.
void filter_n(string &seq_rc)
{
// Bit by bit.
for(long i = 0; i < (long)seq_rc.length(); i++) {
// Adapted from Kurtz code in MUMmer v3.
switch(seq_rc[i])
{
case 'a': case 't': case 'g': case 'c': break;
default:
seq_rc[i] = '~';
}
}
}
// Return the reverse complement of sequence. This allows searching
// the plus strand of instances on the minus strand.
void reverse_complement(string &seq_rc, bool nucleotides_only)
{
// Reverse in-place.
reverse(seq_rc.begin(), seq_rc.end());
for(long i = 0; i < (long)seq_rc.length(); i++)
{
// Adapted from Kurtz code in MUMmer v3.
switch(seq_rc[i])
{
case 'a': seq_rc[i] = 't'; break;
case 'c': seq_rc[i] = 'g'; break;
case 'g': seq_rc[i] = 'c'; break;
case 't': seq_rc[i] = 'a'; break;
case 'r': seq_rc[i] = 'y'; break; /* a or g */
case 'y': seq_rc[i] = 'r'; break; /* c or t */
case 's': seq_rc[i] = 's'; break; /* c or g */
case 'w': seq_rc[i] = 'w'; break; /* a or t */
case 'm': seq_rc[i] = 'k'; break; /* a or c */
case 'k': seq_rc[i] = 'm'; break; /* g or t */
case 'b': seq_rc[i] = 'v'; break; /* c, g or t */
case 'd': seq_rc[i] = 'h'; break; /* a, g or t */
case 'h': seq_rc[i] = 'd'; break; /* a, c or t */
case 'v': seq_rc[i] = 'b'; break; /* a, c or g */
default:
if(!nucleotides_only) seq_rc[i] = 'n';
break; /* anything */
}
}
}
// trim a string.
void trim(string &line, long &start, long &end)
{
// Trim leading spaces.
for(long i = start; i < (int)line.length(); i++)
{
if(line[i] != ' ')
{
start = i;
break;
}
}
// Trim trailing spaces.
for(long i = line.length() - 1; i >= 0; i--) {
if(line[i] != ' ') {
end = i;
break;
}
if(i == 0) break;
}
}
// load data.
void load_fasta(string filename,
string &S,
vector<string> &descr,
vector<long> &startpos)
{
string meta, line;
long length = 0;
// Everything starts at zero.
startpos.push_back(0);
ifstream data(filename.c_str());
if(!data.is_open()) {
cerr << "unable to open " << filename << endl;
exit(1);
}
while(!data.eof())
{
getline(data, line); // Load one line at a time.
if(line.length() == 0) continue;
long start = 0, end = line.length() - 1;
// Meta tag line and start of a new sequence.
if(line[0] == '>') {
// Save previous sequence and meta data.
if(length > 0) {
descr.push_back(meta);
//cout<<meta<<endl;
S += '`'; // ` character used to separate strings
startpos.push_back(S.length());
//lengths.push_back(length+1);
}
// Reset parser state.
start = 1; meta = ""; length = 0;
}
trim(line, start, end);
// Collect meta data.
if(line[0] == '>') {
for(long i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
}else { // Collect sequence data.
length += end - start + 1;
for(long i = start; i <= end; i++) {
S += std::tolower(line[i]);
}
}
}
if(length > 0) {
descr.push_back(meta);
//cout<<meta<<endl;
}
cerr << "# S.length=" << S.length() << endl;
for(long i = 0; i < (long)descr.size(); i++) {
cerr << "# " << descr[i] << " " << startpos[i] << endl;
}
}
// Load part genomes of total for clustering.
// Previous genomes have been processed need to skip.
void load_part_genomes(string filename,
vector<Genome> &partgenomes,
vector<GenomeClustInfo> &totalgenomes,
long previous,
long number)
{
string meta, line, S;
long length = 0;
Genome tg;
ifstream data(filename.c_str());
if(!data.is_open()) {
cerr << "unable to open " << filename << endl;
exit(1);
}
// Skip previous genomes.
long i=0;
while(!data.eof()) {
getline(data, line);
if(line[0] == '>') {
i++;
if (i>previous){
break;
}
}
}
// Genome id from previous.
long id=i-1;
long loadnum=0;
// First one sequence.
meta = "";
long start = 1, end = line.length() - 1;
for(i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
S="";
while(!data.eof()) {
getline(data, line); // Load one line at a time.
if(line.length() == 0) continue;
long start = 0, end = line.length() - 1;
// Meta tag line and start of a new sequence.
if(line[0] == '>') {
// Save previous sequence and meta data.
if(length > 0) {
tg.descript=meta;
tg.id=id++;
tg.size=S.length();
tg.cont=S;
partgenomes.push_back(tg);
loadnum++;
S="";
// Check genomes loaded one time.
if (loadnum>=number){
break;
}
}
// Reset parser state.
start = 1; meta = ""; length = 0;
}
trim(line, start, end);
// Collect meta data.
if(line[0] == '>') {
for(long i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
}else { // Collect sequence data.
length += end - start + 1;
for(long i = start; i <= end; i++) {
S += std::tolower(line[i]);
}
}
}
// last sequence
if (loadnum<number){
if(length > 0) {
tg.descript=meta;
tg.id=id++;
tg.size=S.length();
tg.cont=S;
partgenomes.push_back(tg);
loadnum++;
}
}
}
// Load genomes from memory.
void load_part_genomes_mem(vector<Genome> &allpartgenomes,
vector<Genome> &partgenomes,
vector<GenomeClustInfo> &totalgenomes,
long previous,
long number)
{
Genome tg;
long loadnumber=0;
long genomes=allpartgenomes.size();
for (long i=previous; i<genomes; i++){
tg=allpartgenomes[i];
partgenomes.push_back(tg);
loadnumber++;
if (loadnumber>=number){
break;
}
}
}
// Load genomes from file.
void load_part_genomes_internal(string filename,
vector<Genome> &partgenomes,
vector<GenomeClustInfo> &totalgenomes,
long previous,
int &number,
long totalsize,
bool &ifend,
int memiden)
{
string meta, line, S;
Genome tg;
long length, loadgenomes, id, loadnumber, start, end, sizeadd, stablenumber;
length=loadgenomes=loadnumber=sizeadd=0;
if (memiden==100)
{
stablenumber=MAX_PARTNUMBERFORPERFECT;
}else{
stablenumber=MAX_PARTNUMBER;
}
bool beforeend=false;
ifend=false;
ifstream data(filename.c_str());
if(!data.is_open()) {
cerr << "unable to open " << filename << endl;
exit(1);
}
// Skip previous genomes.
long i=0;
while(!data.eof()) {
getline(data, line);
if(line[0] == '>') {
i++;
if (i>previous){ break;}
}
}
id=i-1; // Genome id from previous.
// First sequence.
meta = "";
start = 1; end = line.length() - 1;
for(i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
S="";
while(!data.eof())
{
getline(data, line); // Load one line at a time.
if(line.length() == 0) continue;
start = 0; end = line.length() - 1;
// Meta tag line and start of a new sequence.
if(line[0] == '>') {
// Save previous sequence and meta data.
if(length > 0) {
tg.descript=meta;
tg.id=id++;
tg.size=S.length();
tg.cont=S;
if (totalgenomes[tg.id].rep){
sizeadd+=tg.size;
if ((sizeadd<=totalsize)&&(loadgenomes<stablenumber)){
partgenomes.push_back(tg);
loadnumber++;
loadgenomes++;
}else{
beforeend=true;
break;
}
}else{
partgenomes.push_back(tg);
loadnumber++;
}
S="";
}
// Reset parser state.
start = 1; meta = ""; length = 0;
}
trim(line, start, end);
if(line[0] == '>') {
for(long i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
}else { // Collect sequence data.
length += end - start + 1;
for(long i = start; i <= end; i++) {
S += std::tolower(line[i]);
}
}
}
// The last one
if(length > 0) {
tg.descript=meta;
tg.id=id++;
tg.size=S.length();
tg.cont=S;
}
if (!beforeend){
partgenomes.push_back(tg);
loadnumber++;
if (totalgenomes[tg.id].rep){
loadgenomes++;
}
ifend=true;
}
number=loadnumber;
}
// Load genomes from memory.
void load_part_genomes_internal_mem(vector<Genome> &allpartgenomes,
vector<Genome> &partgenomes,
vector<GenomeClustInfo> &totalgenomes,
long previous,
int &number,
long totalsize,
bool &ifend,
int memiden)
{
Genome tg;
long loadnumber, loadgenomes, genomes, sizeadd, stablenumber, i;
loadnumber=loadgenomes=sizeadd=0;
genomes=allpartgenomes.size();
if (memiden==100)
{
stablenumber=MAX_PARTNUMBERFORPERFECT;
}else{
stablenumber=MAX_PARTNUMBER;
}
ifend=false;
for (i=previous; i<genomes; i++){
tg=allpartgenomes[i];
if (totalgenomes[tg.id].rep){
sizeadd+=tg.size;
if ((sizeadd<=totalsize)&&(loadgenomes<stablenumber)){
partgenomes.push_back(tg);
loadnumber++;
loadgenomes++;
}else{
break;
}
}else{
partgenomes.push_back(tg);
loadnumber++;
}
}
number=loadnumber;
if (i==genomes){
ifend=true;
}
}
// Load all genomes same as loading part genomes
void load_part_genomes_all(string filename, vector<Genome> &partgenomes)
{
string meta, line, S;
long length = 0;
Genome tg;
ifstream data(filename.c_str());
if(!data.is_open()) {
cerr << "unable to open " << filename << endl;
exit(1);
}
// Skip previous genomes.
long i=0;
while(!data.eof()) {
getline(data, line);
if(line[0] == '>') {
i++;
if (i>0){
break;
}
}
}
// Genome id from previous.
long id=0;
long loadnum=0;
// First one sequence.
meta = "";
long start = 1, end = line.length() - 1;
for(i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
S="";
while(!data.eof()) {
getline(data, line); // Load one line at a time.
if(line.length() == 0) continue;
long start = 0, end = line.length() - 1;
// Meta tag line and start of a new sequence.
if(line[0] == '>') {
// Save previous sequence and meta data.
if(length > 0) {
tg.descript=meta;
tg.id=id++;
tg.size=S.length();
tg.cont=S;
partgenomes.push_back(tg);
loadnum++;
S="";
}
// Reset parser state.
start = 1; meta = ""; length = 0;
}
trim(line, start, end);
// Collect meta data.
if(line[0] == '>') {
for(long i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
}else { // Collect sequence data.
length += end - start + 1;
for(long i = start; i <= end; i++) {
S += std::tolower(line[i]);
}
}
}
// last sequence
if(length > 0)
{
tg.descript=meta;
tg.id=id++;
tg.size=S.length();
tg.cont=S;
partgenomes.push_back(tg);
loadnum++;
}
}
//Test part genomes loading vector
void test_part(vector<Genome> &partgenomes)
{
Genome tg;
int s=partgenomes.size();
for (int i=0;i<s;i++){
tg=partgenomes[i];
cout<<"===========\n";
cout<<tg.descript<<endl;
cout<<tg.id<<endl;
cout<<tg.size<<endl;
cout<<tg.cont<<endl;
cout<<"===========\n";
}
}
// Make one suffix array from one block.
void make_block_ref(vector<Genome> &partgenomes, string &S,
vector<GenomeClustInfo> &totalgenomes,
vector<long> &descr,
vector<long> &startpos)
{
long pos = 0;
Genome tg;
long s=partgenomes.size();
S="";
startpos.push_back(0);
for (long i=0;i<s;i++){
tg=partgenomes[i];
if (!totalgenomes[tg.id].rep){
continue;
}
S += tg.cont;
S += '`';
pos = pos+tg.size+1;
startpos.push_back(pos);
descr.push_back(tg.id);
}
startpos.pop_back();
int k = S.length();
S = S.substr(0,k-1);
cerr<<"\n===="<<endl;
cerr<<"S "<<S.length()<<endl;
cerr<<"startpos "<<startpos.size()<<endl;
cerr<<"descr "<<descr.size()<<endl;
cerr<<"====\n"<<endl;
}
// Load total genomes one time.
void load_total_genomes(string filename,
vector<GenomeClustInfo> &totalgenomes)
{
long length, maxlen, totallen, minlen;
length=maxlen=totallen=0;
minlen=MAX_GENOME;
int id, loadnum; // Genome id from previous.
id=loadnum=0;
string meta, line;
GenomeClustInfo tg;
// Everything starts at zero.
ifstream data(filename.c_str());
if(!data.is_open()) {
cerr << "unable to open " << filename << endl;
exit(1);
}
while(!data.eof()) {
getline(data, line); // Load one line at a time.
if(line.length() == 0) continue;
long start = 0, end = line.length() - 1;
if(line[0] == '>') { // Meta tag line and start of a new sequence.
if(length > 0) { // Save previous sequence and meta data.
tg.descript=meta;
tg.id=id;
//tg.pid=id;
tg.rep=true;
tg.size=length;
totallen+=length;
totalgenomes.push_back(tg);
if (length>maxlen){ maxlen=length; }
if (length<minlen){ minlen=length; }
id++;
loadnum++;
}
start = 1; meta = ""; length = 0; // Reset parser state.
}
trim(line, start, end);
if(line[0] == '>') { // Collect meta data.
for(long i = start; i <= end; i++) {
if(line[i] == ' ') break;
meta += line[i];
}
}else { // Collect sequence data.
length += end - start + 1;
}
}
if(length > 0) { // Last one.
tg.descript=meta;
tg.id=id;
tg.rep=true;
tg.size=length;
totalgenomes.push_back(tg);
totallen+=length;
if (length>maxlen){ maxlen=length; }
if (length<minlen){ minlen=length; }
loadnum++;
id++;
}
cerr<<"=====================\n\n";
cerr<<"Genomes: "<<loadnum<<endl;
cerr<<"Maximum Length: "<<maxlen<<endl;
cerr<<"Minimum Length: "<<minlen<<endl;
cerr<<"Average Length: "<<totallen/loadnum<<endl;
cerr<<"\n";
cerr<<"=====================\n\n";
}
| 23.298831 | 77 | 0.552379 | [
"vector"
] |
33ccfb270fab32cf3c94db76dc6d65eb564caf2f | 6,746 | cpp | C++ | adapters-stk/test/stk_interface_test/tSquareTriMeshFactory.cpp | hillyuan/Tianxin | 57c7a5ed2466dda99471dec41cd85878335774d7 | [
"BSD-3-Clause"
] | 1 | 2022-03-22T03:49:50.000Z | 2022-03-22T03:49:50.000Z | adapters-stk/test/stk_interface_test/tSquareTriMeshFactory.cpp | hillyuan/Tianxin | 57c7a5ed2466dda99471dec41cd85878335774d7 | [
"BSD-3-Clause"
] | null | null | null | adapters-stk/test/stk_interface_test/tSquareTriMeshFactory.cpp | hillyuan/Tianxin | 57c7a5ed2466dda99471dec41cd85878335774d7 | [
"BSD-3-Clause"
] | null | null | null | // @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and
// Eric C. Cyr (eccyr@sandia.gov)
// ***********************************************************************
// @HEADER
#include <Teuchos_ConfigDefs.hpp>
#include <Teuchos_UnitTestHarness.hpp>
#include "Teuchos_DefaultComm.hpp"
#include "Teuchos_GlobalMPISession.hpp"
#include "Teuchos_ParameterList.hpp"
#include "PanzerAdaptersSTK_config.hpp"
#include "Panzer_STK_Interface.hpp"
#include "Panzer_STK_SquareTriMeshFactory.hpp"
#include "Shards_BasicTopologies.hpp"
#include "stk_mesh/base/GetEntities.hpp"
#include "stk_mesh/base/Selector.hpp"
#include "Ioss_DatabaseIO.h"
#include "Ioss_IOFactory.h"
#include "Ioss_Region.h"
#include "Ioss_EdgeBlock.h"
namespace panzer_stk {
void edge_block_test_helper(Teuchos::FancyOStream &out,
bool &success,
Teuchos::RCP<Teuchos::ParameterList> pl,
std::string exodus_filename,
uint32_t expected_edge_block_count)
{
SquareTriMeshFactory factory;
factory.setParameterList(pl);
Teuchos::RCP<STK_Interface> mesh = factory.buildMesh(MPI_COMM_WORLD);
TEST_ASSERT(mesh!=Teuchos::null);
if(mesh->isWritable())
mesh->writeToExodus(exodus_filename.c_str());
{
Ioss::DatabaseIO *db_io = Ioss::IOFactory::create("exodus",
exodus_filename.c_str(),
Ioss::READ_MODEL);
TEST_ASSERT(db_io);
Ioss::Region region(db_io);
TEST_ASSERT(db_io->ok() == true);
auto all_edge_blocks = region.get_edge_blocks();
TEST_ASSERT(all_edge_blocks.size() == expected_edge_block_count);
if (expected_edge_block_count == 1) {
std::vector<stk::mesh::Entity> edges;
mesh->getMyEdges(edges);
TEST_ASSERT(all_edge_blocks[0]->entity_count() == (int64_t)edges.size());
}
}
}
TEUCHOS_UNIT_TEST(tSquareTriMeshFactory, defaults)
{
using Teuchos::RCP;
using Teuchos::rcp;
using Teuchos::rcpFromRef;
SquareTriMeshFactory factory;
RCP<STK_Interface> mesh = factory.buildMesh(MPI_COMM_WORLD);
if(mesh->isWritable())
mesh->writeToExodus("square-tri.exo");
// minimal requirements
TEST_ASSERT(mesh!=Teuchos::null);
TEST_ASSERT(not mesh->isModifiable());
TEST_EQUALITY(mesh->getNumElementBlocks(),1);
TEST_EQUALITY(mesh->getNumSidesets(),4);
TEST_EQUALITY(mesh->getEntityCounts(mesh->getElementRank()),2*25);
TEST_EQUALITY(mesh->getEntityCounts(mesh->getSideRank()),25+60);
TEST_EQUALITY(mesh->getEntityCounts(mesh->getNodeRank()),36);
int numprocs = stk::parallel_machine_size(MPI_COMM_WORLD);
int rank = stk::parallel_machine_rank(MPI_COMM_WORLD);
int mpi_numprocs = -1;
MPI_Comm_size(MPI_COMM_WORLD, &mpi_numprocs);
int mpi_rank = -1;
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
TEST_EQUALITY(numprocs,mpi_numprocs);
TEST_EQUALITY(rank,mpi_rank);
// check for nodeset
std::vector<std::string> nodesets;
mesh->getNodesetNames(nodesets);
TEST_EQUALITY(nodesets.size(),5);
TEST_EQUALITY(nodesets[2],"origin");
}
TEUCHOS_UNIT_TEST(tSquareTriMeshFactory, default_edge_face_blocks)
{
using Teuchos::RCP;
int xe = 2, ye = 2;
int bx = 1, by = 1;
RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList);
pl->set("X Blocks",bx);
pl->set("Y Blocks",by);
pl->set("X Elements",xe);
pl->set("Y Elements",ye);
std::size_t expected_edge_block_count = 0;
edge_block_test_helper(out, success, pl,
"SquareTri_default_edge_blocks.exo",
expected_edge_block_count);
}
TEUCHOS_UNIT_TEST(tSquareTriMeshFactory, create_edge_blocks_pl)
{
using Teuchos::RCP;
int xe = 2, ye = 2;
int bx = 1, by = 1;
RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList);
pl->set("X Blocks",bx);
pl->set("Y Blocks",by);
pl->set("X Elements",xe);
pl->set("Y Elements",ye);
pl->set("Create Edge Blocks",true);
std::size_t expected_edge_block_count = 1;
edge_block_test_helper(out, success, pl,
"SquareTri_create_edge_blocks_pl.exo",
expected_edge_block_count);
}
TEUCHOS_UNIT_TEST(tSquareTriMeshFactory, multiblock_create_edge_blocks_pl)
{
using Teuchos::RCP;
int xe = 2, ye = 2;
int bx = 2, by = 1;
RCP<Teuchos::ParameterList> pl = rcp(new Teuchos::ParameterList);
pl->set("X Blocks",bx);
pl->set("Y Blocks",by);
pl->set("X Elements",xe);
pl->set("Y Elements",ye);
pl->set("Create Edge Blocks",true);
std::size_t expected_edge_block_count = 1;
edge_block_test_helper(out, success, pl,
"SquareTri_create_edge_blocks_pl.exo",
expected_edge_block_count);
}
}
| 33.562189 | 79 | 0.677438 | [
"mesh",
"vector"
] |
33d24b5b832fe9011591606860e0f50361367790 | 6,042 | cpp | C++ | paddle/legacy/gserver/gradientmachines/ParallelNeuralNetwork.cpp | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 9 | 2017-12-04T02:58:01.000Z | 2020-12-03T14:46:30.000Z | paddle/legacy/gserver/gradientmachines/ParallelNeuralNetwork.cpp | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 7 | 2017-12-05T20:29:08.000Z | 2018-10-15T08:57:40.000Z | paddle/legacy/gserver/gradientmachines/ParallelNeuralNetwork.cpp | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 6 | 2018-03-19T22:38:46.000Z | 2019-11-01T22:28:27.000Z | /* Copyright (c) 2016 PaddlePaddle Authors. 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 "paddle/legacy/utils/Stat.h"
#include "paddle/legacy/utils/Util.h"
#include "ParallelNeuralNetwork.h"
#include <pthread.h>
#include <sched.h>
namespace paddle {
void ParallelNeuralNetwork::init(
const ModelConfig& config,
ParamInitCallback callback,
const std::vector<ParameterType>& parameterTypes,
bool useGpu) {
NeuralNetwork::init(config, callback, parameterTypes, useGpu);
if (config.type() == "recurrent_nn") {
LOG(FATAL)
<< "You can not add `--parallel_nn=true` on the command line, "
<< "parallel_nn training mode does not support the recurrent_nn model.";
}
useGpu_ = useGpu;
numDevices_ = 0;
if (useGpu_) {
numDevices_ = hl_get_device_count();
}
for (auto& layer : layers_) {
int deviceId = layer->getDeviceId();
CHECK_LT(deviceId, numDevices_);
addComputeThread(deviceId);
}
}
void ParallelNeuralNetwork::addComputeThread(int deviceId) {
for (auto& thread : threads_) {
if (thread->getDeviceId() == deviceId) {
return;
}
}
threads_.emplace_back(new ParallelThread(
threads_.size(), deviceId, deviceId >= 0 ? useGpu_ : false));
}
void ParallelNeuralNetwork::waitAllThread() {
for (auto& thread : threads_) {
thread->jobEnqueue(NULL, TASK_END_LAYER);
}
for (size_t i = 0; i < threads_.size(); i++) {
threads_[i]->queue_.waitEmpty();
}
}
void ParallelNeuralNetwork::dispatchByDeviceId(int deviceId,
LayerPtr layer,
TaskType task) {
for (auto& thread : threads_) {
if (thread->getDeviceId() == deviceId) {
thread->jobEnqueue(layer, task);
return;
}
}
LOG(FATAL) << "No specific device thread ";
}
void ParallelNeuralNetwork::forward(const std::vector<Argument>& inArgs,
std::vector<Argument>* outArgs,
PassType passType) {
for (auto& thread : threads_) {
thread->setForwardPassType(passType);
}
CHECK_EQ(inArgs.size(), dataLayers_.size());
outArgs->resize(outputLayers_.size());
for (size_t i = 0; i != dataLayers_.size(); ++i) {
const_cast<Argument&>(inArgs[i]).deviceId = -1;
dataLayers_[i]->setData(inArgs[i]);
}
for (auto& layer : layers_) {
dispatchByDeviceId(layer->getDeviceId(), layer, TASK_FORWARD);
}
{
REGISTER_TIMER("forwardTime");
waitAllThread();
}
outArgs->clear();
outArgs->reserve(outputLayers_.size());
for (auto& layer : outputLayers_) {
outArgs->push_back(layer->getOutput());
}
}
void ParallelNeuralNetwork::backward(const UpdateCallback& callback) {
for (auto& thread : threads_) {
thread->setBackwardCallback(callback);
}
FOR_EACH_R(layer, layers_) {
dispatchByDeviceId((*layer)->getDeviceId(), *layer, TASK_BACKWARD);
}
{
REGISTER_TIMER("backwardTime");
waitAllThread();
}
}
void ParallelNeuralNetwork::forwardBackward(const std::vector<Argument>& inArgs,
std::vector<Argument>* outArgs,
PassType passType,
const UpdateCallback& callback) {
forward(inArgs, outArgs, passType);
backward(callback);
}
void ParallelNeuralNetwork::start() {
for (auto& thread : threads_) {
thread->start();
}
}
ParallelThread::ParallelThread(int threadId, int deviceId, bool useGpu)
: threadId_(threadId), deviceId_(deviceId), useGpu_(useGpu) {}
ParallelThread::~ParallelThread() { stop(); }
void ParallelThread::stop() {
if (computeThread_) {
jobEnqueue(NULL, TASK_THREAD_FINISH);
computeThread_->join();
computeThread_.reset(nullptr);
}
}
void ParallelThread::computeThread() {
LOG(INFO) << "gradComputeThread " << threadId_;
if (useGpu_) {
hl_init(deviceId_);
}
while (true) {
struct Job job_work = queue_.dequeue();
if (job_work.task_ == TASK_END_LAYER) {
continue;
} else if (job_work.task_ == TASK_THREAD_FINISH) {
break;
}
if (TASK_FORWARD == job_work.task_) {
{
REGISTER_TIMER_INFO("waitInputValue",
job_work.layer_->getName().c_str());
job_work.layer_->waitInputValue();
}
{
REGISTER_TIMER_INFO("threadForwardTimer",
job_work.layer_->getName().c_str());
job_work.layer_->forward(passType_);
}
{
REGISTER_TIMER_INFO("copyOutputToOtherDevice",
job_work.layer_->getName().c_str());
job_work.layer_->copyOutputToOtherDevice();
}
} else {
{
REGISTER_TIMER_INFO("waitAndMergeOutputGrad",
job_work.layer_->getName().c_str());
job_work.layer_->waitAndMergeOutputGrad();
}
{
REGISTER_TIMER_INFO("threadBackwardTimer",
job_work.layer_->getName().c_str());
job_work.layer_->backward(backwardCallback_);
}
hl_stream_synchronize(HPPL_STREAM_DEFAULT);
job_work.layer_->markAllInputGrad();
}
}
hl_fini();
}
void ParallelThread::start() {
computeThread_.reset(new std::thread([this]() { computeThread(); }));
}
void ParallelThread::jobEnqueue(LayerPtr layer, TaskType task) {
struct Job job_work;
job_work.layer_ = layer;
job_work.task_ = task;
queue_.enqueue(job_work);
}
} // namespace paddle
| 28.102326 | 80 | 0.634062 | [
"vector",
"model"
] |
33d5242b708bf82bfc6bd79b5109b520cee3b56d | 25,852 | cc | C++ | net/quic/crypto/quic_crypto_client_config.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-01-16T03:57:39.000Z | 2019-01-16T03:57:39.000Z | net/quic/crypto/quic_crypto_client_config.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | net/quic/crypto/quic_crypto_client_config.cc | aranajhonny/chromium | caf5bcb822f79b8997720e589334266551a50a13 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "net/quic/crypto/quic_crypto_client_config.h"
#include "base/metrics/sparse_histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "net/quic/crypto/cert_compressor.h"
#include "net/quic/crypto/chacha20_poly1305_encrypter.h"
#include "net/quic/crypto/channel_id.h"
#include "net/quic/crypto/common_cert_set.h"
#include "net/quic/crypto/crypto_framer.h"
#include "net/quic/crypto/crypto_utils.h"
#include "net/quic/crypto/curve25519_key_exchange.h"
#include "net/quic/crypto/key_exchange.h"
#include "net/quic/crypto/p256_key_exchange.h"
#include "net/quic/crypto/proof_verifier.h"
#include "net/quic/crypto/quic_encrypter.h"
#include "net/quic/quic_utils.h"
using base::StringPiece;
using std::find;
using std::make_pair;
using std::map;
using std::string;
using std::vector;
namespace net {
QuicCryptoClientConfig::QuicCryptoClientConfig()
: disable_ecdsa_(false) {}
QuicCryptoClientConfig::~QuicCryptoClientConfig() {
STLDeleteValues(&cached_states_);
}
QuicCryptoClientConfig::CachedState::CachedState()
: server_config_valid_(false),
generation_counter_(0) {}
QuicCryptoClientConfig::CachedState::~CachedState() {}
bool QuicCryptoClientConfig::CachedState::IsComplete(QuicWallTime now) const {
if (server_config_.empty() || !server_config_valid_) {
return false;
}
const CryptoHandshakeMessage* scfg = GetServerConfig();
if (!scfg) {
// Should be impossible short of cache corruption.
DCHECK(false);
return false;
}
uint64 expiry_seconds;
if (scfg->GetUint64(kEXPY, &expiry_seconds) != QUIC_NO_ERROR ||
now.ToUNIXSeconds() >= expiry_seconds) {
return false;
}
return true;
}
bool QuicCryptoClientConfig::CachedState::IsEmpty() const {
return server_config_.empty();
}
const CryptoHandshakeMessage*
QuicCryptoClientConfig::CachedState::GetServerConfig() const {
if (server_config_.empty()) {
return NULL;
}
if (!scfg_.get()) {
scfg_.reset(CryptoFramer::ParseMessage(server_config_));
DCHECK(scfg_.get());
}
return scfg_.get();
}
QuicErrorCode QuicCryptoClientConfig::CachedState::SetServerConfig(
StringPiece server_config, QuicWallTime now, string* error_details) {
const bool matches_existing = server_config == server_config_;
// Even if the new server config matches the existing one, we still wish to
// reject it if it has expired.
scoped_ptr<CryptoHandshakeMessage> new_scfg_storage;
const CryptoHandshakeMessage* new_scfg;
if (!matches_existing) {
new_scfg_storage.reset(CryptoFramer::ParseMessage(server_config));
new_scfg = new_scfg_storage.get();
} else {
new_scfg = GetServerConfig();
}
if (!new_scfg) {
*error_details = "SCFG invalid";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
uint64 expiry_seconds;
if (new_scfg->GetUint64(kEXPY, &expiry_seconds) != QUIC_NO_ERROR) {
*error_details = "SCFG missing EXPY";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
if (now.ToUNIXSeconds() >= expiry_seconds) {
*error_details = "SCFG has expired";
return QUIC_CRYPTO_SERVER_CONFIG_EXPIRED;
}
if (!matches_existing) {
server_config_ = server_config.as_string();
SetProofInvalid();
scfg_.reset(new_scfg_storage.release());
}
return QUIC_NO_ERROR;
}
void QuicCryptoClientConfig::CachedState::InvalidateServerConfig() {
server_config_.clear();
scfg_.reset();
SetProofInvalid();
}
void QuicCryptoClientConfig::CachedState::SetProof(const vector<string>& certs,
StringPiece signature) {
bool has_changed =
signature != server_config_sig_ || certs_.size() != certs.size();
if (!has_changed) {
for (size_t i = 0; i < certs_.size(); i++) {
if (certs_[i] != certs[i]) {
has_changed = true;
break;
}
}
}
if (!has_changed) {
return;
}
// If the proof has changed then it needs to be revalidated.
SetProofInvalid();
certs_ = certs;
server_config_sig_ = signature.as_string();
}
void QuicCryptoClientConfig::CachedState::Clear() {
server_config_.clear();
source_address_token_.clear();
certs_.clear();
server_config_sig_.clear();
server_config_valid_ = false;
proof_verify_details_.reset();
scfg_.reset();
++generation_counter_;
}
void QuicCryptoClientConfig::CachedState::ClearProof() {
SetProofInvalid();
certs_.clear();
server_config_sig_.clear();
}
void QuicCryptoClientConfig::CachedState::SetProofValid() {
server_config_valid_ = true;
}
void QuicCryptoClientConfig::CachedState::SetProofInvalid() {
server_config_valid_ = false;
++generation_counter_;
}
bool QuicCryptoClientConfig::CachedState::Initialize(
StringPiece server_config,
StringPiece source_address_token,
const vector<string>& certs,
StringPiece signature,
QuicWallTime now) {
DCHECK(server_config_.empty());
if (server_config.empty()) {
return false;
}
string error_details;
QuicErrorCode error = SetServerConfig(server_config, now,
&error_details);
if (error != QUIC_NO_ERROR) {
DVLOG(1) << "SetServerConfig failed with " << error_details;
return false;
}
signature.CopyToString(&server_config_sig_);
source_address_token.CopyToString(&source_address_token_);
certs_ = certs;
return true;
}
const string& QuicCryptoClientConfig::CachedState::server_config() const {
return server_config_;
}
const string&
QuicCryptoClientConfig::CachedState::source_address_token() const {
return source_address_token_;
}
const vector<string>& QuicCryptoClientConfig::CachedState::certs() const {
return certs_;
}
const string& QuicCryptoClientConfig::CachedState::signature() const {
return server_config_sig_;
}
bool QuicCryptoClientConfig::CachedState::proof_valid() const {
return server_config_valid_;
}
uint64 QuicCryptoClientConfig::CachedState::generation_counter() const {
return generation_counter_;
}
const ProofVerifyDetails*
QuicCryptoClientConfig::CachedState::proof_verify_details() const {
return proof_verify_details_.get();
}
void QuicCryptoClientConfig::CachedState::set_source_address_token(
StringPiece token) {
source_address_token_ = token.as_string();
}
void QuicCryptoClientConfig::CachedState::SetProofVerifyDetails(
ProofVerifyDetails* details) {
proof_verify_details_.reset(details);
}
void QuicCryptoClientConfig::CachedState::InitializeFrom(
const QuicCryptoClientConfig::CachedState& other) {
DCHECK(server_config_.empty());
DCHECK(!server_config_valid_);
server_config_ = other.server_config_;
source_address_token_ = other.source_address_token_;
certs_ = other.certs_;
server_config_sig_ = other.server_config_sig_;
server_config_valid_ = other.server_config_valid_;
++generation_counter_;
}
void QuicCryptoClientConfig::SetDefaults() {
// Key exchange methods.
kexs.resize(2);
kexs[0] = kC255;
kexs[1] = kP256;
// Authenticated encryption algorithms. Prefer ChaCha20 by default.
aead.clear();
if (ChaCha20Poly1305Encrypter::IsSupported()) {
aead.push_back(kCC12);
}
aead.push_back(kAESG);
disable_ecdsa_ = false;
}
QuicCryptoClientConfig::CachedState* QuicCryptoClientConfig::LookupOrCreate(
const QuicServerId& server_id) {
CachedStateMap::const_iterator it = cached_states_.find(server_id);
if (it != cached_states_.end()) {
return it->second;
}
CachedState* cached = new CachedState;
cached_states_.insert(make_pair(server_id, cached));
PopulateFromCanonicalConfig(server_id, cached);
return cached;
}
void QuicCryptoClientConfig::ClearCachedStates() {
for (CachedStateMap::const_iterator it = cached_states_.begin();
it != cached_states_.end(); ++it) {
it->second->Clear();
}
}
void QuicCryptoClientConfig::FillInchoateClientHello(
const QuicServerId& server_id,
const QuicVersion preferred_version,
const CachedState* cached,
QuicCryptoNegotiatedParameters* out_params,
CryptoHandshakeMessage* out) const {
out->set_tag(kCHLO);
out->set_minimum_size(kClientHelloMinimumSize);
// Server name indication. We only send SNI if it's a valid domain name, as
// per the spec.
if (CryptoUtils::IsValidSNI(server_id.host())) {
out->SetStringPiece(kSNI, server_id.host());
}
out->SetValue(kVER, QuicVersionToQuicTag(preferred_version));
if (!user_agent_id_.empty()) {
out->SetStringPiece(kUAID, user_agent_id_);
}
if (!cached->source_address_token().empty()) {
out->SetStringPiece(kSourceAddressTokenTag, cached->source_address_token());
}
if (server_id.is_https()) {
if (disable_ecdsa_) {
out->SetTaglist(kPDMD, kX59R, 0);
} else {
out->SetTaglist(kPDMD, kX509, 0);
}
}
if (common_cert_sets) {
out->SetStringPiece(kCCS, common_cert_sets->GetCommonHashes());
}
const vector<string>& certs = cached->certs();
// We save |certs| in the QuicCryptoNegotiatedParameters so that, if the
// client config is being used for multiple connections, another connection
// doesn't update the cached certificates and cause us to be unable to
// process the server's compressed certificate chain.
out_params->cached_certs = certs;
if (!certs.empty()) {
vector<uint64> hashes;
hashes.reserve(certs.size());
for (vector<string>::const_iterator i = certs.begin();
i != certs.end(); ++i) {
hashes.push_back(QuicUtils::FNV1a_64_Hash(i->data(), i->size()));
}
out->SetVector(kCCRT, hashes);
}
}
QuicErrorCode QuicCryptoClientConfig::FillClientHello(
const QuicServerId& server_id,
QuicConnectionId connection_id,
const QuicVersion preferred_version,
const CachedState* cached,
QuicWallTime now,
QuicRandom* rand,
const ChannelIDKey* channel_id_key,
QuicCryptoNegotiatedParameters* out_params,
CryptoHandshakeMessage* out,
string* error_details) const {
DCHECK(error_details != NULL);
FillInchoateClientHello(server_id, preferred_version, cached,
out_params, out);
const CryptoHandshakeMessage* scfg = cached->GetServerConfig();
if (!scfg) {
// This should never happen as our caller should have checked
// cached->IsComplete() before calling this function.
*error_details = "Handshake not ready";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
StringPiece scid;
if (!scfg->GetStringPiece(kSCID, &scid)) {
*error_details = "SCFG missing SCID";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
out->SetStringPiece(kSCID, scid);
const QuicTag* their_aeads;
const QuicTag* their_key_exchanges;
size_t num_their_aeads, num_their_key_exchanges;
if (scfg->GetTaglist(kAEAD, &their_aeads,
&num_their_aeads) != QUIC_NO_ERROR ||
scfg->GetTaglist(kKEXS, &their_key_exchanges,
&num_their_key_exchanges) != QUIC_NO_ERROR) {
*error_details = "Missing AEAD or KEXS";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
// AEAD: the work loads on the client and server are symmetric. Since the
// client is more likely to be CPU-constrained, break the tie by favoring
// the client's preference.
// Key exchange: the client does more work than the server, so favor the
// client's preference.
size_t key_exchange_index;
if (!QuicUtils::FindMutualTag(
aead, their_aeads, num_their_aeads, QuicUtils::LOCAL_PRIORITY,
&out_params->aead, NULL) ||
!QuicUtils::FindMutualTag(
kexs, their_key_exchanges, num_their_key_exchanges,
QuicUtils::LOCAL_PRIORITY, &out_params->key_exchange,
&key_exchange_index)) {
*error_details = "Unsupported AEAD or KEXS";
return QUIC_CRYPTO_NO_SUPPORT;
}
out->SetTaglist(kAEAD, out_params->aead, 0);
out->SetTaglist(kKEXS, out_params->key_exchange, 0);
StringPiece public_value;
if (scfg->GetNthValue24(kPUBS, key_exchange_index, &public_value) !=
QUIC_NO_ERROR) {
*error_details = "Missing public value";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
StringPiece orbit;
if (!scfg->GetStringPiece(kORBT, &orbit) || orbit.size() != kOrbitSize) {
*error_details = "SCFG missing OBIT";
return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND;
}
CryptoUtils::GenerateNonce(now, rand, orbit, &out_params->client_nonce);
out->SetStringPiece(kNONC, out_params->client_nonce);
if (!out_params->server_nonce.empty()) {
out->SetStringPiece(kServerNonceTag, out_params->server_nonce);
}
switch (out_params->key_exchange) {
case kC255:
out_params->client_key_exchange.reset(Curve25519KeyExchange::New(
Curve25519KeyExchange::NewPrivateKey(rand)));
break;
case kP256:
out_params->client_key_exchange.reset(P256KeyExchange::New(
P256KeyExchange::NewPrivateKey()));
break;
default:
DCHECK(false);
*error_details = "Configured to support an unknown key exchange";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
if (!out_params->client_key_exchange->CalculateSharedKey(
public_value, &out_params->initial_premaster_secret)) {
*error_details = "Key exchange failure";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
out->SetStringPiece(kPUBS, out_params->client_key_exchange->public_value());
if (channel_id_key) {
// In order to calculate the encryption key for the CETV block we need to
// serialise the client hello as it currently is (i.e. without the CETV
// block). For this, the client hello is serialized without padding.
const size_t orig_min_size = out->minimum_size();
out->set_minimum_size(0);
CryptoHandshakeMessage cetv;
cetv.set_tag(kCETV);
string hkdf_input;
const QuicData& client_hello_serialized = out->GetSerialized();
hkdf_input.append(QuicCryptoConfig::kCETVLabel,
strlen(QuicCryptoConfig::kCETVLabel) + 1);
hkdf_input.append(reinterpret_cast<char*>(&connection_id),
sizeof(connection_id));
hkdf_input.append(client_hello_serialized.data(),
client_hello_serialized.length());
hkdf_input.append(cached->server_config());
string key = channel_id_key->SerializeKey();
string signature;
if (!channel_id_key->Sign(hkdf_input, &signature)) {
*error_details = "Channel ID signature failed";
return QUIC_INVALID_CHANNEL_ID_SIGNATURE;
}
cetv.SetStringPiece(kCIDK, key);
cetv.SetStringPiece(kCIDS, signature);
CrypterPair crypters;
if (!CryptoUtils::DeriveKeys(out_params->initial_premaster_secret,
out_params->aead, out_params->client_nonce,
out_params->server_nonce, hkdf_input,
CryptoUtils::CLIENT, &crypters)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
const QuicData& cetv_plaintext = cetv.GetSerialized();
scoped_ptr<QuicData> cetv_ciphertext(crypters.encrypter->EncryptPacket(
0 /* sequence number */,
StringPiece() /* associated data */,
cetv_plaintext.AsStringPiece()));
if (!cetv_ciphertext.get()) {
*error_details = "Packet encryption failed";
return QUIC_ENCRYPTION_FAILURE;
}
out->SetStringPiece(kCETV, cetv_ciphertext->AsStringPiece());
out->MarkDirty();
out->set_minimum_size(orig_min_size);
}
// Derive the symmetric keys and set up the encrypters and decrypters.
// Set the following members of out_params:
// out_params->hkdf_input_suffix
// out_params->initial_crypters
out_params->hkdf_input_suffix.clear();
out_params->hkdf_input_suffix.append(reinterpret_cast<char*>(&connection_id),
sizeof(connection_id));
const QuicData& client_hello_serialized = out->GetSerialized();
out_params->hkdf_input_suffix.append(client_hello_serialized.data(),
client_hello_serialized.length());
out_params->hkdf_input_suffix.append(cached->server_config());
string hkdf_input;
const size_t label_len = strlen(QuicCryptoConfig::kInitialLabel) + 1;
hkdf_input.reserve(label_len + out_params->hkdf_input_suffix.size());
hkdf_input.append(QuicCryptoConfig::kInitialLabel, label_len);
hkdf_input.append(out_params->hkdf_input_suffix);
if (!CryptoUtils::DeriveKeys(
out_params->initial_premaster_secret, out_params->aead,
out_params->client_nonce, out_params->server_nonce, hkdf_input,
CryptoUtils::CLIENT, &out_params->initial_crypters)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::CacheNewServerConfig(
const CryptoHandshakeMessage& message,
QuicWallTime now,
const vector<string>& cached_certs,
CachedState* cached,
string* error_details) {
DCHECK(error_details != NULL);
StringPiece scfg;
if (!message.GetStringPiece(kSCFG, &scfg)) {
*error_details = "Missing SCFG";
return QUIC_CRYPTO_MESSAGE_PARAMETER_NOT_FOUND;
}
QuicErrorCode error = cached->SetServerConfig(scfg, now, error_details);
if (error != QUIC_NO_ERROR) {
return error;
}
StringPiece token;
if (message.GetStringPiece(kSourceAddressTokenTag, &token)) {
cached->set_source_address_token(token);
}
StringPiece proof, cert_bytes;
bool has_proof = message.GetStringPiece(kPROF, &proof);
bool has_cert = message.GetStringPiece(kCertificateTag, &cert_bytes);
if (has_proof && has_cert) {
vector<string> certs;
if (!CertCompressor::DecompressChain(cert_bytes, cached_certs,
common_cert_sets, &certs)) {
*error_details = "Certificate data invalid";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
cached->SetProof(certs, proof);
} else {
cached->ClearProof();
if (has_proof && !has_cert) {
*error_details = "Certificate missing";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
if (!has_proof && has_cert) {
*error_details = "Proof missing";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::ProcessRejection(
const CryptoHandshakeMessage& rej,
QuicWallTime now,
CachedState* cached,
QuicCryptoNegotiatedParameters* out_params,
string* error_details) {
DCHECK(error_details != NULL);
if (rej.tag() != kREJ) {
*error_details = "Message is not REJ";
return QUIC_CRYPTO_INTERNAL_ERROR;
}
QuicErrorCode error = CacheNewServerConfig(rej, now, out_params->cached_certs,
cached, error_details);
if (error != QUIC_NO_ERROR) {
return error;
}
StringPiece nonce;
if (rej.GetStringPiece(kServerNonceTag, &nonce)) {
out_params->server_nonce = nonce.as_string();
}
const uint32* reject_reasons;
size_t num_reject_reasons;
COMPILE_ASSERT(sizeof(QuicTag) == sizeof(uint32), header_out_of_sync);
if (rej.GetTaglist(kRREJ, &reject_reasons,
&num_reject_reasons) == QUIC_NO_ERROR) {
uint32 packed_error = 0;
for (size_t i = 0; i < num_reject_reasons; ++i) {
// HANDSHAKE_OK is 0 and don't report that as error.
if (reject_reasons[i] == HANDSHAKE_OK || reject_reasons[i] >= 32) {
continue;
}
HandshakeFailureReason reason =
static_cast<HandshakeFailureReason>(reject_reasons[i]);
packed_error |= 1 << (reason - 1);
}
DVLOG(1) << "Reasons for rejection: " << packed_error;
UMA_HISTOGRAM_SPARSE_SLOWLY("Net.QuicClientHelloRejectReasons",
packed_error);
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::ProcessServerHello(
const CryptoHandshakeMessage& server_hello,
QuicConnectionId connection_id,
const QuicVersionVector& negotiated_versions,
CachedState* cached,
QuicCryptoNegotiatedParameters* out_params,
string* error_details) {
DCHECK(error_details != NULL);
if (server_hello.tag() != kSHLO) {
*error_details = "Bad tag";
return QUIC_INVALID_CRYPTO_MESSAGE_TYPE;
}
const QuicTag* supported_version_tags;
size_t num_supported_versions;
if (server_hello.GetTaglist(kVER, &supported_version_tags,
&num_supported_versions) != QUIC_NO_ERROR) {
*error_details = "server hello missing version list";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
if (!negotiated_versions.empty()) {
bool mismatch = num_supported_versions != negotiated_versions.size();
for (size_t i = 0; i < num_supported_versions && !mismatch; ++i) {
mismatch = QuicTagToQuicVersion(supported_version_tags[i]) !=
negotiated_versions[i];
}
// The server sent a list of supported versions, and the connection
// reports that there was a version negotiation during the handshake.
// Ensure that these two lists are identical.
if (mismatch) {
*error_details = "Downgrade attack detected";
return QUIC_VERSION_NEGOTIATION_MISMATCH;
}
}
// Learn about updated source address tokens.
StringPiece token;
if (server_hello.GetStringPiece(kSourceAddressTokenTag, &token)) {
cached->set_source_address_token(token);
}
// TODO(agl):
// learn about updated SCFGs.
StringPiece public_value;
if (!server_hello.GetStringPiece(kPUBS, &public_value)) {
*error_details = "server hello missing forward secure public value";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
if (!out_params->client_key_exchange->CalculateSharedKey(
public_value, &out_params->forward_secure_premaster_secret)) {
*error_details = "Key exchange failure";
return QUIC_INVALID_CRYPTO_MESSAGE_PARAMETER;
}
string hkdf_input;
const size_t label_len = strlen(QuicCryptoConfig::kForwardSecureLabel) + 1;
hkdf_input.reserve(label_len + out_params->hkdf_input_suffix.size());
hkdf_input.append(QuicCryptoConfig::kForwardSecureLabel, label_len);
hkdf_input.append(out_params->hkdf_input_suffix);
if (!CryptoUtils::DeriveKeys(
out_params->forward_secure_premaster_secret, out_params->aead,
out_params->client_nonce, out_params->server_nonce, hkdf_input,
CryptoUtils::CLIENT, &out_params->forward_secure_crypters)) {
*error_details = "Symmetric key setup failed";
return QUIC_CRYPTO_SYMMETRIC_KEY_SETUP_FAILED;
}
return QUIC_NO_ERROR;
}
QuicErrorCode QuicCryptoClientConfig::ProcessServerConfigUpdate(
const CryptoHandshakeMessage& server_config_update,
QuicWallTime now,
CachedState* cached,
QuicCryptoNegotiatedParameters* out_params,
string* error_details) {
DCHECK(error_details != NULL);
if (server_config_update.tag() != kSCUP) {
*error_details = "ServerConfigUpdate must have kSCUP tag.";
return QUIC_INVALID_CRYPTO_MESSAGE_TYPE;
}
return CacheNewServerConfig(server_config_update, now,
out_params->cached_certs, cached, error_details);
}
ProofVerifier* QuicCryptoClientConfig::proof_verifier() const {
return proof_verifier_.get();
}
void QuicCryptoClientConfig::SetProofVerifier(ProofVerifier* verifier) {
proof_verifier_.reset(verifier);
}
ChannelIDSource* QuicCryptoClientConfig::channel_id_source() const {
return channel_id_source_.get();
}
void QuicCryptoClientConfig::SetChannelIDSource(ChannelIDSource* source) {
channel_id_source_.reset(source);
}
void QuicCryptoClientConfig::InitializeFrom(
const QuicServerId& server_id,
const QuicServerId& canonical_server_id,
QuicCryptoClientConfig* canonical_crypto_config) {
CachedState* canonical_cached =
canonical_crypto_config->LookupOrCreate(canonical_server_id);
if (!canonical_cached->proof_valid()) {
return;
}
CachedState* cached = LookupOrCreate(server_id);
cached->InitializeFrom(*canonical_cached);
}
void QuicCryptoClientConfig::AddCanonicalSuffix(const string& suffix) {
canoncial_suffixes_.push_back(suffix);
}
void QuicCryptoClientConfig::PreferAesGcm() {
DCHECK(!aead.empty());
if (aead.size() <= 1) {
return;
}
QuicTagVector::iterator pos = find(aead.begin(), aead.end(), kAESG);
if (pos != aead.end()) {
aead.erase(pos);
aead.insert(aead.begin(), kAESG);
}
}
void QuicCryptoClientConfig::DisableEcdsa() {
disable_ecdsa_ = true;
}
void QuicCryptoClientConfig::PopulateFromCanonicalConfig(
const QuicServerId& server_id,
CachedState* server_state) {
DCHECK(server_state->IsEmpty());
size_t i = 0;
for (; i < canoncial_suffixes_.size(); ++i) {
if (EndsWith(server_id.host(), canoncial_suffixes_[i], false)) {
break;
}
}
if (i == canoncial_suffixes_.size())
return;
QuicServerId suffix_server_id(canoncial_suffixes_[i], server_id.port(),
server_id.is_https(),
server_id.privacy_mode());
if (!ContainsKey(canonical_server_map_, suffix_server_id)) {
// This is the first host we've seen which matches the suffix, so make it
// canonical.
canonical_server_map_[suffix_server_id] = server_id;
return;
}
const QuicServerId& canonical_server_id =
canonical_server_map_[suffix_server_id];
CachedState* canonical_state = cached_states_[canonical_server_id];
if (!canonical_state->proof_valid()) {
return;
}
// Update canonical version to point at the "most recent" entry.
canonical_server_map_[suffix_server_id] = server_id;
server_state->InitializeFrom(*canonical_state);
}
} // namespace net
| 31.955501 | 80 | 0.714954 | [
"vector"
] |
33d66db6578a023f065b339aa44a31e6db04ca79 | 6,956 | hpp | C++ | examples/capacitatedopenvehiclerouting.hpp | fontanf/columngenerationsolver | f0261d0f621e2c342aeca86f404d5f92fff3fc7a | [
"MIT"
] | 8 | 2021-02-07T21:36:04.000Z | 2022-03-23T15:50:55.000Z | examples/capacitatedopenvehiclerouting.hpp | fontanf/columngenerationsolver | f0261d0f621e2c342aeca86f404d5f92fff3fc7a | [
"MIT"
] | null | null | null | examples/capacitatedopenvehiclerouting.hpp | fontanf/columngenerationsolver | f0261d0f621e2c342aeca86f404d5f92fff3fc7a | [
"MIT"
] | null | null | null | #pragma once
/**
* Capacitated Open Vehicle Routing Problem.
*
* Problem description:
* See https://github.com/fontanf/orproblems/blob/main/orproblems/capacitatedopenvehiclerouting.hpp
*
* The linear programming formulation of the problem based on Dantzig–Wolfe
* decomposition is written as follows:
*
* Variables:
* - yᵏ ∈ {0, 1} representing a feasible route.
* yᵏ = 1 iff the corresponding route is selected.
* dᵏ the length of route yᵏ.
* xⱼᵏ = 1 iff customer j is visited in route yᵏ.
*
* Program:
*
* min ∑ₖ dᵏ yᵏ
*
* 0 <= ∑ₖ yᵏ <= m
* (not more then m vehicles)
* Dual variable: u
* 1 <= ∑ₖ xⱼᵏ yᵏ <= 1 for all customers j
* (each customer is visited exactly once)
* Dual variables: vⱼ
*
* The pricing problem consists in finding a variable of negative reduced cost.
* The reduced cost of a variable yᵏ is given by:
* rc(yᵏ) = dᵏ - ∑ⱼ xⱼᵏ vⱼ
*
* Therefore, finding a variable of minimum reduced cost reduces to solving
* an Elementary Open Shortest Path Problems with Resource Constraints.
*
*/
#include "columngenerationsolver/commons.hpp"
#include "examples/pricingsolver/eospprc.hpp"
#include "orproblems/capacitatedopenvehiclerouting.hpp"
#include "treesearchsolver/algorithms/iterative_beam_search.hpp"
#include "treesearchsolver/algorithms/a_star.hpp"
#include "treesearchsolver/algorithms/iterative_memory_bounded_a_star.hpp"
#include "optimizationtools/utils.hpp"
namespace columngenerationsolver
{
namespace capacitatedopenvehiclerouting
{
using namespace orproblems::capacitatedopenvehiclerouting;
class PricingSolver: public columngenerationsolver::PricingSolver
{
public:
PricingSolver(const Instance& instance):
instance_(instance),
visited_customers_(instance.number_of_locations(), 0)
{ }
virtual std::vector<ColIdx> initialize_pricing(
const std::vector<Column>& columns,
const std::vector<std::pair<ColIdx, Value>>& fixed_columns);
virtual std::vector<Column> solve_pricing(
const std::vector<Value>& duals);
private:
const Instance& instance_;
std::vector<Demand> visited_customers_;
std::vector<LocationId> espp2vrp_;
};
columngenerationsolver::Parameters get_parameters(const Instance& instance)
{
LocationId n = instance.number_of_locations();
columngenerationsolver::Parameters p(n);
p.objective_sense = columngenerationsolver::ObjectiveSense::Min;
p.column_lower_bound = 0;
p.column_upper_bound = 1;
// Row bounds.
p.row_lower_bounds[0] = 0;
p.row_upper_bounds[0] = instance.number_of_vehicles();
p.row_coefficient_lower_bounds[0] = 1;
p.row_coefficient_upper_bounds[0] = 1;
for (LocationId j = 1; j < n; ++j) {
p.row_lower_bounds[j] = 1;
p.row_upper_bounds[j] = 1;
p.row_coefficient_lower_bounds[j] = 0;
p.row_coefficient_upper_bounds[j] = 1;
}
// Dummy column objective coefficient.
p.dummy_column_objective_coefficient = 3 * instance.maximum_distance();
// Pricing solver.
p.pricing_solver = std::unique_ptr<columngenerationsolver::PricingSolver>(
new PricingSolver(instance));
return p;
}
std::vector<ColIdx> PricingSolver::initialize_pricing(
const std::vector<Column>& columns,
const std::vector<std::pair<ColIdx, Value>>& fixed_columns)
{
std::fill(visited_customers_.begin(), visited_customers_.end(), 0);
for (auto p: fixed_columns) {
const Column& column = columns[p.first];
Value value = p.second;
if (value < 0.5)
continue;
for (RowIdx row_pos = 0; row_pos < (RowIdx)column.row_indices.size(); ++row_pos) {
RowIdx row_index = column.row_indices[row_pos];
Value row_coefficient = column.row_coefficients[row_pos];
if (row_index == 0)
continue;
if (row_coefficient < 0.5)
continue;
visited_customers_[row_index] = 1;
}
}
return {};
}
struct ColumnExtra
{
std::vector<LocationId> route;
};
std::vector<Column> PricingSolver::solve_pricing(
const std::vector<Value>& duals)
{
LocationId n = instance_.number_of_locations();
// Build subproblem instance.
espp2vrp_.clear();
espp2vrp_.push_back(0);
for (LocationId j = 1; j < n; ++j) {
if (visited_customers_[j] == 1)
continue;
espp2vrp_.push_back(j);
}
LocationId n_espp = espp2vrp_.size();
if (n_espp == 1)
return {};
eospprc::Instance instance_espp(n_espp);
instance_espp.set_maximum_route_length(instance_.maximum_route_length());
for (LocationId j_espp = 0; j_espp < n_espp; ++j_espp) {
LocationId j = espp2vrp_[j_espp];
instance_espp.set_location(
j_espp,
instance_.demand(j),
((j != 0)? duals[j]: 0));
for (LocationId j2_espp = 0; j2_espp < n_espp; ++j2_espp) {
if (j2_espp == j_espp)
continue;
LocationId j2 = espp2vrp_[j2_espp];
instance_espp.set_distance(j_espp, j2_espp, instance_.distance(j, j2));
}
}
// Solve subproblem instance.
eospprc::BranchingScheme branching_scheme(instance_espp);
treesearchsolver::IterativeBeamSearchOptionalParameters parameters_espp;
parameters_espp.maximum_size_of_the_solution_pool = 100;
parameters_espp.minimum_size_of_the_queue = 512;
parameters_espp.maximum_size_of_the_queue = 512;
//parameters_espp.info.set_verbose(true);
auto output_espp = treesearchsolver::iterativebeamsearch(
branching_scheme, parameters_espp);
// Retrieve column.
std::vector<Column> columns;
LocationId i = 0;
for (const std::shared_ptr<eospprc::BranchingScheme::Node>& node:
output_espp.solution_pool.solutions()) {
if (i > 2 * n_espp)
break;
std::vector<LocationId> solution; // Without the depot.
if (node->j != 0) {
for (auto node_tmp = node; node_tmp->father != nullptr; node_tmp = node_tmp->father)
solution.push_back(espp2vrp_[node_tmp->j]);
std::reverse(solution.begin(), solution.end());
}
i += solution.size();
Column column;
column.objective_coefficient = node->length;
column.row_indices.push_back(0);
column.row_coefficients.push_back(1);
for (LocationId j: solution) {
column.row_indices.push_back(j);
column.row_coefficients.push_back(1);
}
ColumnExtra extra {solution};
column.extra = std::shared_ptr<void>(new ColumnExtra(extra));
columns.push_back(column);
}
return columns;
}
}
}
| 32.203704 | 99 | 0.643186 | [
"vector"
] |
33d8a3ba42d35e386cca2c1132f8d322d320a8bd | 26,066 | hpp | C++ | python/pylc_converters.hpp | CMU-Light-Curtains/Simulator | 6ad251738b02911b346a9f6dd3757555a92ad02d | [
"BSD-3-Clause"
] | 5 | 2022-01-02T09:48:13.000Z | 2022-03-12T15:44:25.000Z | python/pylc_converters.hpp | CMU-Light-Curtains/Simulator | 6ad251738b02911b346a9f6dd3757555a92ad02d | [
"BSD-3-Clause"
] | null | null | null | python/pylc_converters.hpp | CMU-Light-Curtains/Simulator | 6ad251738b02911b346a9f6dd3757555a92ad02d | [
"BSD-3-Clause"
] | null | null | null | #ifndef CONVERTERS_H
#define CONVERTERS_H
#include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <stdexcept>
#include <opencv2/opencv.hpp>
namespace py = pybind11;
// Numpy - cv::Mat interop
namespace pybind11 { namespace detail {
template <> struct type_caster<cv::Mat> {
public:
PYBIND11_TYPE_CASTER(cv::Mat, _("numpy.ndarray"));
// Cast numpy to cv::Mat
bool load(handle src, bool)
{
/* Try a default converting into a Python */
//array b(src, true);
array b = reinterpret_borrow<array>(src);
buffer_info info = b.request();
int ndims = info.ndim;
decltype(CV_32F) dtype;
size_t elemsize;
if (info.format == format_descriptor<float>::format()) {
if (ndims == 3) {
dtype = CV_32FC3;
} else {
dtype = CV_32FC1;
}
elemsize = sizeof(float);
} else if (info.format == format_descriptor<double>::format()) {
if (ndims == 3) {
dtype = CV_64FC3;
} else {
dtype = CV_64FC1;
}
elemsize = sizeof(double);
} else if (info.format == format_descriptor<unsigned char>::format()) {
if (ndims == 3) {
dtype = CV_8UC3;
} else {
dtype = CV_8UC1;
}
elemsize = sizeof(unsigned char);
} else {
throw std::logic_error("Unsupported type");
return false;
}
std::vector<int> shape = {(int)info.shape[0], (int)info.shape[1]};
value = cv::Mat(cv::Size(shape[1], shape[0]), dtype, info.ptr, cv::Mat::AUTO_STEP);
return true;
}
// Cast cv::Mat to numpy
static handle cast(const cv::Mat &m, return_value_policy, handle defval)
{
std::string format = format_descriptor<unsigned char>::format();
size_t elemsize = sizeof(unsigned char);
int dim, channels;
switch(m.type()) {
case CV_8U:
format = format_descriptor<unsigned char>::format();
elemsize = sizeof(unsigned char);
dim = 2;
channels = 0;
break;
case CV_8UC3:
format = format_descriptor<unsigned char>::format();
elemsize = sizeof(unsigned char);
dim = 3;
channels = 3;
break;
case CV_32F:
format = format_descriptor<float>::format();
elemsize = sizeof(float);
dim = 2;
channels = 0;
break;
case CV_64F:
format = format_descriptor<double>::format();
elemsize = sizeof(double);
dim = 2;
channels = 0;
break;
case CV_32FC4:
format = format_descriptor<float>::format();
elemsize = sizeof(float);
dim = 3;
channels = 4;
break;
default:
throw std::logic_error("Unsupported type");
}
std::vector<size_t> bufferdim;
std::vector<size_t> strides;
if (dim == 2) {
bufferdim = {(size_t) m.rows, (size_t) m.cols};
strides = {elemsize * (size_t) m.cols, elemsize};
} else if (dim == 3) {
bufferdim = {(size_t) m.rows, (size_t) m.cols, (size_t) channels};
strides = {(size_t) elemsize * m.cols * channels, (size_t) elemsize * channels, (size_t) elemsize};
}
return array(buffer_info(
m.data, /* Pointer to buffer */
elemsize, /* Size of one scalar */
format, /* Python struct-style format descriptor */
dim, /* Number of dimensions */
bufferdim, /* Buffer dimensions */
strides /* Strides (in bytes) for each index */
)).release();
}
};
}} // namespace pybind11::detail
#ifdef ROS
#include <ros/duration.h>
#include <ros/ros.h>
#include <ros/time.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Point.h>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/Transform.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/Vector3.h>
#include <sensor_msgs/CameraInfo.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/Header.h>
static inline bool is_ros_msg_type(pybind11::handle src,
const std::string &msg_type_name) {
namespace py = pybind11;
if (!py::hasattr(src, "_type")) {
return false;
}
std::string msg_type(src.attr("_type").cast<std::string>());
if (msg_type != msg_type_name) {
return false;
}
return true;
}
namespace pybind11 {
namespace detail {
template <>
struct type_caster<ros::Time> {
public:
PYBIND11_TYPE_CASTER(ros::Time, _("ros::Time"));
// python -> cpp
bool load(handle src, bool) {
PyObject *obj(src.ptr());
if (!PyObject_HasAttrString(obj, "secs")) {
return false;
}
if (!PyObject_HasAttrString(obj, "nsecs")) {
return false;
}
value.sec = (src.attr("secs")).cast<uint32_t>();
value.nsec = (src.attr("nsecs")).cast<uint32_t>();
return true;
}
// cpp -> python
static handle cast(ros::Time src, return_value_policy policy, handle parent) {
object rospy = module::import("rospy");
object TimeType = rospy.attr("Time");
object pyts = TimeType();
pyts.attr("secs") = pybind11::cast(src.sec);
pyts.attr("nsecs") = pybind11::cast(src.nsec);
pyts.inc_ref();
return pyts;
}
};
template <>
struct type_caster<std_msgs::Header> {
public:
PYBIND11_TYPE_CASTER(std_msgs::Header, _("std_msgs::Header"));
// python -> cpp
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "std_msgs/Header")) {
return false;
}
value.seq = src.attr("seq").cast<uint32_t>();
value.stamp = src.attr("stamp").cast<ros::Time>();
value.frame_id = src.attr("frame_id").cast<std::string>();
return true;
}
// cpp -> python
static handle cast(std_msgs::Header header,
return_value_policy policy,
handle parent) {
object mod = module::import("std_msgs.msg._Header");
object MsgType = mod.attr("Header");
object msg = MsgType();
msg.attr("seq") = pybind11::cast(header.seq);
msg.attr("stamp") = pybind11::cast(header.stamp);
// avoid !!python/unicode problem.
// msg.attr("frame_id") = pybind11::cast(header.frame_id);
msg.attr("frame_id") =
pybind11::bytes(reinterpret_cast<const char *>(&header.frame_id[0]),
header.frame_id.size());
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<geometry_msgs::Point> {
public:
PYBIND11_TYPE_CASTER(geometry_msgs::Point, _("geometry_msgs::Point"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "geometry_msgs/Point")) {
return false;
}
value.x = (src.attr("x")).cast<double>();
value.y = (src.attr("y")).cast<double>();
value.z = (src.attr("z")).cast<double>();
return true;
}
static handle cast(geometry_msgs::Point pt,
return_value_policy policy,
handle parent) {
object mod = module::import("geometry_msgs.msg._Point");
object MsgType = mod.attr("Point");
object msg = MsgType();
msg.attr("x") = pybind11::cast(pt.x);
msg.attr("y") = pybind11::cast(pt.y);
msg.attr("z") = pybind11::cast(pt.z);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<geometry_msgs::Vector3> {
public:
PYBIND11_TYPE_CASTER(geometry_msgs::Vector3, _("geometry_msgs::Vector3"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "geometry_msgs/Vector3")) {
return false;
}
value.x = (src.attr("x")).cast<double>();
value.y = (src.attr("y")).cast<double>();
value.z = (src.attr("z")).cast<double>();
return true;
}
static handle cast(geometry_msgs::Vector3 cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("geometry_msgs.msg._Vector3");
object MsgType = mod.attr("Vector3");
object msg = MsgType();
msg.attr("x") = pybind11::cast(cpp_msg.x);
msg.attr("y") = pybind11::cast(cpp_msg.y);
msg.attr("z") = pybind11::cast(cpp_msg.z);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<geometry_msgs::Quaternion> {
public:
PYBIND11_TYPE_CASTER(geometry_msgs::Quaternion,
_("geometry_msgs::Quaternion"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "geometry_msgs/Quaternion")) {
return false;
}
value.x = (src.attr("x")).cast<double>();
value.y = (src.attr("y")).cast<double>();
value.z = (src.attr("z")).cast<double>();
value.w = (src.attr("w")).cast<double>();
return true;
}
static handle cast(geometry_msgs::Quaternion cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("geometry_msgs.msg._Quaternion");
object MsgType = mod.attr("Quaternion");
object msg = MsgType();
msg.attr("x") = pybind11::cast(cpp_msg.x);
msg.attr("y") = pybind11::cast(cpp_msg.y);
msg.attr("z") = pybind11::cast(cpp_msg.z);
msg.attr("w") = pybind11::cast(cpp_msg.w);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<geometry_msgs::Transform> {
public:
PYBIND11_TYPE_CASTER(geometry_msgs::Transform, _("geometry_msgs::Transform"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "geometry_msgs/Transform")) {
return false;
}
value.translation =
(src.attr("translation")).cast<geometry_msgs::Vector3>();
value.rotation = (src.attr("rotation")).cast<geometry_msgs::Quaternion>();
return true;
}
static handle cast(geometry_msgs::Transform cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("geometry_msgs.msg._Transform");
object MsgType = mod.attr("Transform");
object msg = MsgType();
msg.attr("translation") = pybind11::cast(cpp_msg.translation);
msg.attr("rotation") = pybind11::cast(cpp_msg.rotation);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<geometry_msgs::TransformStamped> {
public:
PYBIND11_TYPE_CASTER(geometry_msgs::TransformStamped,
_("geometry_msgs::TransformStamped"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "geometry_msgs/TransformStamped")) {
return false;
}
value.header = src.attr("header").cast<std_msgs::Header>();
value.child_frame_id = src.attr("child_frame_id").cast<std::string>();
value.transform = src.attr("transform").cast<geometry_msgs::Transform>();
return true;
}
static handle cast(geometry_msgs::TransformStamped cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("geometry_msgs.msg._TransformStamped");
object MsgType = mod.attr("TransformStamped");
object msg = MsgType();
msg.attr("header") = pybind11::cast(cpp_msg.header);
// msg.attr("child_frame_id") = pybind11::cast(cpp_msg.child_frame_id);
msg.attr("child_frame_id") = pybind11::bytes(
reinterpret_cast<const char *>(&cpp_msg.child_frame_id[0]),
cpp_msg.child_frame_id.size());
msg.attr("transform") = pybind11::cast(cpp_msg.transform);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<sensor_msgs::PointField> {
public:
PYBIND11_TYPE_CASTER(sensor_msgs::PointField, _("sensor_msgs::PointField"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "sensor_msgs/PointField")) {
return false;
}
value.name = (src.attr("name")).cast<std::string>();
value.offset = (src.attr("offset")).cast<uint32_t>();
value.datatype = (src.attr("datatype")).cast<uint8_t>();
value.count = (src.attr("count")).cast<uint32_t>();
return true;
}
static handle cast(sensor_msgs::PointField cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("sensor_msgs.msg._PointField");
object MsgType = mod.attr("PointField");
object msg = MsgType();
// avoid !!python/unicode problem.
// msg.attr("name") = pybind11::cast(cpp_msg.name);
// msg.attr("name") = PyString_FromString(cpp_msg.name.c_str());
msg.attr("name") = pybind11::bytes(
reinterpret_cast<const char *>(&cpp_msg.name[0]), cpp_msg.name.size());
msg.attr("offset") = pybind11::cast(cpp_msg.offset);
msg.attr("datatype") = pybind11::cast(cpp_msg.datatype);
msg.attr("count") = pybind11::cast(cpp_msg.count);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<sensor_msgs::PointCloud2> {
public:
PYBIND11_TYPE_CASTER(sensor_msgs::PointCloud2, _("sensor_msgs::PointCloud2"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "sensor_msgs/PointCloud2")) {
return false;
}
value.header = (src.attr("header")).cast<std_msgs::Header>();
value.height = (src.attr("height")).cast<uint32_t>();
value.width = (src.attr("width")).cast<uint32_t>();
pybind11::list field_lst = (src.attr("fields")).cast<pybind11::list>();
for (int i = 0; i < pybind11::len(field_lst); ++i) {
sensor_msgs::PointField pf(
(field_lst[i]).cast<sensor_msgs::PointField>());
value.fields.push_back(pf);
}
value.is_bigendian = (src.attr("is_bigendian")).cast<bool>();
value.point_step = (src.attr("point_step")).cast<uint32_t>();
value.row_step = (src.attr("row_step")).cast<uint32_t>();
std::string data_str = (src.attr("data")).cast<std::string>();
value.data.insert(value.data.end(),
data_str.c_str(),
data_str.c_str() + data_str.length());
value.is_dense = (src.attr("is_dense")).cast<bool>();
return true;
}
static handle cast(sensor_msgs::PointCloud2 cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("sensor_msgs.msg._PointCloud2");
object MsgType = mod.attr("PointCloud2");
object msg = MsgType();
msg.attr("header") = pybind11::cast(cpp_msg.header);
msg.attr("height") = pybind11::cast(cpp_msg.height);
msg.attr("width") = pybind11::cast(cpp_msg.width);
// msg.attr("fields") = pybind11::cast(cpp_msg.fields);
// pybind11::list field_lst = (msg.attr("fields")).cast<pybind11::list>();
pybind11::list field_lst;
for (size_t i = 0; i < cpp_msg.fields.size(); ++i) {
const sensor_msgs::PointField &pf(cpp_msg.fields[i]);
field_lst.append(pybind11::cast(pf));
}
msg.attr("fields") = field_lst;
msg.attr("is_bigendian") = pybind11::cast(cpp_msg.is_bigendian);
msg.attr("point_step") = pybind11::cast(cpp_msg.point_step);
msg.attr("row_step") = pybind11::cast(cpp_msg.row_step);
// msg.attr("data") = pybind11::bytes(std::string(cpp_msg.data.begin(),
// cpp_msg.data.end()));
msg.attr("data") = pybind11::bytes(
reinterpret_cast<const char *>(&cpp_msg.data[0]), cpp_msg.data.size());
msg.attr("is_dense") = pybind11::cast(cpp_msg.is_dense);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<sensor_msgs::Image> {
public:
PYBIND11_TYPE_CASTER(sensor_msgs::Image, _("sensor_msgs::Image"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "sensor_msgs/Image")) {
return false;
}
value.header = src.attr("header").cast<std_msgs::Header>();
value.height = src.attr("height").cast<uint32_t>();
value.width = src.attr("width").cast<uint32_t>();
value.encoding = src.attr("encoding").cast<std::string>();
value.is_bigendian = src.attr("is_bigendian").cast<int>();
value.step = src.attr("step").cast<uint32_t>();
std::string data_str = src.attr("data").cast<std::string>();
value.data.insert(value.data.end(),
data_str.c_str(),
data_str.c_str() + data_str.length());
return true;
}
static handle cast(sensor_msgs::Image cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("sensor_msgs.msg._Image");
object MsgType = mod.attr("Image");
object msg = MsgType();
msg.attr("header") = pybind11::cast(cpp_msg.header);
msg.attr("height") = pybind11::cast(cpp_msg.height);
msg.attr("width") = pybind11::cast(cpp_msg.width);
msg.attr("encoding") = pybind11::bytes(cpp_msg.encoding);
msg.attr("is_bigendian") = pybind11::cast(cpp_msg.is_bigendian);
msg.attr("step") = pybind11::cast(cpp_msg.step);
// msg.attr("data") = pybind11::bytes(std::string(cpp_msg.data.begin(),
// cpp_msg.data.end()));
msg.attr("data") = pybind11::bytes(
reinterpret_cast<const char *>(&cpp_msg.data[0]), cpp_msg.data.size());
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<sensor_msgs::CameraInfo> {
public:
PYBIND11_TYPE_CASTER(sensor_msgs::CameraInfo, _("sensor_msgs::CameraInfo"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "sensor_msgs/CameraInfo")) {
return false;
}
value.height = src.attr("height").cast<uint32_t>();
value.width = src.attr("width").cast<uint32_t>();
value.distortion_model = src.attr("distortion_model").cast<std::string>();
{
for (auto item : src.attr("D")) {
value.D.push_back(item.cast<double>());
}
}
{
int i = 0;
for (auto item : src.attr("K")) {
value.K[i] = item.cast<double>();
++i;
}
}
{
int i = 0;
for (auto item : src.attr("R")) {
value.R[i] = item.cast<double>();
++i;
}
}
{
int i = 0;
for (auto item : src.attr("P")) {
value.P[i] = item.cast<double>();
++i;
}
}
value.header = src.attr("header").cast<std_msgs::Header>();
return true;
}
static handle cast(sensor_msgs::CameraInfo cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("sensor_msgs.msg._CameraInfo");
object MsgType = mod.attr("CameraInfo");
object msg = MsgType();
// TODO untested
msg.attr("height") = cpp_msg.height;
msg.attr("width") = cpp_msg.width;
msg.attr("distortion_model") = cpp_msg.distortion_model;
for (size_t i = 0; i < cpp_msg.D.size(); ++i) {
pybind11::list D = msg.attr("D");
D[i] = cpp_msg.K[i];
}
for (size_t i = 0; i < cpp_msg.K.size(); ++i) {
pybind11::list K = msg.attr("K");
K[i] = cpp_msg.K[i];
}
for (size_t i = 0; i < cpp_msg.R.size(); ++i) {
pybind11::list R = msg.attr("R");
R[i] = cpp_msg.K[i];
}
for (size_t i = 0; i < cpp_msg.P.size(); ++i) {
pybind11::list P = msg.attr("P");
P[i] = cpp_msg.P[i];
}
msg.attr("header") = pybind11::cast(cpp_msg.header);
msg.inc_ref();
return msg;
}
};
template <>
struct type_caster<geometry_msgs::Pose> {
public:
PYBIND11_TYPE_CASTER(geometry_msgs::Pose, _("geometry_msgs::Pose"));
bool load(handle src, bool) {
if (!is_ros_msg_type(src, "geometry_msgs/Pose")) {
return false;
}
value.position = (src.attr("position")).cast<geometry_msgs::Point>();
value.orientation =
(src.attr("orientation")).cast<geometry_msgs::Quaternion>();
return true;
}
static handle cast(geometry_msgs::Pose cpp_msg,
return_value_policy policy,
handle parent) {
object mod = module::import("geometry_msgs.msg._Pose");
object MsgType = mod.attr("Pose");
object msg = MsgType();
msg.attr("position") = pybind11::cast(cpp_msg.position);
msg.attr("orientation") = pybind11::cast(cpp_msg.orientation);
msg.inc_ref();
return msg;
}
};
}
}
#endif
#endif | 41.506369 | 119 | 0.467621 | [
"object",
"shape",
"vector",
"transform"
] |
33d983cb380e9c6efbb40f7bc1897a793121dc30 | 1,458 | hpp | C++ | Tutorials/06-Raytrace/RTX/Structs/DxilLibrary.hpp | qingqhua/CppDirectXRayTracing | bbdae2155a3b464faddce5eec8a000eb318e0c0f | [
"BSD-3-Clause"
] | 1 | 2021-09-06T13:09:13.000Z | 2021-09-06T13:09:13.000Z | Tutorials/06-Raytrace/RTX/Structs/DxilLibrary.hpp | qingqhua/CppDirectXRayTracing | bbdae2155a3b464faddce5eec8a000eb318e0c0f | [
"BSD-3-Clause"
] | null | null | null | Tutorials/06-Raytrace/RTX/Structs/DxilLibrary.hpp | qingqhua/CppDirectXRayTracing | bbdae2155a3b464faddce5eec8a000eb318e0c0f | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "Framework.h"
namespace CppDirectXRayTracing06
{
struct DxilLibrary
{
DxilLibrary(ID3DBlobPtr pBlob, const WCHAR* entryPoint[], uint32_t entryPointCount) : pShaderBlob(pBlob)
{
stateSubobject.Type = D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY;
stateSubobject.pDesc = &dxilLibDesc;
dxilLibDesc = {};
exportDesc.resize(entryPointCount);
exportName.resize(entryPointCount);
if (pBlob)
{
dxilLibDesc.DXILLibrary.pShaderBytecode = pBlob->GetBufferPointer();
dxilLibDesc.DXILLibrary.BytecodeLength = pBlob->GetBufferSize();
dxilLibDesc.NumExports = entryPointCount;
dxilLibDesc.pExports = exportDesc.data();
for (uint32_t i = 0; i < entryPointCount; i++)
{
exportName[i] = entryPoint[i];
exportDesc[i].Name = exportName[i].c_str();
exportDesc[i].Flags = D3D12_EXPORT_FLAG_NONE;
exportDesc[i].ExportToRename = nullptr;
}
}
};
DxilLibrary() : DxilLibrary(nullptr, nullptr, 0) {}
D3D12_DXIL_LIBRARY_DESC dxilLibDesc = {};
D3D12_STATE_SUBOBJECT stateSubobject{};
ID3DBlobPtr pShaderBlob;
std::vector<D3D12_EXPORT_DESC> exportDesc;
std::vector<std::wstring> exportName;
};
} | 35.560976 | 112 | 0.58642 | [
"vector"
] |
33da54504df23ad3c7088857c2d0631d45d9bbef | 7,745 | hh | C++ | src/OpenMesh/Apps/Unsupported/Streaming-qt4/Server/VDPMServerSession.hh | rzoller/OpenMesh | f84bca0b26c61eab5f9335b2191962ca8545c5f6 | [
"BSD-3-Clause"
] | null | null | null | src/OpenMesh/Apps/Unsupported/Streaming-qt4/Server/VDPMServerSession.hh | rzoller/OpenMesh | f84bca0b26c61eab5f9335b2191962ca8545c5f6 | [
"BSD-3-Clause"
] | null | null | null | src/OpenMesh/Apps/Unsupported/Streaming-qt4/Server/VDPMServerSession.hh | rzoller/OpenMesh | f84bca0b26c61eab5f9335b2191962ca8545c5f6 | [
"BSD-3-Clause"
] | null | null | null | /* ========================================================================= *
* *
* OpenMesh *
* Copyright (c) 2001-2015, RWTH-Aachen University *
* Department of Computer Graphics and Multimedia *
* All rights reserved. *
* www.openmesh.org *
* *
*---------------------------------------------------------------------------*
* This file is part of OpenMesh. *
*---------------------------------------------------------------------------*
* *
* 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. *
* *
* ========================================================================= */
/*===========================================================================*\
* *
* $Revision: 1258 $ *
* $Date: 2015-04-28 15:07:46 +0200 (Di, 28 Apr 2015) $ *
* *
\*===========================================================================*/
#ifndef OPENMESH_APP_VDPMSTREAMING_SERVER_VDPMSERVERSESSION_HH
#define OPENMESH_APP_VDPMSTREAMING_SERVER_VDPMSERVERSESSION_HH
#include <QTcpSocket>
#include <QThread>
#include <QDataStream>
#include <QTimer>
#include <iostream>
// #include <QObject>
#include <OpenMesh/Core/Geometry/VectorT.hh>
#include <OpenMesh/Core/Geometry/Plane3d.hh>
#include <OpenMesh/Tools/Utils/Timer.hh>
#include <OpenMesh/Tools/VDPM/StreamingDef.hh>
#include <OpenMesh/Tools/VDPM/VHierarchyNodeIndex.hh>
#include <OpenMesh/Tools/VDPM/ViewingParameters.hh>
#include <OpenMesh/Tools/VDPM/VHierarchy.hh>
#include <OpenMesh/Tools/VDPM/VFront.hh>
#include <OpenMesh/Apps/VDProgMesh/Streaming/Server/ServerSideVDPM.hh>
#include <OpenMesh/Tools/VDPM/VHierarchyWindow.hh>
using OpenMesh::VDPM::VDPMStreamingPhase;
using OpenMesh::VDPM::kBaseMesh;
using OpenMesh::VDPM::kVSplits;
using OpenMesh::VDPM::VHierarchyWindow;
using OpenMesh::VDPM::VHierarchyNodeIndex;
using OpenMesh::VDPM::VHierarchyNodeHandle;
using OpenMesh::VDPM::ViewingParameters;
using OpenMesh::VDPM::set_debug_print;
class VDPMServerSession : public QThread
{
Q_OBJECT
public:
VDPMServerSession(QTcpSocket* _socket, QObject *parent=0, const char *name=0)
{
socket_ = _socket;
set_debug_print(true);
streaming_phase_ = kBaseMesh;
transmission_complete_ = false;
connect(socket_, SIGNAL(connected()), this, SLOT(socketConnected()));
QTcpSocket::connect(socket_, SIGNAL(readyRead()), this, SLOT(socketReadyRead()));
//connect(this, SIGNAL(connectionClosed()), SLOT(deleteLater()));
QTcpSocket::connect(socket_, SIGNAL(connectionClosed()), this, SLOT(delayedCloseFinished()));
///TODO: find out how to port it from QSocket -> QTcpSocket
// setSocket(sock);
qStatisticsTimer_ = new QTimer(this);
QTcpSocket::connect(qStatisticsTimer_, SIGNAL(timeout()), this, SLOT(print_statistics()));
mem_file = fopen("mem.txt", "w");
start();
}
~VDPMServerSession()
{
fclose(mem_file);
}
// void run()
// {
// exec();
// }
private:
VDPMStreamingPhase streaming_phase_;
bool transmission_complete_;
QTcpSocket* socket_;
private:
void sendBaseMeshToClient();
void send_vsplit_packets();
void readBaseMeshRequestFromClient();
void readViewingParametersFromClient();
void PrintOutVFront();
private slots:
void socketConnected()
{
std::cout << "socket is connected" << std::endl;
}
void socketReadyRead()
{
if (streaming_phase_ == kBaseMesh)
{
readBaseMeshRequestFromClient();
}
else if (streaming_phase_ == kVSplits)
{
readViewingParametersFromClient();
}
}
void print_statistics()
{
//std::cout << memory_requirements(true) << " " << memory_requirements(false) << std::endl;
}
private:
unsigned short tree_id_bits_; // obsolete
ServerSideVDPM* vdpm_;
VHierarchy* vhierarchy_;
VHierarchyWindow vhwindow_;
ViewingParameters viewing_parameters_;
float kappa_square_;
VHierarchyNodeHandleContainer vsplits_;
private:
bool outside_view_frustum(const OpenMesh::Vec3f &pos, float radius);
bool oriented_away(float sin_square, float distance_square, float product_value);
bool screen_space_error(float mue_square, float sigma_square, float distance_square, float product_value);
void adaptive_refinement();
void sequential_refinement();
bool qrefine(VHierarchyNodeHandle _node_handle);
void force_vsplit(VHierarchyNodeHandle node_handle);
void vsplit(VHierarchyNodeHandle _node_handle);
VHierarchyNodeHandle active_ancestor_handle(VHierarchyNodeIndex &node_index);
void stream_vsplits();
public:
bool set_vdpm(const char _vdpm_name[256]);
unsigned int memory_requirements_using_window(bool _estimate);
unsigned int memory_requirements_using_vfront();
// for example
private:
QTimer *qStatisticsTimer_;
FILE *mem_file;
};
#endif //OPENMESH_APP_VDPMSTREAMING_SERVER_VDPMSERVERSESSION_HH defined
| 39.314721 | 108 | 0.559458 | [
"geometry"
] |
33dacabb8be7b333cc36e01f69e105c674bee8dd | 71,784 | cc | C++ | third_party/webrtc/src/chromium/src/device/bluetooth/dbus/fake_bluetooth_device_client.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 8 | 2016-02-08T11:59:31.000Z | 2020-05-31T15:19:54.000Z | third_party/webrtc/src/chromium/src/device/bluetooth/dbus/fake_bluetooth_device_client.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 1 | 2021-05-05T11:11:31.000Z | 2021-05-05T11:11:31.000Z | third_party/webrtc/src/chromium/src/device/bluetooth/dbus/fake_bluetooth_device_client.cc | bopopescu/webrtc-streaming-node | 727a441204344ff596401b0253caac372b714d91 | [
"MIT"
] | 7 | 2016-02-09T09:28:14.000Z | 2020-07-25T19:03:36.000Z | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/dbus/fake_bluetooth_device_client.h"
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <algorithm>
#include <string>
#include <utility>
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/rand_util.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
#include "base/time/time.h"
#include "dbus/file_descriptor.h"
#include "device/bluetooth/dbus/bluez_dbus_manager.h"
#include "device/bluetooth/dbus/fake_bluetooth_adapter_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_agent_manager_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_agent_service_provider.h"
#include "device/bluetooth/dbus/fake_bluetooth_gatt_service_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_input_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_profile_manager_client.h"
#include "device/bluetooth/dbus/fake_bluetooth_profile_service_provider.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace {
// Default interval between simulated events.
const int kSimulationIntervalMs = 750;
// Minimum and maximum bounds for randomly generated RSSI values.
const int kMinRSSI = -90;
const int kMaxRSSI = -30;
// The default value of connection info properties from GetConnInfo().
const int kUnkownPower = 127;
// This is meant to delay the removal of a pre defined device until the
// developer has time to see it.
const int kVanishingDevicePairTimeMultiplier = 4;
// Meant to delay a pair request for an observable amount of time.
const int kIncomingSimulationPairTimeMultiplier = 45;
// Meant to delay a request that asks for pair requests for an observable
// amount of time.
const int kIncomingSimulationStartPairTimeMultiplier = 30;
// This allows the PIN code dialog to be shown for a long enough time to see
// the PIN code UI in detail.
const int kPinCodeDevicePairTimeMultiplier = 7;
// This allows the pairing dialog to be shown for a long enough time to see
// its UI in detail.
const int kSimulateNormalPairTimeMultiplier = 3;
void SimulatedProfileSocket(int fd) {
// Simulate a server-side socket of a profile; read data from the socket,
// write it back, and then close.
char buf[1024];
ssize_t len;
ssize_t count;
len = read(fd, buf, sizeof buf);
if (len < 0) {
close(fd);
return;
}
count = len;
len = write(fd, buf, count);
if (len < 0) {
close(fd);
return;
}
close(fd);
}
void SimpleErrorCallback(const std::string& error_name,
const std::string& error_message) {
VLOG(1) << "Bluetooth Error: " << error_name << ": " << error_message;
}
} // namespace
namespace bluez {
const char FakeBluetoothDeviceClient::kTestPinCode[] = "123456";
const int FakeBluetoothDeviceClient::kTestPassKey = 123456;
const char FakeBluetoothDeviceClient::kPairingMethodNone[] = "None";
const char FakeBluetoothDeviceClient::kPairingMethodPinCode[] = "PIN Code";
const char FakeBluetoothDeviceClient::kPairingMethodPassKey[] = "PassKey";
const char FakeBluetoothDeviceClient::kPairingActionConfirmation[] =
"Confirmation";
const char FakeBluetoothDeviceClient::kPairingActionDisplay[] = "Display";
const char FakeBluetoothDeviceClient::kPairingActionFail[] = "Fail";
const char FakeBluetoothDeviceClient::kPairingActionRequest[] = "Request";
const char FakeBluetoothDeviceClient::kPairedDevicePath[] = "/fake/hci0/dev0";
const char FakeBluetoothDeviceClient::kPairedDeviceAddress[] =
"00:11:22:33:44:55";
const char FakeBluetoothDeviceClient::kPairedDeviceName[] = "Fake Device";
const uint32 FakeBluetoothDeviceClient::kPairedDeviceClass = 0x000104;
const char FakeBluetoothDeviceClient::kLegacyAutopairPath[] = "/fake/hci0/dev1";
const char FakeBluetoothDeviceClient::kLegacyAutopairAddress[] =
"28:CF:DA:00:00:00";
const char FakeBluetoothDeviceClient::kLegacyAutopairName[] =
"Bluetooth 2.0 Mouse";
const uint32 FakeBluetoothDeviceClient::kLegacyAutopairClass = 0x002580;
const char FakeBluetoothDeviceClient::kDisplayPinCodePath[] = "/fake/hci0/dev2";
const char FakeBluetoothDeviceClient::kDisplayPinCodeAddress[] =
"28:37:37:00:00:00";
const char FakeBluetoothDeviceClient::kDisplayPinCodeName[] =
"Bluetooth 2.0 Keyboard";
const uint32 FakeBluetoothDeviceClient::kDisplayPinCodeClass = 0x002540;
const char FakeBluetoothDeviceClient::kVanishingDevicePath[] =
"/fake/hci0/dev3";
const char FakeBluetoothDeviceClient::kVanishingDeviceAddress[] =
"01:02:03:04:05:06";
const char FakeBluetoothDeviceClient::kVanishingDeviceName[] =
"Vanishing Device";
const uint32 FakeBluetoothDeviceClient::kVanishingDeviceClass = 0x000104;
const char FakeBluetoothDeviceClient::kConnectUnpairablePath[] =
"/fake/hci0/dev4";
const char FakeBluetoothDeviceClient::kConnectUnpairableAddress[] =
"7C:ED:8D:00:00:00";
const char FakeBluetoothDeviceClient::kConnectUnpairableName[] =
"Unpairable Device";
const uint32 FakeBluetoothDeviceClient::kConnectUnpairableClass = 0x002580;
const char FakeBluetoothDeviceClient::kDisplayPasskeyPath[] = "/fake/hci0/dev5";
const char FakeBluetoothDeviceClient::kDisplayPasskeyAddress[] =
"00:0F:F6:00:00:00";
const char FakeBluetoothDeviceClient::kDisplayPasskeyName[] =
"Bluetooth 2.1+ Keyboard";
const uint32 FakeBluetoothDeviceClient::kDisplayPasskeyClass = 0x002540;
const char FakeBluetoothDeviceClient::kRequestPinCodePath[] = "/fake/hci0/dev6";
const char FakeBluetoothDeviceClient::kRequestPinCodeAddress[] =
"00:24:BE:00:00:00";
const char FakeBluetoothDeviceClient::kRequestPinCodeName[] = "PIN Device";
const uint32 FakeBluetoothDeviceClient::kRequestPinCodeClass = 0x240408;
const char FakeBluetoothDeviceClient::kConfirmPasskeyPath[] = "/fake/hci0/dev7";
const char FakeBluetoothDeviceClient::kConfirmPasskeyAddress[] =
"20:7D:74:00:00:00";
const char FakeBluetoothDeviceClient::kConfirmPasskeyName[] = "Phone";
const uint32 FakeBluetoothDeviceClient::kConfirmPasskeyClass = 0x7a020c;
const char FakeBluetoothDeviceClient::kRequestPasskeyPath[] = "/fake/hci0/dev8";
const char FakeBluetoothDeviceClient::kRequestPasskeyAddress[] =
"20:7D:74:00:00:01";
const char FakeBluetoothDeviceClient::kRequestPasskeyName[] = "Passkey Device";
const uint32 FakeBluetoothDeviceClient::kRequestPasskeyClass = 0x7a020c;
const char FakeBluetoothDeviceClient::kUnconnectableDevicePath[] =
"/fake/hci0/dev9";
const char FakeBluetoothDeviceClient::kUnconnectableDeviceAddress[] =
"20:7D:74:00:00:02";
const char FakeBluetoothDeviceClient::kUnconnectableDeviceName[] =
"Unconnectable Device";
const uint32 FakeBluetoothDeviceClient::kUnconnectableDeviceClass = 0x7a020c;
const char FakeBluetoothDeviceClient::kUnpairableDevicePath[] =
"/fake/hci0/devA";
const char FakeBluetoothDeviceClient::kUnpairableDeviceAddress[] =
"20:7D:74:00:00:03";
const char FakeBluetoothDeviceClient::kUnpairableDeviceName[] =
"Unpairable Device";
const uint32 FakeBluetoothDeviceClient::kUnpairableDeviceClass = 0x002540;
const char FakeBluetoothDeviceClient::kJustWorksPath[] = "/fake/hci0/devB";
const char FakeBluetoothDeviceClient::kJustWorksAddress[] = "00:0C:8A:00:00:00";
const char FakeBluetoothDeviceClient::kJustWorksName[] = "Just-Works Device";
const uint32 FakeBluetoothDeviceClient::kJustWorksClass = 0x240428;
const char FakeBluetoothDeviceClient::kLowEnergyPath[] = "/fake/hci0/devC";
const char FakeBluetoothDeviceClient::kLowEnergyAddress[] = "00:1A:11:00:15:30";
const char FakeBluetoothDeviceClient::kLowEnergyName[] =
"Bluetooth 4.0 Heart Rate Monitor";
const uint32 FakeBluetoothDeviceClient::kLowEnergyClass =
0x000918; // Major class "Health", Minor class "Heart/Pulse Rate Monitor."
const char FakeBluetoothDeviceClient::kPairedUnconnectableDevicePath[] =
"/fake/hci0/devD";
const char FakeBluetoothDeviceClient::kPairedUnconnectableDeviceAddress[] =
"20:7D:74:00:00:04";
const char FakeBluetoothDeviceClient::kPairedUnconnectableDeviceName[] =
"Paired Unconnectable Device";
const uint32 FakeBluetoothDeviceClient::kPairedUnconnectableDeviceClass =
0x000104;
const char FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDevicePath[] =
"/fake/hci0/devE";
const char
FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDeviceAddress[] =
"11:22:33:44:55:66";
const char FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDeviceName[] =
"Connected Pairable Device";
const uint32 FakeBluetoothDeviceClient::kConnectedTrustedNotPairedDeviceClass =
0x7a020c;
FakeBluetoothDeviceClient::Properties::Properties(
const PropertyChangedCallback& callback)
: BluetoothDeviceClient::Properties(
NULL,
bluetooth_device::kBluetoothDeviceInterface,
callback) {}
FakeBluetoothDeviceClient::Properties::~Properties() {}
void FakeBluetoothDeviceClient::Properties::Get(
dbus::PropertyBase* property,
dbus::PropertySet::GetCallback callback) {
VLOG(1) << "Get " << property->name();
callback.Run(false);
}
void FakeBluetoothDeviceClient::Properties::GetAll() {
VLOG(1) << "GetAll";
}
void FakeBluetoothDeviceClient::Properties::Set(
dbus::PropertyBase* property,
dbus::PropertySet::SetCallback callback) {
VLOG(1) << "Set " << property->name();
if (property->name() == trusted.name()) {
callback.Run(true);
property->ReplaceValueWithSetValue();
} else {
callback.Run(false);
}
}
FakeBluetoothDeviceClient::SimulatedPairingOptions::SimulatedPairingOptions() {}
FakeBluetoothDeviceClient::SimulatedPairingOptions::~SimulatedPairingOptions() {
}
FakeBluetoothDeviceClient::IncomingDeviceProperties::
IncomingDeviceProperties() {}
FakeBluetoothDeviceClient::IncomingDeviceProperties::
~IncomingDeviceProperties() {}
FakeBluetoothDeviceClient::FakeBluetoothDeviceClient()
: simulation_interval_ms_(kSimulationIntervalMs),
discovery_simulation_step_(0),
incoming_pairing_simulation_step_(0),
pairing_cancelled_(false),
connection_rssi_(kUnkownPower),
transmit_power_(kUnkownPower),
max_transmit_power_(kUnkownPower) {
scoped_ptr<Properties> properties(new Properties(
base::Bind(&FakeBluetoothDeviceClient::OnPropertyChanged,
base::Unretained(this), dbus::ObjectPath(kPairedDevicePath))));
properties->address.ReplaceValue(kPairedDeviceAddress);
properties->bluetooth_class.ReplaceValue(kPairedDeviceClass);
properties->name.ReplaceValue("Fake Device (Name)");
properties->alias.ReplaceValue(kPairedDeviceName);
properties->paired.ReplaceValue(true);
properties->trusted.ReplaceValue(true);
properties->adapter.ReplaceValue(
dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath));
std::vector<std::string> uuids;
uuids.push_back("00001800-0000-1000-8000-00805f9b34fb");
uuids.push_back("00001801-0000-1000-8000-00805f9b34fb");
properties->uuids.ReplaceValue(uuids);
properties->modalias.ReplaceValue("usb:v05ACp030Dd0306");
properties_map_.insert(dbus::ObjectPath(kPairedDevicePath),
properties.Pass());
device_list_.push_back(dbus::ObjectPath(kPairedDevicePath));
properties.reset(new Properties(base::Bind(
&FakeBluetoothDeviceClient::OnPropertyChanged, base::Unretained(this),
dbus::ObjectPath(kPairedUnconnectableDevicePath))));
properties->address.ReplaceValue(kPairedUnconnectableDeviceAddress);
properties->bluetooth_class.ReplaceValue(kPairedUnconnectableDeviceClass);
properties->name.ReplaceValue("Fake Device 2 (Unconnectable)");
properties->alias.ReplaceValue(kPairedUnconnectableDeviceName);
properties->paired.ReplaceValue(true);
properties->trusted.ReplaceValue(true);
properties->adapter.ReplaceValue(
dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath));
properties->uuids.ReplaceValue(uuids);
properties->modalias.ReplaceValue("usb:v05ACp030Dd0306");
properties_map_.insert(dbus::ObjectPath(kPairedUnconnectableDevicePath),
properties.Pass());
device_list_.push_back(dbus::ObjectPath(kPairedUnconnectableDevicePath));
}
FakeBluetoothDeviceClient::~FakeBluetoothDeviceClient() {}
void FakeBluetoothDeviceClient::Init(dbus::Bus* bus) {}
void FakeBluetoothDeviceClient::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void FakeBluetoothDeviceClient::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
std::vector<dbus::ObjectPath> FakeBluetoothDeviceClient::GetDevicesForAdapter(
const dbus::ObjectPath& adapter_path) {
if (adapter_path ==
dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath))
return device_list_;
else
return std::vector<dbus::ObjectPath>();
}
FakeBluetoothDeviceClient::Properties* FakeBluetoothDeviceClient::GetProperties(
const dbus::ObjectPath& object_path) {
PropertiesMap::const_iterator iter = properties_map_.find(object_path);
if (iter != properties_map_.end())
return iter->second;
return NULL;
}
FakeBluetoothDeviceClient::SimulatedPairingOptions*
FakeBluetoothDeviceClient::GetPairingOptions(
const dbus::ObjectPath& object_path) {
PairingOptionsMap::const_iterator iter =
pairing_options_map_.find(object_path);
if (iter != pairing_options_map_.end())
return iter->second;
return iter != pairing_options_map_.end() ? iter->second : nullptr;
}
void FakeBluetoothDeviceClient::Connect(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "Connect: " << object_path.value();
Properties* properties = GetProperties(object_path);
if (properties->connected.value() == true) {
// Already connected.
callback.Run();
return;
}
if (properties->paired.value() != true &&
object_path != dbus::ObjectPath(kConnectUnpairablePath) &&
object_path != dbus::ObjectPath(kLowEnergyPath)) {
// Must be paired.
error_callback.Run(bluetooth_device::kErrorFailed, "Not paired");
return;
} else if (properties->paired.value() == true &&
(object_path == dbus::ObjectPath(kUnconnectableDevicePath) ||
object_path ==
dbus::ObjectPath(kPairedUnconnectableDevicePath))) {
// Must not be paired
error_callback.Run(bluetooth_device::kErrorFailed,
"Connection fails while paired");
return;
}
// The device can be connected.
properties->connected.ReplaceValue(true);
callback.Run();
// Expose GATT services if connected to LE device.
if (object_path == dbus::ObjectPath(kLowEnergyPath)) {
FakeBluetoothGattServiceClient* gatt_service_client =
static_cast<FakeBluetoothGattServiceClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothGattServiceClient());
gatt_service_client->ExposeHeartRateService(
dbus::ObjectPath(kLowEnergyPath));
}
AddInputDeviceIfNeeded(object_path, properties);
}
void FakeBluetoothDeviceClient::Disconnect(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "Disconnect: " << object_path.value();
Properties* properties = GetProperties(object_path);
if (!properties->connected.value()) {
error_callback.Run("org.bluez.Error.NotConnected", "Not Connected");
return;
}
// Hide the Heart Rate Service if disconnected from LE device.
if (object_path == dbus::ObjectPath(kLowEnergyPath)) {
FakeBluetoothGattServiceClient* gatt_service_client =
static_cast<FakeBluetoothGattServiceClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothGattServiceClient());
gatt_service_client->HideHeartRateService();
}
callback.Run();
properties->connected.ReplaceValue(false);
}
void FakeBluetoothDeviceClient::ConnectProfile(
const dbus::ObjectPath& object_path,
const std::string& uuid,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "ConnectProfile: " << object_path.value() << " " << uuid;
FakeBluetoothProfileManagerClient* fake_bluetooth_profile_manager_client =
static_cast<FakeBluetoothProfileManagerClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothProfileManagerClient());
FakeBluetoothProfileServiceProvider* profile_service_provider =
fake_bluetooth_profile_manager_client->GetProfileServiceProvider(uuid);
if (profile_service_provider == NULL) {
error_callback.Run(kNoResponseError, "Missing profile");
return;
}
if (object_path == dbus::ObjectPath(kPairedUnconnectableDevicePath)) {
error_callback.Run(bluetooth_device::kErrorFailed, "unconnectable");
return;
}
// Make a socket pair of a compatible type with the type used by Bluetooth;
// spin up a thread to simulate the server side and wrap the client side in
// a D-Bus file descriptor object.
int socket_type = SOCK_STREAM;
if (uuid == FakeBluetoothProfileManagerClient::kL2capUuid)
socket_type = SOCK_SEQPACKET;
int fds[2];
if (socketpair(AF_UNIX, socket_type, 0, fds) < 0) {
error_callback.Run(kNoResponseError, "socketpair call failed");
return;
}
int args;
args = fcntl(fds[1], F_GETFL, NULL);
if (args < 0) {
error_callback.Run(kNoResponseError, "failed to get socket flags");
return;
}
args |= O_NONBLOCK;
if (fcntl(fds[1], F_SETFL, args) < 0) {
error_callback.Run(kNoResponseError, "failed to set socket non-blocking");
return;
}
base::WorkerPool::GetTaskRunner(false)
->PostTask(FROM_HERE, base::Bind(&SimulatedProfileSocket, fds[0]));
scoped_ptr<dbus::FileDescriptor> fd(new dbus::FileDescriptor(fds[1]));
// Post the new connection to the service provider.
BluetoothProfileServiceProvider::Delegate::Options options;
profile_service_provider->NewConnection(
object_path, fd.Pass(), options,
base::Bind(&FakeBluetoothDeviceClient::ConnectionCallback,
base::Unretained(this), object_path, callback,
error_callback));
}
void FakeBluetoothDeviceClient::DisconnectProfile(
const dbus::ObjectPath& object_path,
const std::string& uuid,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "DisconnectProfile: " << object_path.value() << " " << uuid;
FakeBluetoothProfileManagerClient* fake_bluetooth_profile_manager_client =
static_cast<FakeBluetoothProfileManagerClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothProfileManagerClient());
FakeBluetoothProfileServiceProvider* profile_service_provider =
fake_bluetooth_profile_manager_client->GetProfileServiceProvider(uuid);
if (profile_service_provider == NULL) {
error_callback.Run(kNoResponseError, "Missing profile");
return;
}
profile_service_provider->RequestDisconnection(
object_path, base::Bind(&FakeBluetoothDeviceClient::DisconnectionCallback,
base::Unretained(this), object_path, callback,
error_callback));
}
void FakeBluetoothDeviceClient::Pair(const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "Pair: " << object_path.value();
Properties* properties = GetProperties(object_path);
if (properties->paired.value() == true) {
// Already paired.
callback.Run();
return;
}
SimulatePairing(object_path, false, callback, error_callback);
}
void FakeBluetoothDeviceClient::CancelPairing(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "CancelPairing: " << object_path.value();
pairing_cancelled_ = true;
callback.Run();
}
void FakeBluetoothDeviceClient::GetConnInfo(
const dbus::ObjectPath& object_path,
const ConnInfoCallback& callback,
const ErrorCallback& error_callback) {
Properties* properties = GetProperties(object_path);
if (!properties->connected.value()) {
error_callback.Run("org.bluez.Error.NotConnected", "Not Connected");
return;
}
callback.Run(connection_rssi_, transmit_power_, max_transmit_power_);
}
void FakeBluetoothDeviceClient::BeginDiscoverySimulation(
const dbus::ObjectPath& adapter_path) {
VLOG(1) << "starting discovery simulation";
discovery_simulation_step_ = 1;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::DiscoverySimulationTimer,
base::Unretained(this)),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
void FakeBluetoothDeviceClient::EndDiscoverySimulation(
const dbus::ObjectPath& adapter_path) {
VLOG(1) << "stopping discovery simulation";
discovery_simulation_step_ = 0;
}
void FakeBluetoothDeviceClient::BeginIncomingPairingSimulation(
const dbus::ObjectPath& adapter_path) {
VLOG(1) << "starting incoming pairing simulation";
incoming_pairing_simulation_step_ = 1;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::IncomingPairingSimulationTimer,
base::Unretained(this)),
base::TimeDelta::FromMilliseconds(
kIncomingSimulationStartPairTimeMultiplier *
simulation_interval_ms_));
}
void FakeBluetoothDeviceClient::EndIncomingPairingSimulation(
const dbus::ObjectPath& adapter_path) {
VLOG(1) << "stopping incoming pairing simulation";
incoming_pairing_simulation_step_ = 0;
}
void FakeBluetoothDeviceClient::SetSimulationIntervalMs(int interval_ms) {
simulation_interval_ms_ = interval_ms;
}
void FakeBluetoothDeviceClient::CreateDevice(
const dbus::ObjectPath& adapter_path,
const dbus::ObjectPath& device_path) {
if (std::find(device_list_.begin(), device_list_.end(), device_path) !=
device_list_.end())
return;
scoped_ptr<Properties> properties(
new Properties(base::Bind(&FakeBluetoothDeviceClient::OnPropertyChanged,
base::Unretained(this), device_path)));
properties->adapter.ReplaceValue(adapter_path);
if (device_path == dbus::ObjectPath(kLegacyAutopairPath)) {
properties->address.ReplaceValue(kLegacyAutopairAddress);
properties->bluetooth_class.ReplaceValue(kLegacyAutopairClass);
properties->name.ReplaceValue("LegacyAutopair");
properties->alias.ReplaceValue(kLegacyAutopairName);
std::vector<std::string> uuids;
uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
properties->uuids.ReplaceValue(uuids);
} else if (device_path == dbus::ObjectPath(kDisplayPinCodePath)) {
properties->address.ReplaceValue(kDisplayPinCodeAddress);
properties->bluetooth_class.ReplaceValue(kDisplayPinCodeClass);
properties->name.ReplaceValue("DisplayPinCode");
properties->alias.ReplaceValue(kDisplayPinCodeName);
std::vector<std::string> uuids;
uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
properties->uuids.ReplaceValue(uuids);
} else if (device_path == dbus::ObjectPath(kVanishingDevicePath)) {
properties->address.ReplaceValue(kVanishingDeviceAddress);
properties->bluetooth_class.ReplaceValue(kVanishingDeviceClass);
properties->name.ReplaceValue("VanishingDevice");
properties->alias.ReplaceValue(kVanishingDeviceName);
} else if (device_path == dbus::ObjectPath(kConnectUnpairablePath)) {
properties->address.ReplaceValue(kConnectUnpairableAddress);
properties->bluetooth_class.ReplaceValue(kConnectUnpairableClass);
properties->name.ReplaceValue("ConnectUnpairable");
properties->alias.ReplaceValue(kConnectUnpairableName);
std::vector<std::string> uuids;
uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
properties->uuids.ReplaceValue(uuids);
} else if (device_path == dbus::ObjectPath(kDisplayPasskeyPath)) {
properties->address.ReplaceValue(kDisplayPasskeyAddress);
properties->bluetooth_class.ReplaceValue(kDisplayPasskeyClass);
properties->name.ReplaceValue("DisplayPasskey");
properties->alias.ReplaceValue(kDisplayPasskeyName);
std::vector<std::string> uuids;
uuids.push_back("00001124-0000-1000-8000-00805f9b34fb");
properties->uuids.ReplaceValue(uuids);
} else if (device_path == dbus::ObjectPath(kRequestPinCodePath)) {
properties->address.ReplaceValue(kRequestPinCodeAddress);
properties->bluetooth_class.ReplaceValue(kRequestPinCodeClass);
properties->name.ReplaceValue("RequestPinCode");
properties->alias.ReplaceValue(kRequestPinCodeName);
} else if (device_path == dbus::ObjectPath(kConfirmPasskeyPath)) {
properties->address.ReplaceValue(kConfirmPasskeyAddress);
properties->bluetooth_class.ReplaceValue(kConfirmPasskeyClass);
properties->name.ReplaceValue("ConfirmPasskey");
properties->alias.ReplaceValue(kConfirmPasskeyName);
} else if (device_path == dbus::ObjectPath(kRequestPasskeyPath)) {
properties->address.ReplaceValue(kRequestPasskeyAddress);
properties->bluetooth_class.ReplaceValue(kRequestPasskeyClass);
properties->name.ReplaceValue("RequestPasskey");
properties->alias.ReplaceValue(kRequestPasskeyName);
} else if (device_path == dbus::ObjectPath(kUnconnectableDevicePath)) {
properties->address.ReplaceValue(kUnconnectableDeviceAddress);
properties->bluetooth_class.ReplaceValue(kUnconnectableDeviceClass);
properties->name.ReplaceValue("UnconnectableDevice");
properties->alias.ReplaceValue(kUnconnectableDeviceName);
} else if (device_path == dbus::ObjectPath(kUnpairableDevicePath)) {
properties->address.ReplaceValue(kUnpairableDeviceAddress);
properties->bluetooth_class.ReplaceValue(kUnpairableDeviceClass);
properties->name.ReplaceValue("Fake Unpairable Device");
properties->alias.ReplaceValue(kUnpairableDeviceName);
} else if (device_path == dbus::ObjectPath(kJustWorksPath)) {
properties->address.ReplaceValue(kJustWorksAddress);
properties->bluetooth_class.ReplaceValue(kJustWorksClass);
properties->name.ReplaceValue("JustWorks");
properties->alias.ReplaceValue(kJustWorksName);
} else if (device_path == dbus::ObjectPath(kLowEnergyPath)) {
properties->address.ReplaceValue(kLowEnergyAddress);
properties->bluetooth_class.ReplaceValue(kLowEnergyClass);
properties->name.ReplaceValue("Heart Rate Monitor");
properties->alias.ReplaceValue(kLowEnergyName);
std::vector<std::string> uuids;
uuids.push_back(FakeBluetoothGattServiceClient::kHeartRateServiceUUID);
properties->uuids.ReplaceValue(uuids);
} else if (device_path ==
dbus::ObjectPath(kConnectedTrustedNotPairedDevicePath)) {
properties->address.ReplaceValue(kConnectedTrustedNotPairedDeviceAddress);
properties->bluetooth_class.ReplaceValue(
kConnectedTrustedNotPairedDeviceClass);
properties->trusted.ReplaceValue(true);
properties->connected.ReplaceValue(true);
properties->paired.ReplaceValue(false);
properties->name.ReplaceValue("Connected Pairable Device");
properties->alias.ReplaceValue(kConnectedTrustedNotPairedDeviceName);
} else {
NOTREACHED();
}
properties_map_.insert(device_path, properties.Pass());
device_list_.push_back(device_path);
FOR_EACH_OBSERVER(BluetoothDeviceClient::Observer, observers_,
DeviceAdded(device_path));
}
void FakeBluetoothDeviceClient::CreateDeviceWithProperties(
const dbus::ObjectPath& adapter_path,
const IncomingDeviceProperties& props) {
dbus::ObjectPath device_path(props.device_path);
if (std::find(device_list_.begin(), device_list_.end(), device_path) !=
device_list_.end())
return;
scoped_ptr<Properties> properties(
new Properties(base::Bind(&FakeBluetoothDeviceClient::OnPropertyChanged,
base::Unretained(this), device_path)));
properties->adapter.ReplaceValue(adapter_path);
properties->name.ReplaceValue(props.device_name);
properties->alias.ReplaceValue(props.device_alias);
properties->address.ReplaceValue(props.device_address);
properties->bluetooth_class.ReplaceValue(props.device_class);
properties->trusted.ReplaceValue(props.is_trusted);
if (props.is_trusted)
properties->paired.ReplaceValue(true);
scoped_ptr<SimulatedPairingOptions> options(new SimulatedPairingOptions);
options->pairing_method = props.pairing_method;
options->pairing_auth_token = props.pairing_auth_token;
options->pairing_action = props.pairing_action;
options->incoming = props.incoming;
properties_map_.insert(device_path, properties.Pass());
device_list_.push_back(device_path);
pairing_options_map_.insert(device_path, options.Pass());
FOR_EACH_OBSERVER(BluetoothDeviceClient::Observer, observers_,
DeviceAdded(device_path));
}
scoped_ptr<base::ListValue>
FakeBluetoothDeviceClient::GetBluetoothDevicesAsDictionaries() const {
scoped_ptr<base::ListValue> predefined_devices(new base::ListValue);
scoped_ptr<base::DictionaryValue> pairedDevice(new base::DictionaryValue);
pairedDevice->SetString("path", kPairedDevicePath);
pairedDevice->SetString("address", kPairedDeviceAddress);
pairedDevice->SetString("name", kPairedDeviceName);
pairedDevice->SetString("alias", kPairedDeviceName);
pairedDevice->SetString("pairingMethod", "");
pairedDevice->SetString("pairingAuthToken", "");
pairedDevice->SetString("pairingAction", "");
pairedDevice->SetInteger("classValue", kPairedDeviceClass);
pairedDevice->SetBoolean("discoverable", true);
pairedDevice->SetBoolean("isTrusted", true);
pairedDevice->SetBoolean("paired", true);
pairedDevice->SetBoolean("incoming", false);
predefined_devices->Append(pairedDevice.Pass());
scoped_ptr<base::DictionaryValue> legacyDevice(new base::DictionaryValue);
legacyDevice->SetString("path", kLegacyAutopairPath);
legacyDevice->SetString("address", kLegacyAutopairAddress);
legacyDevice->SetString("name", kLegacyAutopairName);
legacyDevice->SetString("alias", kLegacyAutopairName);
legacyDevice->SetString("pairingMethod", "");
legacyDevice->SetString("pairingAuthToken", "");
legacyDevice->SetString("pairingAction", "");
legacyDevice->SetInteger("classValue", kLegacyAutopairClass);
legacyDevice->SetBoolean("isTrusted", true);
legacyDevice->SetBoolean("discoverable", false);
legacyDevice->SetBoolean("paired", false);
legacyDevice->SetBoolean("incoming", false);
predefined_devices->Append(legacyDevice.Pass());
scoped_ptr<base::DictionaryValue> pin(new base::DictionaryValue);
pin->SetString("path", kDisplayPinCodePath);
pin->SetString("address", kDisplayPinCodeAddress);
pin->SetString("name", kDisplayPinCodeName);
pin->SetString("alias", kDisplayPinCodeName);
pin->SetString("pairingMethod", kPairingMethodPinCode);
pin->SetString("pairingAuthToken", kTestPinCode);
pin->SetString("pairingAction", kPairingActionDisplay);
pin->SetInteger("classValue", kDisplayPinCodeClass);
pin->SetBoolean("isTrusted", false);
pin->SetBoolean("discoverable", false);
pin->SetBoolean("paired", false);
pin->SetBoolean("incoming", false);
predefined_devices->Append(pin.Pass());
scoped_ptr<base::DictionaryValue> vanishing(new base::DictionaryValue);
vanishing->SetString("path", kVanishingDevicePath);
vanishing->SetString("address", kVanishingDeviceAddress);
vanishing->SetString("name", kVanishingDeviceName);
vanishing->SetString("alias", kVanishingDeviceName);
vanishing->SetString("pairingMethod", "");
vanishing->SetString("pairingAuthToken", "");
vanishing->SetString("pairingAction", "");
vanishing->SetInteger("classValue", kVanishingDeviceClass);
vanishing->SetBoolean("isTrusted", false);
vanishing->SetBoolean("discoverable", false);
vanishing->SetBoolean("paired", false);
vanishing->SetBoolean("incoming", false);
predefined_devices->Append(vanishing.Pass());
scoped_ptr<base::DictionaryValue> connect_unpairable(
new base::DictionaryValue);
connect_unpairable->SetString("path", kConnectUnpairablePath);
connect_unpairable->SetString("address", kConnectUnpairableAddress);
connect_unpairable->SetString("name", kConnectUnpairableName);
connect_unpairable->SetString("pairingMethod", "");
connect_unpairable->SetString("pairingAuthToken", "");
connect_unpairable->SetString("pairingAction", "");
connect_unpairable->SetString("alias", kConnectUnpairableName);
connect_unpairable->SetInteger("classValue", kConnectUnpairableClass);
connect_unpairable->SetBoolean("isTrusted", false);
connect_unpairable->SetBoolean("discoverable", false);
connect_unpairable->SetBoolean("paired", false);
connect_unpairable->SetBoolean("incoming", false);
predefined_devices->Append(connect_unpairable.Pass());
scoped_ptr<base::DictionaryValue> passkey(new base::DictionaryValue);
passkey->SetString("path", kDisplayPasskeyPath);
passkey->SetString("address", kDisplayPasskeyAddress);
passkey->SetString("name", kDisplayPasskeyName);
passkey->SetString("alias", kDisplayPasskeyName);
passkey->SetString("pairingMethod", kPairingMethodPassKey);
passkey->SetInteger("pairingAuthToken", kTestPassKey);
passkey->SetString("pairingAction", kPairingActionDisplay);
passkey->SetInteger("classValue", kDisplayPasskeyClass);
passkey->SetBoolean("isTrusted", false);
passkey->SetBoolean("discoverable", false);
passkey->SetBoolean("paired", false);
passkey->SetBoolean("incoming", false);
predefined_devices->Append(passkey.Pass());
scoped_ptr<base::DictionaryValue> request_pin(new base::DictionaryValue);
request_pin->SetString("path", kRequestPinCodePath);
request_pin->SetString("address", kRequestPinCodeAddress);
request_pin->SetString("name", kRequestPinCodeName);
request_pin->SetString("alias", kRequestPinCodeName);
request_pin->SetString("pairingMethod", "");
request_pin->SetString("pairingAuthToken", "");
request_pin->SetString("pairingAction", kPairingActionRequest);
request_pin->SetInteger("classValue", kRequestPinCodeClass);
request_pin->SetBoolean("isTrusted", false);
request_pin->SetBoolean("discoverable", false);
request_pin->SetBoolean("paired", false);
request_pin->SetBoolean("incoming", false);
predefined_devices->Append(request_pin.Pass());
scoped_ptr<base::DictionaryValue> confirm(new base::DictionaryValue);
confirm->SetString("path", kConfirmPasskeyPath);
confirm->SetString("address", kConfirmPasskeyAddress);
confirm->SetString("name", kConfirmPasskeyName);
confirm->SetString("alias", kConfirmPasskeyName);
confirm->SetString("pairingMethod", "");
confirm->SetInteger("pairingAuthToken", kTestPassKey);
confirm->SetString("pairingAction", kPairingActionConfirmation);
confirm->SetInteger("classValue", kConfirmPasskeyClass);
confirm->SetBoolean("isTrusted", false);
confirm->SetBoolean("discoverable", false);
confirm->SetBoolean("paired", false);
confirm->SetBoolean("incoming", false);
predefined_devices->Append(confirm.Pass());
scoped_ptr<base::DictionaryValue> request_passkey(new base::DictionaryValue);
request_passkey->SetString("path", kRequestPasskeyPath);
request_passkey->SetString("address", kRequestPasskeyAddress);
request_passkey->SetString("name", kRequestPasskeyName);
request_passkey->SetString("alias", kRequestPasskeyName);
request_passkey->SetString("pairingMethod", kPairingMethodPassKey);
request_passkey->SetString("pairingAction", kPairingActionRequest);
request_passkey->SetInteger("pairingAuthToken", kTestPassKey);
request_passkey->SetInteger("classValue", kRequestPasskeyClass);
request_passkey->SetBoolean("isTrusted", false);
request_passkey->SetBoolean("discoverable", false);
request_passkey->SetBoolean("paired", false);
request_passkey->SetBoolean("incoming", false);
predefined_devices->Append(request_passkey.Pass());
scoped_ptr<base::DictionaryValue> unconnectable(new base::DictionaryValue);
unconnectable->SetString("path", kUnconnectableDevicePath);
unconnectable->SetString("address", kUnconnectableDeviceAddress);
unconnectable->SetString("name", kUnconnectableDeviceName);
unconnectable->SetString("alias", kUnconnectableDeviceName);
unconnectable->SetString("pairingMethod", "");
unconnectable->SetString("pairingAuthToken", "");
unconnectable->SetString("pairingAction", "");
unconnectable->SetInteger("classValue", kUnconnectableDeviceClass);
unconnectable->SetBoolean("isTrusted", true);
unconnectable->SetBoolean("discoverable", false);
unconnectable->SetBoolean("paired", false);
unconnectable->SetBoolean("incoming", false);
predefined_devices->Append(unconnectable.Pass());
scoped_ptr<base::DictionaryValue> unpairable(new base::DictionaryValue);
unpairable->SetString("path", kUnpairableDevicePath);
unpairable->SetString("address", kUnpairableDeviceAddress);
unpairable->SetString("name", kUnpairableDeviceName);
unpairable->SetString("alias", kUnpairableDeviceName);
unpairable->SetString("pairingMethod", "");
unpairable->SetString("pairingAuthToken", "");
unpairable->SetString("pairingAction", kPairingActionFail);
unpairable->SetInteger("classValue", kUnpairableDeviceClass);
unpairable->SetBoolean("isTrusted", false);
unpairable->SetBoolean("discoverable", false);
unpairable->SetBoolean("paired", false);
unpairable->SetBoolean("incoming", false);
predefined_devices->Append(unpairable.Pass());
scoped_ptr<base::DictionaryValue> just_works(new base::DictionaryValue);
just_works->SetString("path", kJustWorksPath);
just_works->SetString("address", kJustWorksAddress);
just_works->SetString("name", kJustWorksName);
just_works->SetString("alias", kJustWorksName);
just_works->SetString("pairingMethod", "");
just_works->SetString("pairingAuthToken", "");
just_works->SetString("pairingAction", "");
just_works->SetInteger("classValue", kJustWorksClass);
just_works->SetBoolean("isTrusted", false);
just_works->SetBoolean("discoverable", false);
just_works->SetBoolean("paired", false);
just_works->SetBoolean("incoming", false);
predefined_devices->Append(just_works.Pass());
scoped_ptr<base::DictionaryValue> low_energy(new base::DictionaryValue);
low_energy->SetString("path", kLowEnergyPath);
low_energy->SetString("address", kLowEnergyAddress);
low_energy->SetString("name", kLowEnergyName);
low_energy->SetString("alias", kLowEnergyName);
low_energy->SetString("pairingMethod", "");
low_energy->SetString("pairingAuthToken", "");
low_energy->SetString("pairingAction", "");
low_energy->SetInteger("classValue", kLowEnergyClass);
low_energy->SetBoolean("isTrusted", false);
low_energy->SetBoolean("discoverable", false);
low_energy->SetBoolean("paireed", false);
low_energy->SetBoolean("incoming", false);
predefined_devices->Append(low_energy.Pass());
scoped_ptr<base::DictionaryValue> paired_unconnectable(
new base::DictionaryValue);
paired_unconnectable->SetString("path", kPairedUnconnectableDevicePath);
paired_unconnectable->SetString("address", kPairedUnconnectableDeviceAddress);
paired_unconnectable->SetString("name", kPairedUnconnectableDeviceName);
paired_unconnectable->SetString("pairingMethod", "");
paired_unconnectable->SetString("pairingAuthToken", "");
paired_unconnectable->SetString("pairingAction", "");
paired_unconnectable->SetString("alias", kPairedUnconnectableDeviceName);
paired_unconnectable->SetInteger("classValue",
kPairedUnconnectableDeviceClass);
paired_unconnectable->SetBoolean("isTrusted", false);
paired_unconnectable->SetBoolean("discoverable", true);
paired_unconnectable->SetBoolean("paired", true);
paired_unconnectable->SetBoolean("incoming", false);
predefined_devices->Append(paired_unconnectable.Pass());
scoped_ptr<base::DictionaryValue> connected_trusted_not_paired(
new base::DictionaryValue);
connected_trusted_not_paired->SetString("path",
kConnectedTrustedNotPairedDevicePath);
connected_trusted_not_paired->SetString(
"address", kConnectedTrustedNotPairedDeviceAddress);
connected_trusted_not_paired->SetString("name",
kConnectedTrustedNotPairedDeviceName);
connected_trusted_not_paired->SetString("pairingMethod", "");
connected_trusted_not_paired->SetString("pairingAuthToken", "");
connected_trusted_not_paired->SetString("pairingAction", "");
connected_trusted_not_paired->SetString("alias",
kConnectedTrustedNotPairedDeviceName);
connected_trusted_not_paired->SetInteger(
"classValue", kConnectedTrustedNotPairedDeviceClass);
connected_trusted_not_paired->SetBoolean("isTrusted", true);
connected_trusted_not_paired->SetBoolean("discoverable", true);
connected_trusted_not_paired->SetBoolean("paired", false);
connected_trusted_not_paired->SetBoolean("incoming", false);
predefined_devices->Append(connected_trusted_not_paired.Pass());
return predefined_devices.Pass();
}
void FakeBluetoothDeviceClient::RemoveDevice(
const dbus::ObjectPath& adapter_path,
const dbus::ObjectPath& device_path) {
std::vector<dbus::ObjectPath>::iterator listiter =
std::find(device_list_.begin(), device_list_.end(), device_path);
if (listiter == device_list_.end())
return;
PropertiesMap::const_iterator iter = properties_map_.find(device_path);
Properties* properties = iter->second;
VLOG(1) << "removing device: " << properties->alias.value();
device_list_.erase(listiter);
// Remove the Input interface if it exists. This should be called before the
// BluetoothDeviceClient::Observer::DeviceRemoved because it deletes the
// BluetoothDeviceChromeOS object, including the device_path referenced here.
FakeBluetoothInputClient* fake_bluetooth_input_client =
static_cast<FakeBluetoothInputClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothInputClient());
fake_bluetooth_input_client->RemoveInputDevice(device_path);
if (device_path == dbus::ObjectPath(kLowEnergyPath)) {
FakeBluetoothGattServiceClient* gatt_service_client =
static_cast<FakeBluetoothGattServiceClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothGattServiceClient());
gatt_service_client->HideHeartRateService();
}
FOR_EACH_OBSERVER(BluetoothDeviceClient::Observer, observers_,
DeviceRemoved(device_path));
properties_map_.erase(iter);
PairingOptionsMap::const_iterator options_iter =
pairing_options_map_.find(device_path);
if (options_iter != pairing_options_map_.end()) {
pairing_options_map_.erase(options_iter);
}
}
void FakeBluetoothDeviceClient::OnPropertyChanged(
const dbus::ObjectPath& object_path,
const std::string& property_name) {
VLOG(2) << "Fake Bluetooth device property changed: " << object_path.value()
<< ": " << property_name;
FOR_EACH_OBSERVER(BluetoothDeviceClient::Observer, observers_,
DevicePropertyChanged(object_path, property_name));
}
void FakeBluetoothDeviceClient::DiscoverySimulationTimer() {
if (!discovery_simulation_step_)
return;
// Timer fires every .75s, the numbers below are arbitrary to give a feel
// for a discovery process.
VLOG(1) << "discovery simulation, step " << discovery_simulation_step_;
if (discovery_simulation_step_ == 2) {
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kLegacyAutopairPath));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kLowEnergyPath));
} else if (discovery_simulation_step_ == 4) {
UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
base::RandInt(kMinRSSI, kMaxRSSI));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kDisplayPinCodePath));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kVanishingDevicePath));
} else if (discovery_simulation_step_ == 7) {
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kConnectUnpairablePath));
UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
base::RandInt(kMinRSSI, kMaxRSSI));
} else if (discovery_simulation_step_ == 8) {
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kDisplayPasskeyPath));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kRequestPinCodePath));
UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
base::RandInt(kMinRSSI, kMaxRSSI));
} else if (discovery_simulation_step_ == 10) {
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kConfirmPasskeyPath));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kRequestPasskeyPath));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kUnconnectableDevicePath));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kUnpairableDevicePath));
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kJustWorksPath));
UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
base::RandInt(kMinRSSI, kMaxRSSI));
} else if (discovery_simulation_step_ == 13) {
UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
base::RandInt(kMinRSSI, kMaxRSSI));
RemoveDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kVanishingDevicePath));
} else if (discovery_simulation_step_ == 14) {
UpdateDeviceRSSI(dbus::ObjectPath(kLowEnergyPath),
base::RandInt(kMinRSSI, kMaxRSSI));
return;
}
++discovery_simulation_step_;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::DiscoverySimulationTimer,
base::Unretained(this)),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
void FakeBluetoothDeviceClient::IncomingPairingSimulationTimer() {
if (!incoming_pairing_simulation_step_)
return;
VLOG(1) << "incoming pairing simulation, step "
<< incoming_pairing_simulation_step_;
switch (incoming_pairing_simulation_step_) {
case 1:
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kConfirmPasskeyPath));
SimulatePairing(dbus::ObjectPath(kConfirmPasskeyPath), true,
base::Bind(&base::DoNothing),
base::Bind(&SimpleErrorCallback));
break;
case 2:
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kJustWorksPath));
SimulatePairing(dbus::ObjectPath(kJustWorksPath), true,
base::Bind(&base::DoNothing),
base::Bind(&SimpleErrorCallback));
break;
case 3:
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kDisplayPinCodePath));
SimulatePairing(dbus::ObjectPath(kDisplayPinCodePath), true,
base::Bind(&base::DoNothing),
base::Bind(&SimpleErrorCallback));
break;
case 4:
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kDisplayPasskeyPath));
SimulatePairing(dbus::ObjectPath(kDisplayPasskeyPath), true,
base::Bind(&base::DoNothing),
base::Bind(&SimpleErrorCallback));
break;
case 5:
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kRequestPinCodePath));
SimulatePairing(dbus::ObjectPath(kRequestPinCodePath), true,
base::Bind(&base::DoNothing),
base::Bind(&SimpleErrorCallback));
break;
case 6:
CreateDevice(dbus::ObjectPath(FakeBluetoothAdapterClient::kAdapterPath),
dbus::ObjectPath(kRequestPasskeyPath));
SimulatePairing(dbus::ObjectPath(kRequestPasskeyPath), true,
base::Bind(&base::DoNothing),
base::Bind(&SimpleErrorCallback));
break;
default:
return;
}
++incoming_pairing_simulation_step_;
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::IncomingPairingSimulationTimer,
base::Unretained(this)),
base::TimeDelta::FromMilliseconds(kIncomingSimulationPairTimeMultiplier *
simulation_interval_ms_));
}
void FakeBluetoothDeviceClient::SimulatePairing(
const dbus::ObjectPath& object_path,
bool incoming_request,
const base::Closure& callback,
const ErrorCallback& error_callback) {
pairing_cancelled_ = false;
FakeBluetoothAgentManagerClient* fake_bluetooth_agent_manager_client =
static_cast<FakeBluetoothAgentManagerClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothAgentManagerClient());
FakeBluetoothAgentServiceProvider* agent_service_provider =
fake_bluetooth_agent_manager_client->GetAgentServiceProvider();
CHECK(agent_service_provider != NULL);
// Grab the device's pairing properties.
PairingOptionsMap::const_iterator iter =
pairing_options_map_.find(object_path);
// If the device with path |object_path| has simulated pairing properties
// defined, then pair it based on its |pairing_method|.
if (iter != pairing_options_map_.end()) {
if (iter->second->pairing_action == kPairingActionFail) {
// Fails the pairing with an org.bluez.Error.Failed error.
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::FailSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else if (iter->second->pairing_method == kPairingMethodNone ||
iter->second->pairing_method.empty()) {
if (!iter->second->incoming) {
// Simply pair and connect the device.
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(
kSimulateNormalPairTimeMultiplier * simulation_interval_ms_));
} else {
agent_service_provider->RequestAuthorization(
object_path,
base::Bind(&FakeBluetoothDeviceClient::ConfirmationCallback,
base::Unretained(this), object_path, callback,
error_callback));
}
} else if (iter->second->pairing_method == kPairingMethodPinCode) {
if (iter->second->pairing_action == kPairingActionDisplay) {
// Display a Pincode, and wait before acting as if the other end
// accepted it.
agent_service_provider->DisplayPinCode(
object_path, iter->second->pairing_auth_token);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(kPinCodeDevicePairTimeMultiplier *
simulation_interval_ms_));
} else if (iter->second->pairing_action == kPairingActionRequest) {
// Request a pin code.
agent_service_provider->RequestPinCode(
object_path, base::Bind(&FakeBluetoothDeviceClient::PinCodeCallback,
base::Unretained(this), object_path,
callback, error_callback));
} else if (iter->second->pairing_action == kPairingActionConfirmation) {
error_callback.Run(kNoResponseError, "No confirm for pincode pairing.");
}
} else if (iter->second->pairing_method == kPairingMethodPassKey) {
// Display a passkey, and each interval act as if another key was entered
// for it.
if (iter->second->pairing_action == kPairingActionDisplay) {
agent_service_provider->DisplayPasskey(
object_path, std::stoi(iter->second->pairing_auth_token), 0);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&FakeBluetoothDeviceClient::SimulateKeypress,
base::Unretained(this), 1, object_path,
callback, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else if (iter->second->pairing_action == kPairingActionRequest) {
agent_service_provider->RequestPasskey(
object_path, base::Bind(&FakeBluetoothDeviceClient::PasskeyCallback,
base::Unretained(this), object_path,
callback, error_callback));
} else if (iter->second->pairing_action == kPairingActionConfirmation) {
agent_service_provider->RequestConfirmation(
object_path, std::stoi(iter->second->pairing_auth_token),
base::Bind(&FakeBluetoothDeviceClient::ConfirmationCallback,
base::Unretained(this), object_path, callback,
error_callback));
}
}
} else {
if (object_path == dbus::ObjectPath(kLegacyAutopairPath) ||
object_path == dbus::ObjectPath(kConnectUnpairablePath) ||
object_path == dbus::ObjectPath(kUnconnectableDevicePath) ||
object_path == dbus::ObjectPath(kLowEnergyPath)) {
// No need to call anything on the pairing delegate, just wait 3 times
// the interval before acting as if the other end accepted it.
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(kSimulateNormalPairTimeMultiplier *
simulation_interval_ms_));
} else if (object_path == dbus::ObjectPath(kDisplayPinCodePath)) {
// Display a Pincode, and wait before acting as if the other end accepted
// it.
agent_service_provider->DisplayPinCode(object_path, kTestPinCode);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(kPinCodeDevicePairTimeMultiplier *
simulation_interval_ms_));
} else if (object_path == dbus::ObjectPath(kVanishingDevicePath)) {
// The vanishing device simulates being too far away, and thus times out.
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::TimeoutSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(kVanishingDevicePairTimeMultiplier *
simulation_interval_ms_));
} else if (object_path == dbus::ObjectPath(kDisplayPasskeyPath)) {
// Display a passkey, and each interval act as if another key was entered
// for it.
agent_service_provider->DisplayPasskey(object_path, kTestPassKey, 0);
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&FakeBluetoothDeviceClient::SimulateKeypress,
base::Unretained(this), 1, object_path,
callback, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else if (object_path == dbus::ObjectPath(kRequestPinCodePath)) {
// Request a Pincode.
agent_service_provider->RequestPinCode(
object_path, base::Bind(&FakeBluetoothDeviceClient::PinCodeCallback,
base::Unretained(this), object_path, callback,
error_callback));
} else if (object_path == dbus::ObjectPath(kConfirmPasskeyPath) ||
object_path ==
dbus::ObjectPath(kConnectedTrustedNotPairedDevicePath)) {
// Request confirmation of a Passkey.
agent_service_provider->RequestConfirmation(
object_path, kTestPassKey,
base::Bind(&FakeBluetoothDeviceClient::ConfirmationCallback,
base::Unretained(this), object_path, callback,
error_callback));
} else if (object_path == dbus::ObjectPath(kRequestPasskeyPath)) {
// Request a Passkey from the user.
agent_service_provider->RequestPasskey(
object_path, base::Bind(&FakeBluetoothDeviceClient::PasskeyCallback,
base::Unretained(this), object_path, callback,
error_callback));
} else if (object_path == dbus::ObjectPath(kUnpairableDevicePath)) {
// Fails the pairing with an org.bluez.Error.Failed error.
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::FailSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else if (object_path == dbus::ObjectPath(kJustWorksPath)) {
if (incoming_request) {
agent_service_provider->RequestAuthorization(
object_path,
base::Bind(&FakeBluetoothDeviceClient::ConfirmationCallback,
base::Unretained(this), object_path, callback,
error_callback));
} else {
// No need to call anything on the pairing delegate, just wait before
// acting as if the other end accepted it.
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(
kSimulateNormalPairTimeMultiplier * simulation_interval_ms_));
}
} else {
error_callback.Run(kNoResponseError, "No pairing fake");
}
}
}
void FakeBluetoothDeviceClient::CompleteSimulatedPairing(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "CompleteSimulatedPairing: " << object_path.value();
if (pairing_cancelled_) {
pairing_cancelled_ = false;
error_callback.Run(bluetooth_device::kErrorAuthenticationCanceled,
"Cancelled");
} else {
Properties* properties = GetProperties(object_path);
properties->paired.ReplaceValue(true);
callback.Run();
AddInputDeviceIfNeeded(object_path, properties);
}
}
void FakeBluetoothDeviceClient::TimeoutSimulatedPairing(
const dbus::ObjectPath& object_path,
const ErrorCallback& error_callback) {
VLOG(1) << "TimeoutSimulatedPairing: " << object_path.value();
error_callback.Run(bluetooth_device::kErrorAuthenticationTimeout,
"Timed out");
}
void FakeBluetoothDeviceClient::CancelSimulatedPairing(
const dbus::ObjectPath& object_path,
const ErrorCallback& error_callback) {
VLOG(1) << "CancelSimulatedPairing: " << object_path.value();
error_callback.Run(bluetooth_device::kErrorAuthenticationCanceled,
"Canceled");
}
void FakeBluetoothDeviceClient::RejectSimulatedPairing(
const dbus::ObjectPath& object_path,
const ErrorCallback& error_callback) {
VLOG(1) << "RejectSimulatedPairing: " << object_path.value();
error_callback.Run(bluetooth_device::kErrorAuthenticationRejected,
"Rejected");
}
void FakeBluetoothDeviceClient::FailSimulatedPairing(
const dbus::ObjectPath& object_path,
const ErrorCallback& error_callback) {
VLOG(1) << "FailSimulatedPairing: " << object_path.value();
error_callback.Run(bluetooth_device::kErrorFailed, "Failed");
}
void FakeBluetoothDeviceClient::AddInputDeviceIfNeeded(
const dbus::ObjectPath& object_path,
Properties* properties) {
// If the paired device is a HID device based on it's bluetooth class,
// simulate the Input interface.
FakeBluetoothInputClient* fake_bluetooth_input_client =
static_cast<FakeBluetoothInputClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothInputClient());
if ((properties->bluetooth_class.value() & 0x001f03) == 0x000500)
fake_bluetooth_input_client->AddInputDevice(object_path);
}
void FakeBluetoothDeviceClient::UpdateDeviceRSSI(
const dbus::ObjectPath& object_path,
int16 rssi) {
PropertiesMap::const_iterator iter = properties_map_.find(object_path);
if (iter == properties_map_.end()) {
VLOG(2) << "Fake device does not exist: " << object_path.value();
return;
}
Properties* properties = iter->second;
DCHECK(properties);
properties->rssi.ReplaceValue(rssi);
}
void FakeBluetoothDeviceClient::UpdateConnectionInfo(
uint16 connection_rssi,
uint16 transmit_power,
uint16 max_transmit_power) {
connection_rssi_ = connection_rssi;
transmit_power_ = transmit_power;
max_transmit_power_ = max_transmit_power;
}
void FakeBluetoothDeviceClient::PinCodeCallback(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback,
BluetoothAgentServiceProvider::Delegate::Status status,
const std::string& pincode) {
VLOG(1) << "PinCodeCallback: " << object_path.value();
if (status == BluetoothAgentServiceProvider::Delegate::SUCCESS) {
PairingOptionsMap::const_iterator iter =
pairing_options_map_.find(object_path);
bool success = true;
// If the device has pairing options defined
if (iter != pairing_options_map_.end()) {
success = iter->second->pairing_auth_token == pincode;
}
if (success) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(kSimulateNormalPairTimeMultiplier *
simulation_interval_ms_));
} else {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
} else if (status == BluetoothAgentServiceProvider::Delegate::CANCELLED) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CancelSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else if (status == BluetoothAgentServiceProvider::Delegate::REJECTED) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
}
void FakeBluetoothDeviceClient::PasskeyCallback(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback,
BluetoothAgentServiceProvider::Delegate::Status status,
uint32 passkey) {
VLOG(1) << "PasskeyCallback: " << object_path.value();
if (status == BluetoothAgentServiceProvider::Delegate::SUCCESS) {
PairingOptionsMap::const_iterator iter =
pairing_options_map_.find(object_path);
bool success = true;
if (iter != pairing_options_map_.end()) {
success = static_cast<uint32>(
std::stoi(iter->second->pairing_auth_token)) == passkey;
}
if (success) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(kSimulateNormalPairTimeMultiplier *
simulation_interval_ms_));
} else {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
} else if (status == BluetoothAgentServiceProvider::Delegate::CANCELLED) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CancelSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else if (status == BluetoothAgentServiceProvider::Delegate::REJECTED) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
}
void FakeBluetoothDeviceClient::ConfirmationCallback(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback,
BluetoothAgentServiceProvider::Delegate::Status status) {
VLOG(1) << "ConfirmationCallback: " << object_path.value();
if (status == BluetoothAgentServiceProvider::Delegate::SUCCESS) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(kSimulateNormalPairTimeMultiplier *
simulation_interval_ms_));
} else if (status == BluetoothAgentServiceProvider::Delegate::CANCELLED) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CancelSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else if (status == BluetoothAgentServiceProvider::Delegate::REJECTED) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::RejectSimulatedPairing,
base::Unretained(this), object_path, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
}
void FakeBluetoothDeviceClient::SimulateKeypress(
uint16 entered,
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
VLOG(1) << "SimulateKeypress " << entered << ": " << object_path.value();
FakeBluetoothAgentManagerClient* fake_bluetooth_agent_manager_client =
static_cast<FakeBluetoothAgentManagerClient*>(
bluez::BluezDBusManager::Get()->GetBluetoothAgentManagerClient());
FakeBluetoothAgentServiceProvider* agent_service_provider =
fake_bluetooth_agent_manager_client->GetAgentServiceProvider();
// The agent service provider object could have been destroyed after the
// pairing is canceled.
if (!agent_service_provider)
return;
agent_service_provider->DisplayPasskey(object_path, kTestPassKey, entered);
if (entered < 7) {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE, base::Bind(&FakeBluetoothDeviceClient::SimulateKeypress,
base::Unretained(this), entered + 1, object_path,
callback, error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
} else {
base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
FROM_HERE,
base::Bind(&FakeBluetoothDeviceClient::CompleteSimulatedPairing,
base::Unretained(this), object_path, callback,
error_callback),
base::TimeDelta::FromMilliseconds(simulation_interval_ms_));
}
}
void FakeBluetoothDeviceClient::ConnectionCallback(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback,
BluetoothProfileServiceProvider::Delegate::Status status) {
VLOG(1) << "ConnectionCallback: " << object_path.value();
if (status == BluetoothProfileServiceProvider::Delegate::SUCCESS) {
callback.Run();
} else if (status == BluetoothProfileServiceProvider::Delegate::CANCELLED) {
// TODO(keybuk): tear down this side of the connection
error_callback.Run(bluetooth_device::kErrorFailed, "Canceled");
} else if (status == BluetoothProfileServiceProvider::Delegate::REJECTED) {
// TODO(keybuk): tear down this side of the connection
error_callback.Run(bluetooth_device::kErrorFailed, "Rejected");
}
}
void FakeBluetoothDeviceClient::DisconnectionCallback(
const dbus::ObjectPath& object_path,
const base::Closure& callback,
const ErrorCallback& error_callback,
BluetoothProfileServiceProvider::Delegate::Status status) {
VLOG(1) << "DisconnectionCallback: " << object_path.value();
if (status == BluetoothProfileServiceProvider::Delegate::SUCCESS) {
// TODO(keybuk): tear down this side of the connection
callback.Run();
} else if (status == BluetoothProfileServiceProvider::Delegate::CANCELLED) {
error_callback.Run(bluetooth_device::kErrorFailed, "Canceled");
} else if (status == BluetoothProfileServiceProvider::Delegate::REJECTED) {
error_callback.Run(bluetooth_device::kErrorFailed, "Rejected");
}
}
} // namespace bluez
| 43.191336 | 80 | 0.724632 | [
"object",
"vector"
] |
33db074a9b1b86d5b65e47e1da1290ce7dcce9a0 | 380 | hpp | C++ | src/noad/script.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | 4 | 2021-04-02T02:52:05.000Z | 2021-12-11T00:42:35.000Z | src/noad/script.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | null | null | null | src/noad/script.hpp | cpp-niel/mfl | d22d698b112b95d102150d5f3a5f35d8eb7fb0f3 | [
"MIT"
] | null | null | null | #pragma once
#include "noad/noad.hpp"
#include <optional>
#include <vector>
namespace mfl
{
struct script
{
std::vector<noad> nucleus;
std::optional<std::vector<noad>> sub;
std::optional<std::vector<noad>> sup;
};
struct settings;
struct hlist;
hlist script_to_hlist(const settings s, const cramping cramp, const script& sc);
} | 18.095238 | 84 | 0.642105 | [
"vector"
] |
33de86fb72f8eeac1c13c462ce132e7ffa0cd88f | 3,461 | c++ | C++ | c++/src/kj/refcount.c++ | MixusMinimax/capnproto | 48db1a9cda33bad8a89f8b0285a7843f19b27ee6 | [
"MIT"
] | 4,518 | 2017-06-06T15:33:15.000Z | 2022-03-31T16:43:23.000Z | c++/src/kj/refcount.c++ | seanwallawalla-forks/capnproto | 8009588ff84cbdf233f6d23d1d507462b050b427 | [
"MIT"
] | 718 | 2017-06-05T22:58:24.000Z | 2022-03-24T03:05:45.000Z | c++/src/kj/refcount.c++ | seanwallawalla-forks/capnproto | 8009588ff84cbdf233f6d23d1d507462b050b427 | [
"MIT"
] | 492 | 2017-06-07T08:40:53.000Z | 2022-03-30T20:57:05.000Z | // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "refcount.h"
#include "debug.h"
#if _MSC_VER && !defined(__clang__)
// Annoyingly, MSVC only implements the C++ atomic libs, not the C libs, so the only useful
// thing we can get from <atomic> seems to be atomic_thread_fence... but that one function is
// indeed not implemented by the intrinsics, so...
#include <atomic>
#endif
namespace kj {
// =======================================================================================
// Non-atomic (thread-unsafe) refcounting
Refcounted::~Refcounted() noexcept(false) {
KJ_ASSERT(refcount == 0, "Refcounted object deleted with non-zero refcount.");
}
void Refcounted::disposeImpl(void* pointer) const {
if (--refcount == 0) {
delete this;
}
}
// =======================================================================================
// Atomic (thread-safe) refcounting
AtomicRefcounted::~AtomicRefcounted() noexcept(false) {
KJ_ASSERT(refcount == 0, "Refcounted object deleted with non-zero refcount.");
}
void AtomicRefcounted::disposeImpl(void* pointer) const {
#if _MSC_VER && !defined(__clang__)
if (KJ_MSVC_INTERLOCKED(Decrement, rel)(&refcount) == 0) {
std::atomic_thread_fence(std::memory_order_acquire);
delete this;
}
#else
if (__atomic_sub_fetch(&refcount, 1, __ATOMIC_RELEASE) == 0) {
__atomic_thread_fence(__ATOMIC_ACQUIRE);
delete this;
}
#endif
}
bool AtomicRefcounted::addRefWeakInternal() const {
#if _MSC_VER && !defined(__clang__)
long orig = refcount;
for (;;) {
if (orig == 0) {
// Refcount already hit zero. Destructor is already running so we can't revive the object.
return false;
}
unsigned long old = KJ_MSVC_INTERLOCKED(CompareExchange, nf)(&refcount, orig + 1, orig);
if (old == orig) {
return true;
}
orig = old;
}
#else
uint orig = __atomic_load_n(&refcount, __ATOMIC_RELAXED);
for (;;) {
if (orig == 0) {
// Refcount already hit zero. Destructor is already running so we can't revive the object.
return false;
}
if (__atomic_compare_exchange_n(&refcount, &orig, orig + 1, true,
__ATOMIC_RELAXED, __ATOMIC_RELAXED)) {
// Successfully incremented refcount without letting it hit zero.
return true;
}
}
#endif
}
} // namespace kj
| 33.601942 | 96 | 0.676105 | [
"object"
] |
33dfa27ae8a07e2a56b90599e91d4f29fc9dceef | 2,740 | hpp | C++ | public/Simple-XML/Worksheet-Row-Column-Titles.hpp | Lester-Dowling/Simple-XML | 0ed4fdd317743bf788acf2adc2782ae90e3ca0e6 | [
"MIT"
] | null | null | null | public/Simple-XML/Worksheet-Row-Column-Titles.hpp | Lester-Dowling/Simple-XML | 0ed4fdd317743bf788acf2adc2782ae90e3ca0e6 | [
"MIT"
] | null | null | null | public/Simple-XML/Worksheet-Row-Column-Titles.hpp | Lester-Dowling/Simple-XML | 0ed4fdd317743bf788acf2adc2782ae90e3ca0e6 | [
"MIT"
] | null | null | null | /**
* @file Simple-XML/Worksheet-Row-Column-Titles.hpp
* @date Started 2019-04-18
* @author Lester J. Dowling
*/
#pragma once
#include <string>
#include <map>
#include <utility>
#include <optional>
#include <stdexcept>
#include "Simple-XML/Row-Column-Titles.hpp"
#include "simple-xml_export.h"
namespace simple_xml {
using std::map;
using std::optional;
using std::runtime_error;
using std::string;
using std::to_string;
/**
* Keep all the titles of worksheets, rows and columns in a workbook.
*/
class SIMPLE_XML_EXPORT Worksheet_Row_Column_Titles {
/**
* A mapping from worksheet index to its row and column titles.
*/
map<int, Row_Column_Titles> m_wrc_titles;
int m_previous_wkt_idx = 0;
public: //~ Ctors -------------------------------------------------
Worksheet_Row_Column_Titles() = default;
public: //~ Mutators ----------------------------------------------
/**
* Add a new worksheet title at the given idx to the titles map.
*
* @param[in] wkt_idx The worksheet index within the XML file.
*
* @param[in] title The title of the worksheet.
*/
void add_worksheet(const int wkt_idx, const string title);
/**
* Add a new worksheet title at the idx of one plus the previous idx.
*
* @param[in] title The title of the worksheet.
*
* @return The idx of the added worksheet.
*/
int add_worksheet(const string title);
/**
* Remove all titles and restore the titles map to empty.
*/
void clear()
{
m_wrc_titles.clear();
m_previous_wkt_idx = 0;
}
public: //~ Accessors ---------------------------------------------
/**
* @return Is this data structure empty?
*/
bool empty() const noexcept { return m_wrc_titles.empty(); }
/**
* @return The number of worksheets in the titles map.
*/
size_t size() const noexcept { return m_wrc_titles.size(); }
/**
* @return The number of worksheets in the titles map.
*/
size_t wkt_count() const noexcept { return m_wrc_titles.size(); }
/**
* @return the Row-Columns Titles for the specified worksheet.
*/
Row_Column_Titles& operator()(const int wkt_idx);
Row_Column_Titles const& operator()(const int wkt_idx) const;
/**
* @return A sequence of all the worksheet indices in the titles map.
*/
vector<int> wkt_indices() const;
/**
* @return The title of the given worksheet.
*/
optional<string> wkt_title(const int wkt_idx) const;
/**
* @return A list of all the worksheet titles.
*/
vector<string> wkt_titles() const
{
vector<string> parsed_titles;
for (const int wkt_idx : wkt_indices()) {
parsed_titles.push_back(wkt_title(wkt_idx).value());
}
return parsed_titles;
}
};
} // namespace simple_xml
| 25.37037 | 71 | 0.639051 | [
"vector"
] |
33dfe952ce4548dffa1944e9e06c3de69ae154c9 | 7,767 | hpp | C++ | deps/include/SFML/Graphics/VertexArray.hpp | rohitrtk/Pong | ace1482a81cdb91f0c50eedf249c68945e4a864f | [
"MIT"
] | 79 | 2016-11-05T12:41:46.000Z | 2022-03-23T07:05:01.000Z | deps/include/SFML/Graphics/VertexArray.hpp | rohitrtk/Pong | ace1482a81cdb91f0c50eedf249c68945e4a864f | [
"MIT"
] | 14 | 2017-02-28T02:47:43.000Z | 2021-04-25T20:08:15.000Z | deps/include/SFML/Graphics/VertexArray.hpp | rohitrtk/Pong | ace1482a81cdb91f0c50eedf249c68945e4a864f | [
"MIT"
] | 29 | 2017-03-03T17:14:59.000Z | 2021-12-16T10:26:08.000Z | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2016 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_VERTEXARRAY_HPP
#define SFML_VERTEXARRAY_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/PrimitiveType.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <vector>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Define a set of one or more 2D primitives
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API VertexArray : public Drawable
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty vertex array.
///
////////////////////////////////////////////////////////////
VertexArray();
////////////////////////////////////////////////////////////
/// \brief Construct the vertex array with a type and an initial number of vertices
///
/// \param type Type of primitives
/// \param vertexCount Initial number of vertices in the array
///
////////////////////////////////////////////////////////////
explicit VertexArray(PrimitiveType type, std::size_t vertexCount = 0);
////////////////////////////////////////////////////////////
/// \brief Return the vertex count
///
/// \return Number of vertices in the array
///
////////////////////////////////////////////////////////////
std::size_t getVertexCount() const;
////////////////////////////////////////////////////////////
/// \brief Get a read-write access to a vertex by its index
///
/// This function doesn't check \a index, it must be in range
/// [0, getVertexCount() - 1]. The behavior is undefined
/// otherwise.
///
/// \param index Index of the vertex to get
///
/// \return Reference to the index-th vertex
///
/// \see getVertexCount
///
////////////////////////////////////////////////////////////
Vertex& operator [](std::size_t index);
////////////////////////////////////////////////////////////
/// \brief Get a read-only access to a vertex by its index
///
/// This function doesn't check \a index, it must be in range
/// [0, getVertexCount() - 1]. The behavior is undefined
/// otherwise.
///
/// \param index Index of the vertex to get
///
/// \return Const reference to the index-th vertex
///
/// \see getVertexCount
///
////////////////////////////////////////////////////////////
const Vertex& operator [](std::size_t index) const;
////////////////////////////////////////////////////////////
/// \brief Clear the vertex array
///
/// This function removes all the vertices from the array.
/// It doesn't deallocate the corresponding memory, so that
/// adding new vertices after clearing doesn't involve
/// reallocating all the memory.
///
////////////////////////////////////////////////////////////
void clear();
////////////////////////////////////////////////////////////
/// \brief Resize the vertex array
///
/// If \a vertexCount is greater than the current size, the previous
/// vertices are kept and new (default-constructed) vertices are
/// added.
/// If \a vertexCount is less than the current size, existing vertices
/// are removed from the array.
///
/// \param vertexCount New size of the array (number of vertices)
///
////////////////////////////////////////////////////////////
void resize(std::size_t vertexCount);
////////////////////////////////////////////////////////////
/// \brief Add a vertex to the array
///
/// \param vertex Vertex to add
///
////////////////////////////////////////////////////////////
void append(const Vertex& vertex);
////////////////////////////////////////////////////////////
/// \brief Set the type of primitives to draw
///
/// This function defines how the vertices must be interpreted
/// when it's time to draw them:
/// \li As points
/// \li As lines
/// \li As triangles
/// \li As quads
/// The default primitive type is sf::Points.
///
/// \param type Type of primitive
///
////////////////////////////////////////////////////////////
void setPrimitiveType(PrimitiveType type);
////////////////////////////////////////////////////////////
/// \brief Get the type of primitives drawn by the vertex array
///
/// \return Primitive type
///
////////////////////////////////////////////////////////////
PrimitiveType getPrimitiveType() const;
////////////////////////////////////////////////////////////
/// \brief Compute the bounding rectangle of the vertex array
///
/// This function returns the minimal axis-aligned rectangle
/// that contains all the vertices of the array.
///
/// \return Bounding rectangle of the vertex array
///
////////////////////////////////////////////////////////////
FloatRect getBounds() const;
private:
////////////////////////////////////////////////////////////
/// \brief Draw the vertex array to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
private:
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
std::vector<Vertex> m_vertices; ///< Vertices contained in the array
PrimitiveType m_primitiveType; ///< Type of primitives to draw
};
} // namespace sf
#endif // SFML_VERTEXARRAY_HPP
////////////////////////////////////////////////////////////
/// \class sf::VertexArray
/// \ingroup graphics
///
/// sf::VertexArray is a very simple wrapper around a dynamic
/// array of vertices and a primitives type.
///
/// It inherits sf::Drawable, but unlike other drawables it
/// is not transformable.
///
/// Example:
/// \code
/// sf::VertexArray lines(sf::LineStrip, 4);
/// lines[0].position = sf::Vector2f(10, 0);
/// lines[1].position = sf::Vector2f(20, 0);
/// lines[2].position = sf::Vector2f(30, 5);
/// lines[3].position = sf::Vector2f(40, 2);
///
/// window.draw(lines);
/// \endcode
///
/// \see sf::Vertex
///
////////////////////////////////////////////////////////////
| 34.674107 | 101 | 0.470838 | [
"render",
"vector"
] |
33e2798fe025f3251de6e8c19fccaf26bcd7f2d8 | 43,718 | cc | C++ | engine/source/sim/simObject.cc | pchan126/Torque2D | 8605814be2b1f77fc93595393bf62116d77e8f2f | [
"MIT"
] | null | null | null | engine/source/sim/simObject.cc | pchan126/Torque2D | 8605814be2b1f77fc93595393bf62116d77e8f2f | [
"MIT"
] | null | null | null | engine/source/sim/simObject.cc | pchan126/Torque2D | 8605814be2b1f77fc93595393bf62116d77e8f2f | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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 "sim/simObject.h"
#include "sim/simObjectTimerEvent.h"
#include "console/consoleInternal.h"
#include "console/codeBlock.h"
#include "console/consoleInternal.h"
#include "memory/frameAllocator.h"
#include "io/fileStream.h"
#include "io/fileObject.h"
#include "console/ConsoleTypeValidators.h"
#include "simObject_ScriptBinding.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(SimObject);
namespace Sim
{
extern U32 gNextObjectId;
extern SimIdDictionary *gIdDictionary;
extern SimManagerNameDictionary *gNameDictionary;
extern void cancelPendingEvents(SimObject *obj);
}
//-----------------------------------------------------------------------------
SimObject::SimObject()
{
mFlags.set( ModStaticFields | ModDynamicFields );
objectName = NULL;
mInternalName = NULL;
nextNameObject = (SimObject*)-1;
nextManagerNameObject = (SimObject*)-1;
nextIdObject = NULL;
mId = 0;
mIdString = StringTable->EmptyString;
mGroup = 0;
mNameSpace = NULL;
mNotifyList = NULL;
mTypeMask = 0;
mScriptCallbackGuard = 0;
mFieldDictionary = NULL;
mCanSaveFieldDictionary = true;
mClassName = NULL;
mSuperClassName = NULL;
mProgenitorFile = CodeBlock::getCurrentCodeBlockFullPath();
mPeriodicTimerID = 0;
}
//---------------------------------------------------------------------------
bool SimObject::isMethod( const char* methodName )
{
if( !methodName || !methodName[0] )
return false;
StringTableEntry stname = StringTable->insert( methodName );
if( getNamespace() )
return ( getNamespace()->lookup( stname ) != NULL );
return false;
}
//---------------------------------------------------------------------------
bool SimObject::registerObject()
{
AssertFatal( !mFlags.test( Added ), "reigsterObject - Object already registered!");
mFlags.clear(Deleted | Removed);
if( mId == 0 )
{
mId = Sim::gNextObjectId++;
char idBuffer[64];
dSprintf(idBuffer, sizeof(idBuffer), "%d", mId);
mIdString = StringTable->insert( idBuffer );
}
AssertFatal(Sim::gIdDictionary && Sim::gNameDictionary,
"SimObject::registerObject - tried to register an object before Sim::init()!");
Sim::gIdDictionary->insert(this);
Sim::gNameDictionary->insert(this);
// Notify object
bool ret = onAdd();
if(!ret)
unregisterObject();
AssertFatal(!ret || isProperlyAdded(), "Object did not call SimObject::onAdd()");
if ( isMethod( "onAdd" ) )
Con::executef( this, 1, "onAdd" );
return ret;
}
//---------------------------------------------------------------------------
void SimObject::unregisterObject()
{
// Sanity!
AssertISV( getScriptCallbackGuard() == 0, "SimObject::unregisterObject: Object is being unregistered whilst performing a script callback!" );
if ( isMethod( "onRemove" ) )
Con::executef( this, 1, "onRemove" );
mFlags.set(Removed);
// Notify object first
onRemove();
// Clear out any pending notifications before
// we call our own, just in case they delete
// something that we have referenced.
clearAllNotifications();
// Notify all objects that are waiting for delete
// messages
if (getGroup())
getGroup()->removeObject(this);
processDeleteNotifies();
// Do removals from the Sim.
Sim::gNameDictionary->remove(this);
Sim::gIdDictionary->remove(this);
Sim::cancelPendingEvents(this);
}
//---------------------------------------------------------------------------
void SimObject::deleteObject()
{
// Sanity!
AssertISV( getScriptCallbackGuard() == 0, "SimObject::deleteObject: Object is being deleted whilst performing a script callback!" );
AssertFatal(mFlags.test(Added),
"SimObject::deleteObject: Object not registered.");
AssertFatal(!isDeleted(),"SimManager::deleteObject: "
"Object has already been deleted");
AssertFatal(!isRemoved(),"SimManager::deleteObject: "
"Object in the process of being removed");
mFlags.set(Deleted);
unregisterObject();
delete this;
}
//---------------------------------------------------------------------------
void SimObject::setId(SimObjectId newId)
{
if(!mFlags.test(Added))
{
mId = newId;
}
else
{
// get this object out of the id dictionary if it's in it
Sim::gIdDictionary->remove(this);
// Free current Id.
// Assign new one.
mId = newId ? newId : Sim::gNextObjectId++;
Sim::gIdDictionary->insert(this);
}
char idBuffer[64];
dSprintf(idBuffer, sizeof(idBuffer), "%d", mId);
mIdString = StringTable->insert( idBuffer );
}
void SimObject::assignName(const char *name)
{
if( dStricmp( getClassName(), name ) == 0 )
Con::errorf( "SimObject::assignName - Assigning name '%s' to instance of object with type '%s'."
" This can cause namespace linking issues.", getClassName(), name );
// Is this name already registered?
if ( Sim::gNameDictionary->find(name) != NULL )
{
// Yes, so error,
Con::errorf( "SimObject::assignName() - Attempted to set object to name '%s' but it is already assigned to another object.", name );
return;
}
StringTableEntry newName = NULL;
if (name[0])
newName = StringTable->insert(name);
if (mGroup)
mGroup->nameDictionary.remove(this);
if (isProperlyAdded())
{
// Unlink the old namespaces.
unlinkNamespaces();
Sim::gNameDictionary->remove(this);
}
objectName = newName;
if (mGroup)
mGroup->nameDictionary.insert(this);
if (isProperlyAdded())
{
// Link the new namespaces.
linkNamespaces();
Sim::gNameDictionary->insert(this);
}
}
//---------------------------------------------------------------------------
bool SimObject::registerObject(U32 id)
{
setId(id);
return registerObject();
}
bool SimObject::registerObject(const char *name)
{
assignName(name);
return registerObject();
}
bool SimObject::registerObject(const char *name, U32 id)
{
setId(id);
assignName(name);
return registerObject();
}
void SimObject::assignDynamicFieldsFrom(SimObject* parent)
{
if(parent->mFieldDictionary)
{
if( mFieldDictionary == NULL )
mFieldDictionary = new SimFieldDictionary;
mFieldDictionary->assignFrom(parent->mFieldDictionary);
}
}
void SimObject::assignFieldsFrom(SimObject *parent)
{
// only allow field assigns from objects of the same class:
if(getClassRep() == parent->getClassRep())
{
const AbstractClassRep::FieldList &list = getFieldList();
// copy out all the fields:
for(U32 i = 0; i < (U32)list.size(); i++)
{
const AbstractClassRep::Field* f = &list[i];
S32 lastField = f->elementCount - 1;
for(S32 j = 0; j <= lastField; j++)
{
const char* fieldVal = (*f->getDataFn)( this, Con::getData(f->type, (void *) (((const char *)parent) + f->offset), j, f->table, f->flag));
//if(fieldVal)
// Con::setData(f->type, (void *) (((const char *)this) + f->offset), j, 1, &fieldVal, f->table);
if(fieldVal)
{
// code copied from SimObject::setDataField().
// TODO: paxorr: abstract this into a better setData / getData that considers prot fields.
FrameTemp<char> buffer(2048);
FrameTemp<char> bufferSecure(2048); // This buffer is used to make a copy of the data
ConsoleBaseType *cbt = ConsoleBaseType::getType( f->type );
const char* szBuffer = cbt->prepData( fieldVal, buffer, 2048 );
dMemset( bufferSecure, 0, 2048 );
dMemcpy( bufferSecure, szBuffer, dStrlen( szBuffer ) );
if((*f->setDataFn)( this, bufferSecure ) )
Con::setData(f->type, (void *) (((const char *)this) + f->offset), j, 1, &fieldVal, f->table);
}
}
}
}
assignDynamicFieldsFrom(parent);
}
bool SimObject::writeField(StringTableEntry fieldname, const char* value)
{
// Don't write empty fields.
if (!value || !*value)
return false;
// Don't write ParentGroup
if( fieldname == StringTable->insert("parentGroup") )
return false;
return true;
}
void SimObject::writeFields(Stream &stream, U32 tabStop)
{
const AbstractClassRep::FieldList &list = getFieldList();
for(U32 i = 0; i < (U32)list.size(); i++)
{
const AbstractClassRep::Field* f = &list[i];
if( f->type == AbstractClassRep::DepricatedFieldType ||
f->type == AbstractClassRep::StartGroupFieldType ||
f->type == AbstractClassRep::EndGroupFieldType) continue;
// Fetch fieldname.
StringTableEntry fieldName = StringTable->insert( f->pFieldname );
// Fetch element count.
const S32 elementCount = f->elementCount;
// Skip if the field should not be written.
// For now, we only deal with non-array fields.
if ( elementCount == 1 &&
f->writeDataFn != NULL &&
f->writeDataFn( this, fieldName ) == false )
continue;
for(U32 j = 0; S32(j) < elementCount; j++)
{
char array[8];
dSprintf( array, 8, "%d", j );
const char *val = getDataField(fieldName, array );
// Make a copy for the field check.
if (!val)
continue;
U32 nBufferSize = dStrlen( val ) + 1;
FrameTemp<char> valCopy( nBufferSize );
dStrcpy( (char *)valCopy, val );
if (!writeField(fieldName, valCopy))
continue;
val = valCopy;
U32 expandedBufferSize = ( nBufferSize * 2 ) + 32;
FrameTemp<char> expandedBuffer( expandedBufferSize );
if(f->elementCount == 1)
dSprintf(expandedBuffer, expandedBufferSize, "%s = \"", f->pFieldname);
else
dSprintf(expandedBuffer, expandedBufferSize, "%s[%d] = \"", f->pFieldname, j);
// detect and collapse relative path information
char fnBuf[1024];
if (f->type == TypeFilename)
{
Con::collapsePath(fnBuf, 1024, val);
val = fnBuf;
}
expandEscape((char*)expandedBuffer + dStrlen(expandedBuffer), val);
dStrcat(expandedBuffer, "\";\r\n");
stream.writeTabs(tabStop);
stream.write(dStrlen(expandedBuffer),expandedBuffer);
}
}
if(mFieldDictionary && mCanSaveFieldDictionary)
mFieldDictionary->writeFields(this, stream, tabStop);
}
void SimObject::write(Stream &stream, U32 tabStop, U32 flags)
{
// Only output selected objects if they want that.
if((flags & SelectedOnly) && !isSelected())
return;
stream.writeTabs(tabStop);
char buffer[1024];
dSprintf(buffer, sizeof(buffer), "new %s(%s) {\r\n", getClassName(), getName() ? getName() : "");
stream.write(dStrlen(buffer), buffer);
writeFields(stream, tabStop + 1);
stream.writeTabs(tabStop);
stream.write(4, "};\r\n");
}
bool SimObject::save(const char* pcFileName, bool bOnlySelected)
{
static const char *beginMessage = "//--- OBJECT WRITE BEGIN ---";
static const char *endMessage = "//--- OBJECT WRITE END ---";
FileStream stream;
FileObject f;
f.readMemory(pcFileName);
// check for flags <selected, ...>
U32 writeFlags = 0;
if(bOnlySelected)
writeFlags |= SimObject::SelectedOnly;
if(!ResourceManager->openFileForWrite(stream, pcFileName))
return false;
char docRoot[256];
char modRoot[256];
dStrcpy(docRoot, pcFileName);
char *p = dStrrchr(docRoot, '/');
if (p) *++p = '\0';
else docRoot[0] = '\0';
dStrcpy(modRoot, pcFileName);
p = dStrchr(modRoot, '/');
if (p) *++p = '\0';
else modRoot[0] = '\0';
Con::setVariable("$DocRoot", docRoot);
Con::setVariable("$ModRoot", modRoot);
const char *buffer;
while(!f.isEOF())
{
buffer = (const char *) f.readLine();
if(!dStrcmp(buffer, beginMessage))
break;
stream.write(dStrlen(buffer), buffer);
stream.write(2, "\r\n");
}
stream.write(dStrlen(beginMessage), beginMessage);
stream.write(2, "\r\n");
write(stream, 0, writeFlags);
stream.write(dStrlen(endMessage), endMessage);
stream.write(2, "\r\n");
while(!f.isEOF())
{
buffer = (const char *) f.readLine();
if(!dStrcmp(buffer, endMessage))
break;
}
while(!f.isEOF())
{
buffer = (const char *) f.readLine();
stream.write(dStrlen(buffer), buffer);
stream.write(2, "\r\n");
}
Con::setVariable("$DocRoot", NULL);
Con::setVariable("$ModRoot", NULL);
return true;
}
void SimObject::setInternalName(const char* newname)
{
if(newname)
mInternalName = StringTable->insert(newname);
}
StringTableEntry SimObject::getInternalName()
{
return mInternalName;
}
void SimObject::dumpClassHierarchy()
{
AbstractClassRep* pRep = getClassRep();
while(pRep)
{
Con::warnf("%s ->", pRep->getClassName());
pRep = pRep->getParentClass();
}
}
const char *SimObject::tabComplete(const char *prevText, S32 baseLen, bool fForward)
{
return mNameSpace->tabComplete(prevText, baseLen, fForward);
}
//-----------------------------------------------------------------------------
void SimObject::setDataField(StringTableEntry slotName, const char *array, const char *value)
{
// first search the static fields if enabled
if(mFlags.test(ModStaticFields))
{
const AbstractClassRep::Field *fld = findField(slotName);
if(fld)
{
if( fld->type == AbstractClassRep::DepricatedFieldType ||
fld->type == AbstractClassRep::StartGroupFieldType ||
fld->type == AbstractClassRep::EndGroupFieldType)
return;
S32 array1 = array ? dAtoi(array) : 0;
if(array1 >= 0 && array1 < fld->elementCount && fld->elementCount >= 1)
{
// If the set data notify callback returns true, then go ahead and
// set the data, otherwise, assume the set notify callback has either
// already set the data, or has deemed that the data should not
// be set at all.
FrameTemp<char> buffer(2048);
FrameTemp<char> bufferSecure(2048); // This buffer is used to make a copy of the data
// so that if the prep functions or any other functions use the string stack, the data
// is not corrupted.
ConsoleBaseType *cbt = ConsoleBaseType::getType( fld->type );
AssertFatal( cbt != NULL, "Could not resolve Type Id." );
const char* szBuffer = cbt->prepData( value, buffer, 2048 );
dMemset( bufferSecure, 0, 2048 );
dMemcpy( bufferSecure, szBuffer, dStrlen( szBuffer ) );
if( (*fld->setDataFn)( this, bufferSecure ) )
Con::setData(fld->type, (void *) (((const char *)this) + fld->offset), array1, 1, &value, fld->table);
onStaticModified( slotName, value );
return;
}
if(fld->validator)
fld->validator->validateType(this, (void *) (((const char *)this) + fld->offset));
onStaticModified( slotName, value );
return;
}
}
if(mFlags.test(ModDynamicFields))
{
if(!mFieldDictionary)
mFieldDictionary = new SimFieldDictionary;
if(!array)
mFieldDictionary->setFieldValue(slotName, value);
else
{
char buf[256];
dStrcpy(buf, slotName);
dStrcat(buf, array);
mFieldDictionary->setFieldValue(StringTable->insert(buf), value);
}
}
}
//-----------------------------------------------------------------------------
const char *SimObject::getDataField(StringTableEntry slotName, const char *array)
{
if(mFlags.test(ModStaticFields))
{
S32 array1 = array ? dAtoi(array) : -1;
const AbstractClassRep::Field *fld = findField(slotName);
if(fld)
{
if(array1 == -1 && fld->elementCount == 1)
return (*fld->getDataFn)( this, Con::getData(fld->type, (void *) (((const char *)this) + fld->offset), 0, fld->table, fld->flag) );
if(array1 >= 0 && array1 < fld->elementCount)
return (*fld->getDataFn)( this, Con::getData(fld->type, (void *) (((const char *)this) + fld->offset), array1, fld->table, fld->flag) );// + typeSizes[fld.type] * array1));
return "";
}
}
if(mFlags.test(ModDynamicFields))
{
if(!mFieldDictionary)
return "";
if(!array)
{
if (const char* val = mFieldDictionary->getFieldValue(slotName))
return val;
}
else
{
static char buf[256];
dStrcpy(buf, slotName);
dStrcat(buf, array);
if (const char* val = mFieldDictionary->getFieldValue(StringTable->insert(buf)))
return val;
}
}
return "";
}
//-----------------------------------------------------------------------------
const char *SimObject::getPrefixedDataField(StringTableEntry fieldName, const char *array)
{
// Sanity!
AssertFatal( fieldName != NULL, "Cannot get field value with NULL field name." );
// Fetch field value.
const char* pFieldValue = getDataField( fieldName, array );
// Sanity.
AssertFatal( pFieldValue != NULL, "Field value cannot be NULL." );
// Return without the prefix if there's no value.
if ( *pFieldValue == 0 )
return StringTable->EmptyString;
// Fetch the field prefix.
StringTableEntry fieldPrefix = getDataFieldPrefix( fieldName );
// Sanity!
AssertFatal( fieldPrefix != NULL, "Field prefix cannot be NULL." );
// Calculate a buffer size including prefix.
const U32 valueBufferSize = dStrlen(fieldPrefix) + dStrlen(pFieldValue) + 1;
// Fetch a buffer.
char* pValueBuffer = Con::getReturnBuffer( valueBufferSize );
// Format the value buffer.
dSprintf( pValueBuffer, valueBufferSize, "%s%s", fieldPrefix, pFieldValue );
return pValueBuffer;
}
//-----------------------------------------------------------------------------
void SimObject::setPrefixedDataField(StringTableEntry fieldName, const char *array, const char *value)
{
// Sanity!
AssertFatal( fieldName != NULL, "Cannot set object field value with NULL field name." );
AssertFatal( value != NULL, "Field value cannot be NULL." );
// Set value without prefix if there's no value.
if ( *value == 0 )
{
setDataField( fieldName, NULL, value );
return;
}
// Fetch the field prefix.
StringTableEntry fieldPrefix = getDataFieldPrefix( fieldName );
// Sanity.
AssertFatal( fieldPrefix != NULL, "Field prefix cannot be NULL." );
// Do we have a field prefix?
if ( fieldPrefix == StringTable->EmptyString )
{
// No, so set the data field in the usual way.
setDataField( fieldName, NULL, value );
return;
}
// Yes, so fetch the length of the field prefix.
const U32 fieldPrefixLength = dStrlen(fieldPrefix);
// Yes, so does it start with the object field prefix?
if ( dStrnicmp( value, fieldPrefix, fieldPrefixLength ) != 0 )
{
// No, so set the data field in the usual way.
setDataField( fieldName, NULL, value );
return;
}
// Yes, so set the data excluding the prefix.
setDataField( fieldName, NULL, value + fieldPrefixLength );
}
//-----------------------------------------------------------------------------
const char *SimObject::getPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const S32 fieldType )
{
// Sanity!
AssertFatal( fieldName != NULL, "Cannot get field value with NULL field name." );
// Fetch field value.
const char* pFieldValue = getDataField( fieldName, array );
// Sanity.
AssertFatal( pFieldValue != NULL, "Field value cannot be NULL." );
// Return the field if no field type is specified.
if ( fieldType == -1 )
return pFieldValue;
// Return without the prefix if there's no value.
if ( *pFieldValue == 0 )
return StringTable->EmptyString;
// Fetch the console base type.
ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType( fieldType );
// Did we find the console base type?
if ( pConsoleBaseType == NULL )
{
// No, so warn.
Con::warnf("getPrefixedDynamicDataField() - Invalid field type '%d' specified for field '%s' with value '%s'.",
fieldType, fieldName, pFieldValue );
}
// Fetch the field prefix.
StringTableEntry fieldPrefix = pConsoleBaseType->getTypePrefix();
// Sanity!
AssertFatal( fieldPrefix != NULL, "Field prefix cannot be NULL." );
// Calculate a buffer size including prefix.
const U32 valueBufferSize = dStrlen(fieldPrefix) + dStrlen(pFieldValue) + 1;
// Fetch a buffer.
char* pValueBuffer = Con::getReturnBuffer( valueBufferSize );
// Format the value buffer.
dSprintf( pValueBuffer, valueBufferSize, "%s%s", fieldPrefix, pFieldValue );
return pValueBuffer;
}
//-----------------------------------------------------------------------------
void SimObject::setPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType )
{
// Sanity!
AssertFatal( fieldName != NULL, "Cannot set object field value with NULL field name." );
AssertFatal( value != NULL, "Field value cannot be NULL." );
// Set value without prefix if no field type was specified.
if ( fieldType == -1 )
{
setDataField( fieldName, NULL, value );
return;
}
// Fetch the console base type.
ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType( fieldType );
// Did we find the console base type?
if ( pConsoleBaseType == NULL )
{
// No, so warn.
Con::warnf("setPrefixedDynamicDataField() - Invalid field type '%d' specified for field '%s' with value '%s'.",
fieldType, fieldName, value );
}
// Set value without prefix if there's no value or we didn't find the console base type.
if ( *value == 0 || pConsoleBaseType == NULL )
{
setDataField( fieldName, NULL, value );
return;
}
// Fetch the field prefix.
StringTableEntry fieldPrefix = pConsoleBaseType->getTypePrefix();
// Sanity.
AssertFatal( fieldPrefix != NULL, "Field prefix cannot be NULL." );
// Do we have a field prefix?
if ( fieldPrefix == StringTable->EmptyString )
{
// No, so set the data field in the usual way.
setDataField( fieldName, NULL, value );
return;
}
// Yes, so fetch the length of the field prefix.
const U32 fieldPrefixLength = dStrlen(fieldPrefix);
// Yes, so does it start with the object field prefix?
if ( dStrnicmp( value, fieldPrefix, fieldPrefixLength ) != 0 )
{
// No, so set the data field in the usual way.
setDataField( fieldName, NULL, value );
return;
}
// Yes, so set the data excluding the prefix.
setDataField( fieldName, NULL, value + fieldPrefixLength );
}
//-----------------------------------------------------------------------------
StringTableEntry SimObject::getDataFieldPrefix( StringTableEntry fieldName )
{
// Sanity!
AssertFatal( fieldName != NULL, "Cannot get field prefix with NULL field name." );
// Find the field.
const AbstractClassRep::Field* pField = findField( fieldName );
// Return nothing if field was not found.
if ( pField == NULL )
return StringTable->EmptyString;
// Yes, so fetch the console base type.
ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType( pField->type );
// Fetch the type prefix.
return pConsoleBaseType->getTypePrefix();
}
//-----------------------------------------------------------------------------
U32 SimObject::getDataFieldType( StringTableEntry slotName, const char* array )
{
const AbstractClassRep::Field* field = findField( slotName );
if( field )
return field->type;
return 0;
}
SimObject::~SimObject()
{
delete mFieldDictionary;
AssertFatal(nextNameObject == (SimObject*)-1,avar(
"SimObject::~SimObject: Not removed from dictionary: name %s, id %i",
objectName, mId));
AssertFatal(nextManagerNameObject == (SimObject*)-1,avar(
"SimObject::~SimObject: Not removed from manager dictionary: name %s, id %i",
objectName,mId));
AssertFatal(mFlags.test(Added) == 0, "SimObject::object "
"missing call to SimObject::onRemove");
}
//---------------------------------------------------------------------------
bool SimObject::isLocked()
{
if(!mFieldDictionary)
return false;
const char * val = mFieldDictionary->getFieldValue( StringTable->insert( "locked", false ) );
return( val ? dAtob(val) : false );
}
void SimObject::setLocked( bool b = true )
{
setDataField(StringTable->insert("locked", false), NULL, b ? "true" : "false" );
}
bool SimObject::isHidden()
{
if(!mFieldDictionary)
return false;
const char * val = mFieldDictionary->getFieldValue( StringTable->insert( "hidden", false ) );
return( val ? dAtob(val) : false );
}
void SimObject::setHidden(bool b = true)
{
setDataField(StringTable->insert("hidden", false), NULL, b ? "true" : "false" );
}
//---------------------------------------------------------------------------
bool SimObject::onAdd()
{
mFlags.set(Added);
linkNamespaces();
// onAdd() should return FALSE if there was an error
return true;
}
void SimObject::onRemove()
{
mFlags.clear(Added);
unlinkNamespaces();
}
void SimObject::onGroupAdd()
{
}
void SimObject::onGroupRemove()
{
}
void SimObject::onDeleteNotify(SimObject*)
{
}
void SimObject::onNameChange(const char*)
{
}
void SimObject::onStaticModified(const char* slotName, const char* newValue)
{
}
bool SimObject::processArguments(S32 argc, const char**)
{
return argc == 0;
}
bool SimObject::isChildOfGroup(SimGroup* pGroup)
{
if(!pGroup)
return false;
//if we *are* the group in question,
//return true:
if(pGroup == dynamic_cast<SimGroup*>(this))
return true;
SimGroup* temp = mGroup;
while(temp)
{
if(temp == pGroup)
return true;
temp = temp->mGroup;
}
return false;
}
//---------------------------------------------------------------------------
static Chunker<SimObject::Notify> notifyChunker(128000);
SimObject::Notify *SimObject::mNotifyFreeList = NULL;
SimObject::Notify *SimObject::allocNotify()
{
if(mNotifyFreeList)
{
SimObject::Notify *ret = mNotifyFreeList;
mNotifyFreeList = ret->next;
return ret;
}
return notifyChunker.alloc();
}
void SimObject::freeNotify(SimObject::Notify* note)
{
AssertFatal(note->type != SimObject::Notify::Invalid, "Invalid notify");
note->type = SimObject::Notify::Invalid;
note->next = mNotifyFreeList;
mNotifyFreeList = note;
}
//------------------------------------------------------------------------------
SimObject::Notify* SimObject::removeNotify(void *ptr, SimObject::Notify::Type type)
{
Notify **list = &mNotifyList;
while(*list)
{
if((*list)->ptr == ptr && (*list)->type == type)
{
SimObject::Notify *ret = *list;
*list = ret->next;
return ret;
}
list = &((*list)->next);
}
return NULL;
}
void SimObject::deleteNotify(SimObject* obj)
{
AssertFatal(!obj->isDeleted(),
"SimManager::deleteNotify: Object is being deleted");
Notify *note = allocNotify();
note->ptr = (void *) this;
note->next = obj->mNotifyList;
note->type = Notify::DeleteNotify;
obj->mNotifyList = note;
note = allocNotify();
note->ptr = (void *) obj;
note->next = mNotifyList;
note->type = Notify::ClearNotify;
mNotifyList = note;
//obj->deleteNotifyList.pushBack(this);
//clearNotifyList.pushBack(obj);
}
void SimObject::registerReference(SimObject **ptr)
{
Notify *note = allocNotify();
note->ptr = (void *) ptr;
note->next = mNotifyList;
note->type = Notify::ObjectRef;
mNotifyList = note;
}
void SimObject::unregisterReference(SimObject **ptr)
{
Notify *note = removeNotify((void *) ptr, Notify::ObjectRef);
if(note)
freeNotify(note);
}
void SimObject::clearNotify(SimObject* obj)
{
Notify *note = obj->removeNotify((void *) this, Notify::DeleteNotify);
if(note)
freeNotify(note);
note = removeNotify((void *) obj, Notify::ClearNotify);
if(note)
freeNotify(note);
}
void SimObject::processDeleteNotifies()
{
// clear out any delete notifies and
// object refs.
while(mNotifyList)
{
Notify *note = mNotifyList;
mNotifyList = note->next;
AssertFatal(note->type != Notify::ClearNotify, "Clear notes should be all gone.");
if(note->type == Notify::DeleteNotify)
{
SimObject *obj = (SimObject *) note->ptr;
Notify *cnote = obj->removeNotify((void *)this, Notify::ClearNotify);
obj->onDeleteNotify(this);
freeNotify(cnote);
}
else
{
// it must be an object ref - a pointer refs this object
*((SimObject **) note->ptr) = NULL;
}
freeNotify(note);
}
}
void SimObject::clearAllNotifications()
{
for(Notify **cnote = &mNotifyList; *cnote; )
{
Notify *temp = *cnote;
if(temp->type == Notify::ClearNotify)
{
*cnote = temp->next;
Notify *note = ((SimObject *) temp->ptr)->removeNotify((void *) this, Notify::DeleteNotify);
freeNotify(temp);
freeNotify(note);
}
else
cnote = &(temp->next);
}
}
//---------------------------------------------------------------------------
void SimObject::initPersistFields()
{
Parent::initPersistFields();
addGroup("SimBase");
addField("canSaveDynamicFields", TypeBool, Offset(mCanSaveFieldDictionary, SimObject), &writeCanSaveDynamicFields, "");
addField("internalName", TypeString, Offset(mInternalName, SimObject), &writeInternalName, "");
addProtectedField("parentGroup", TypeSimObjectPtr, Offset(mGroup, SimObject), &setParentGroup, &defaultProtectedGetFn, &writeParentGroup, "Group hierarchy parent of the object." );
endGroup("SimBase");
// Namespace Linking.
addGroup("Namespace Linking");
addProtectedField("superclass", TypeString, Offset(mSuperClassName, SimObject), &setSuperClass, &defaultProtectedGetFn, &writeSuperclass, "Script Class of object.");
addProtectedField("class", TypeString, Offset(mClassName, SimObject), &setClass, &defaultProtectedGetFn, &writeClass, "Script SuperClass of object.");
endGroup("Namespace Linking");
}
//-----------------------------------------------------------------------------
SimObject* SimObject::clone( const bool copyDynamicFields )
{
// Craete cloned object.
SimObject* pCloneObject = dynamic_cast<SimObject*>( ConsoleObject::create(getClassName()) );
if (!pCloneObject)
{
Con::errorf("SimObject::clone() - Unable to create cloned object.");
return NULL;
}
// Register object.
if ( !pCloneObject->registerObject() )
{
Con::warnf("SimObject::clone() - Unable to register cloned object.");
delete pCloneObject;
return NULL;
}
// Copy object.
copyTo( pCloneObject );
// Copy over dynamic fields if requested.
if ( copyDynamicFields )
pCloneObject->assignDynamicFieldsFrom( this );
return pCloneObject;
}
//-----------------------------------------------------------------------------
void SimObject::copyTo(SimObject* object)
{
object->mClassName = mClassName;
object->mSuperClassName = mSuperClassName;
object->mNameSpace = NULL;
object->linkNamespaces();
}
//-----------------------------------------------------------------------------
bool SimObject::setParentGroup(void* obj, const char* data)
{
SimGroup *parent = NULL;
SimObject *object = static_cast<SimObject*>(obj);
if(Sim::findObject(data, parent))
parent->addObject(object);
// always return false, because we've set mGroup when we called addObject
return false;
}
bool SimObject::addToSet(SimObjectId spid)
{
if (mFlags.test(Added) == false)
return false;
SimObject* ptr = Sim::findObject(spid);
if (ptr)
{
SimSet* sp = dynamic_cast<SimSet*>(ptr);
AssertFatal(sp != 0,
"SimObject::addToSet: "
"ObjectId does not refer to a set object");
if (sp)
{
sp->addObject(this);
return true;
}
}
return false;
}
bool SimObject::addToSet(const char *ObjectName)
{
if (mFlags.test(Added) == false)
return false;
SimObject* ptr = Sim::findObject(ObjectName);
if (ptr)
{
SimSet* sp = dynamic_cast<SimSet*>(ptr);
AssertFatal(sp != 0,
"SimObject::addToSet: "
"ObjectName does not refer to a set object");
if (sp)
{
sp->addObject(this);
return true;
}
}
return false;
}
bool SimObject::removeFromSet(SimObjectId sid)
{
if (mFlags.test(Added) == false)
return false;
SimSet *set;
if(Sim::findObject(sid, set))
{
set->removeObject(this);
return true;
}
return false;
}
bool SimObject::removeFromSet(const char *objectName)
{
if (mFlags.test(Added) == false)
return false;
SimSet *set;
if(Sim::findObject(objectName, set))
{
set->removeObject(this);
return true;
}
return false;
}
void SimObject::inspectPreApply()
{
}
void SimObject::inspectPostApply()
{
}
//-----------------------------------------------------------------------------
void SimObject::linkNamespaces()
{
// Don't link if we already have a namespace linkage in place.
AssertWarn(mNameSpace == NULL, "SimObject::linkNamespaces -- Namespace linkage already in place");
if (mNameSpace)
return;
// Start with the C++ Class namespace.
StringTableEntry parent = StringTable->insert( getClassName() );
// Link SuperClass to C++ Class.
if ( mSuperClassName && mSuperClassName[0] )
{
if ( Con::linkNamespaces(parent, mSuperClassName) )
parent = mSuperClassName;
else
mSuperClassName = NULL;
}
// Link Class to SuperClass or Class to C++ Class.
if ( mClassName && mClassName[0] )
{
if ( Con::linkNamespaces(parent, mClassName) )
parent = mClassName;
else
mClassName = NULL;
}
// Get the object's name.
StringTableEntry objectName = getName();
// Link Object Name to Class/SuperClass/C++ Class.
if ( objectName && objectName[0] )
{
if ( Con::linkNamespaces(parent, objectName) )
parent = objectName;
}
// Store our namespace.
mNameSpace = Con::lookupNamespace(parent);
}
//-----------------------------------------------------------------------------
void SimObject::unlinkNamespaces()
{
// Stop if there is no assigned namespace.
if (!mNameSpace)
return;
// Get the object's name.
StringTableEntry child = getName();
// Unlink any possible namespace combination.
if ( child && child[0] )
{
// Object Name/Class
if ( mClassName && mClassName[0] )
{
if( Con::unlinkNamespaces(mClassName, child) )
child = mClassName;
}
// Object Name/SuperClass or Class/SuperClass
if ( mSuperClassName && mSuperClassName[0] )
{
if ( Con::unlinkNamespaces(mSuperClassName, child) )
child = mSuperClassName;
}
// Object Name/C++ Class or SuperClass/C++ Class
Con::unlinkNamespaces(getClassName(), child);
}
else
{
// No Object Name, so get the Class namespace.
child = mClassName;
// Unlink any possible namespace combination.
if ( child && child[0] )
{
// Class/SuperClass
if ( mSuperClassName && mSuperClassName[0] )
{
if ( Con::unlinkNamespaces(mSuperClassName, child) )
child = mSuperClassName;
}
// Class/C++ Class or SuperClass/C++ Class
Con::unlinkNamespaces(getClassName(), child);
}
else
{
// SuperClass/C++ Class
if ( mSuperClassName && mSuperClassName[0] )
Con::unlinkNamespaces(getClassName(), mSuperClassName);
}
}
// Reset the namespace.
mNameSpace = NULL;
}
//-----------------------------------------------------------------------------
void SimObject::setClassNamespace( const char* classNamespace )
{
StringTableEntry oldClass = mClassName;
StringTableEntry newClass = StringTable->insert(classNamespace);
// Skip if no change.
if (oldClass == newClass)
return;
// Unlink the old namespaces.
if ( isProperlyAdded() )
unlinkNamespaces();
// Assign the new class namespace.
mClassName = newClass;
// Link the new namespaces.
if ( isProperlyAdded() )
linkNamespaces();
}
//-----------------------------------------------------------------------------
void SimObject::setSuperClassNamespace( const char* superClassNamespace )
{
StringTableEntry oldSuperClass = mSuperClassName;
StringTableEntry newSuperClass = StringTable->insert(superClassNamespace);
// Skip if no change.
if (oldSuperClass == newSuperClass)
return;
// Unlink the old namespaces.
if ( isProperlyAdded() )
unlinkNamespaces();
// Assign the new SuperClass namespace.
mSuperClassName = newSuperClass;
// Link the new namespaces.
if ( isProperlyAdded() )
linkNamespaces();
}
//-----------------------------------------------------------------------------
static S32 QSORT_CALLBACK compareFields(const void* a,const void* b)
{
const AbstractClassRep::Field* fa = *((const AbstractClassRep::Field**)a);
const AbstractClassRep::Field* fb = *((const AbstractClassRep::Field**)b);
return dStricmp(fa->pFieldname, fb->pFieldname);
}
void SimObject::dump()
{
const AbstractClassRep::FieldList &list = getFieldList();
char expandedBuffer[4096];
Con::printf("Static Fields:");
Vector<const AbstractClassRep::Field *> flist(__FILE__, __LINE__);
for(U32 i = 0; i < (U32)list.size(); i++)
flist.push_back(&list[i]);
dQsort(flist.address(),flist.size(),sizeof(AbstractClassRep::Field *),compareFields);
for(Vector<const AbstractClassRep::Field *>::iterator itr = flist.begin(); itr != flist.end(); itr++)
{
const AbstractClassRep::Field* f = *itr;
if( f->type == AbstractClassRep::DepricatedFieldType ||
f->type == AbstractClassRep::StartGroupFieldType ||
f->type == AbstractClassRep::EndGroupFieldType) continue;
for(U32 j = 0; S32(j) < f->elementCount; j++)
{
// [neo, 07/05/2007 - #3000]
// Some objects use dummy vars and projected fields so make sure we call the get functions
//const char *val = Con::getData(f->type, (void *) (((const char *)object) + f->offset), j, f->table, f->flag);
const char *val = (*f->getDataFn)( this, Con::getData(f->type, (void *) (((const char *)this) + f->offset), j, f->table, f->flag) );// + typeSizes[fld.type] * array1));
if(!val /*|| !*val*/)
continue;
if(f->elementCount == 1)
dSprintf(expandedBuffer, sizeof(expandedBuffer), " %s = \"", f->pFieldname);
else
dSprintf(expandedBuffer, sizeof(expandedBuffer), " %s[%d] = \"", f->pFieldname, j);
expandEscape(expandedBuffer + dStrlen(expandedBuffer), val);
Con::printf("%s\"", expandedBuffer);
}
}
Con::printf("Dynamic Fields:");
if(getFieldDictionary())
getFieldDictionary()->printFields(this);
Con::printf("Methods:");
Namespace *ns = getNamespace();
Vector<Namespace::Entry *> vec(__FILE__, __LINE__);
if(ns)
ns->getEntryList(&vec);
for(Vector<Namespace::Entry *>::iterator j = vec.begin(); j != vec.end(); j++)
Con::printf(" %s() - %s", (*j)->mFunctionName, (*j)->mUsage ? (*j)->mUsage : "");
}
| 30.171153 | 191 | 0.567592 | [
"object",
"vector"
] |
33e29d2b7bda247e48c5f1c88cdb3e5ad9ea89d3 | 13,245 | cpp | C++ | src/Interpreters/InterpreterShowCreateAccessEntityQuery.cpp | tianyiYoung/ClickHouse | 41012b5ba49df807af52fc17ab475a21fadda9b3 | [
"Apache-2.0"
] | 5 | 2021-05-14T02:46:44.000Z | 2021-11-23T04:58:20.000Z | src/Interpreters/InterpreterShowCreateAccessEntityQuery.cpp | tianyiYoung/ClickHouse | 41012b5ba49df807af52fc17ab475a21fadda9b3 | [
"Apache-2.0"
] | 5 | 2021-05-21T06:26:01.000Z | 2021-08-04T04:57:36.000Z | src/Interpreters/InterpreterShowCreateAccessEntityQuery.cpp | tianyiYoung/ClickHouse | 41012b5ba49df807af52fc17ab475a21fadda9b3 | [
"Apache-2.0"
] | 8 | 2021-05-12T01:38:18.000Z | 2022-02-10T06:08:41.000Z | #include <Interpreters/InterpreterShowCreateAccessEntityQuery.h>
#include <Interpreters/Context.h>
#include <Parsers/ASTCreateUserQuery.h>
#include <Parsers/ASTCreateRoleQuery.h>
#include <Parsers/ASTCreateQuotaQuery.h>
#include <Parsers/ASTCreateRowPolicyQuery.h>
#include <Parsers/ASTCreateSettingsProfileQuery.h>
#include <Parsers/ASTShowCreateAccessEntityQuery.h>
#include <Parsers/ASTUserNameWithHost.h>
#include <Parsers/ASTRolesOrUsersSet.h>
#include <Parsers/ASTSettingsProfileElement.h>
#include <Parsers/ASTRowPolicyName.h>
#include <Parsers/ExpressionListParsers.h>
#include <Parsers/formatAST.h>
#include <Parsers/parseQuery.h>
#include <Access/AccessControlManager.h>
#include <Access/EnabledQuota.h>
#include <Access/QuotaUsage.h>
#include <Access/User.h>
#include <Access/Role.h>
#include <Access/SettingsProfile.h>
#include <Columns/ColumnString.h>
#include <DataStreams/OneBlockInputStream.h>
#include <DataTypes/DataTypeString.h>
#include <Common/StringUtils/StringUtils.h>
#include <Core/Defines.h>
#include <ext/range.h>
#include <boost/range/algorithm/sort.hpp>
namespace DB
{
namespace ErrorCodes
{
extern const int NOT_IMPLEMENTED;
}
namespace
{
ASTPtr getCreateQueryImpl(
const User & user,
const AccessControlManager * manager /* not used if attach_mode == true */,
bool attach_mode)
{
auto query = std::make_shared<ASTCreateUserQuery>();
query->names = std::make_shared<ASTUserNamesWithHost>();
query->names->push_back(user.getName());
query->attach = attach_mode;
if (user.allowed_client_hosts != AllowedClientHosts::AnyHostTag{})
query->hosts = user.allowed_client_hosts;
if (user.default_roles != RolesOrUsersSet::AllTag{})
{
if (attach_mode)
query->default_roles = user.default_roles.toAST();
else
query->default_roles = user.default_roles.toASTWithNames(*manager);
}
if (user.authentication.getType() != Authentication::NO_PASSWORD)
{
query->authentication = user.authentication;
query->show_password = attach_mode; /// We don't show password unless it's an ATTACH statement.
}
if (!user.settings.empty())
{
if (attach_mode)
query->settings = user.settings.toAST();
else
query->settings = user.settings.toASTWithNames(*manager);
}
if (user.grantees != RolesOrUsersSet::AllTag{})
{
if (attach_mode)
query->grantees = user.grantees.toAST();
else
query->grantees = user.grantees.toASTWithNames(*manager);
query->grantees->use_keyword_any = true;
}
return query;
}
ASTPtr getCreateQueryImpl(const Role & role, const AccessControlManager * manager, bool attach_mode)
{
auto query = std::make_shared<ASTCreateRoleQuery>();
query->names.emplace_back(role.getName());
query->attach = attach_mode;
if (!role.settings.empty())
{
if (attach_mode)
query->settings = role.settings.toAST();
else
query->settings = role.settings.toASTWithNames(*manager);
}
return query;
}
ASTPtr getCreateQueryImpl(const SettingsProfile & profile, const AccessControlManager * manager, bool attach_mode)
{
auto query = std::make_shared<ASTCreateSettingsProfileQuery>();
query->names.emplace_back(profile.getName());
query->attach = attach_mode;
if (!profile.elements.empty())
{
if (attach_mode)
query->settings = profile.elements.toAST();
else
query->settings = profile.elements.toASTWithNames(*manager);
if (query->settings)
query->settings->setUseInheritKeyword(true);
}
if (!profile.to_roles.empty())
{
if (attach_mode)
query->to_roles = profile.to_roles.toAST();
else
query->to_roles = profile.to_roles.toASTWithNames(*manager);
}
return query;
}
ASTPtr getCreateQueryImpl(
const Quota & quota,
const AccessControlManager * manager /* not used if attach_mode == true */,
bool attach_mode)
{
auto query = std::make_shared<ASTCreateQuotaQuery>();
query->names.emplace_back(quota.getName());
query->attach = attach_mode;
if (quota.key_type != Quota::KeyType::NONE)
query->key_type = quota.key_type;
query->all_limits.reserve(quota.all_limits.size());
for (const auto & limits : quota.all_limits)
{
ASTCreateQuotaQuery::Limits create_query_limits;
create_query_limits.duration = limits.duration;
create_query_limits.randomize_interval = limits.randomize_interval;
for (auto resource_type : ext::range(Quota::MAX_RESOURCE_TYPE))
create_query_limits.max[resource_type] = limits.max[resource_type];
query->all_limits.push_back(create_query_limits);
}
if (!quota.to_roles.empty())
{
if (attach_mode)
query->roles = quota.to_roles.toAST();
else
query->roles = quota.to_roles.toASTWithNames(*manager);
}
return query;
}
ASTPtr getCreateQueryImpl(
const RowPolicy & policy,
const AccessControlManager * manager /* not used if attach_mode == true */,
bool attach_mode)
{
auto query = std::make_shared<ASTCreateRowPolicyQuery>();
query->names = std::make_shared<ASTRowPolicyNames>();
query->names->name_parts.emplace_back(policy.getNameParts());
query->attach = attach_mode;
if (policy.isRestrictive())
query->is_restrictive = policy.isRestrictive();
for (auto type : ext::range(RowPolicy::MAX_CONDITION_TYPE))
{
const auto & condition = policy.conditions[static_cast<size_t>(type)];
if (!condition.empty())
{
ParserExpression parser;
ASTPtr expr = parseQuery(parser, condition, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH);
query->conditions.emplace_back(type, std::move(expr));
}
}
if (!policy.to_roles.empty())
{
if (attach_mode)
query->roles = policy.to_roles.toAST();
else
query->roles = policy.to_roles.toASTWithNames(*manager);
}
return query;
}
ASTPtr getCreateQueryImpl(
const IAccessEntity & entity,
const AccessControlManager * manager /* not used if attach_mode == true */,
bool attach_mode)
{
if (const User * user = typeid_cast<const User *>(&entity))
return getCreateQueryImpl(*user, manager, attach_mode);
if (const Role * role = typeid_cast<const Role *>(&entity))
return getCreateQueryImpl(*role, manager, attach_mode);
if (const RowPolicy * policy = typeid_cast<const RowPolicy *>(&entity))
return getCreateQueryImpl(*policy, manager, attach_mode);
if (const Quota * quota = typeid_cast<const Quota *>(&entity))
return getCreateQueryImpl(*quota, manager, attach_mode);
if (const SettingsProfile * profile = typeid_cast<const SettingsProfile *>(&entity))
return getCreateQueryImpl(*profile, manager, attach_mode);
throw Exception(entity.outputTypeAndName() + ": type is not supported by SHOW CREATE query", ErrorCodes::NOT_IMPLEMENTED);
}
using EntityType = IAccessEntity::Type;
}
InterpreterShowCreateAccessEntityQuery::InterpreterShowCreateAccessEntityQuery(const ASTPtr & query_ptr_, ContextPtr context_)
: WithContext(context_), query_ptr(query_ptr_)
{
}
BlockIO InterpreterShowCreateAccessEntityQuery::execute()
{
BlockIO res;
res.in = executeImpl();
return res;
}
BlockInputStreamPtr InterpreterShowCreateAccessEntityQuery::executeImpl()
{
/// Build a create queries.
ASTs create_queries = getCreateQueries();
/// Build the result column.
MutableColumnPtr column = ColumnString::create();
WriteBufferFromOwnString create_query_buf;
for (const auto & create_query : create_queries)
{
formatAST(*create_query, create_query_buf, false, true);
column->insert(create_query_buf.str());
create_query_buf.restart();
}
/// Prepare description of the result column.
WriteBufferFromOwnString desc_buf;
const auto & show_query = query_ptr->as<const ASTShowCreateAccessEntityQuery &>();
formatAST(show_query, desc_buf, false, true);
String desc = desc_buf.str();
String prefix = "SHOW ";
if (startsWith(desc, prefix))
desc = desc.substr(prefix.length()); /// `desc` always starts with "SHOW ", so we can trim this prefix.
return std::make_shared<OneBlockInputStream>(Block{{std::move(column), std::make_shared<DataTypeString>(), desc}});
}
std::vector<AccessEntityPtr> InterpreterShowCreateAccessEntityQuery::getEntities() const
{
auto & show_query = query_ptr->as<ASTShowCreateAccessEntityQuery &>();
const auto & access_control = getContext()->getAccessControlManager();
getContext()->checkAccess(getRequiredAccess());
show_query.replaceEmptyDatabase(getContext()->getCurrentDatabase());
std::vector<AccessEntityPtr> entities;
if (show_query.all)
{
auto ids = access_control.findAll(show_query.type);
for (const auto & id : ids)
{
if (auto entity = access_control.tryRead(id))
entities.push_back(entity);
}
}
else if (show_query.current_user)
{
if (auto user = getContext()->getUser())
entities.push_back(user);
}
else if (show_query.current_quota)
{
auto usage = getContext()->getQuotaUsage();
if (usage)
entities.push_back(access_control.read<Quota>(usage->quota_id));
}
else if (show_query.type == EntityType::ROW_POLICY)
{
auto ids = access_control.findAll<RowPolicy>();
if (show_query.row_policy_names)
{
for (const String & name : show_query.row_policy_names->toStrings())
entities.push_back(access_control.read<RowPolicy>(name));
}
else
{
for (const auto & id : ids)
{
auto policy = access_control.tryRead<RowPolicy>(id);
if (!policy)
continue;
if (!show_query.short_name.empty() && (policy->getShortName() != show_query.short_name))
continue;
if (show_query.database_and_table_name)
{
const String & database = show_query.database_and_table_name->first;
const String & table_name = show_query.database_and_table_name->second;
if (!database.empty() && (policy->getDatabase() != database))
continue;
if (!table_name.empty() && (policy->getTableName() != table_name))
continue;
}
entities.push_back(policy);
}
}
}
else
{
for (const String & name : show_query.names)
entities.push_back(access_control.read(access_control.getID(show_query.type, name)));
}
boost::range::sort(entities, IAccessEntity::LessByName{});
return entities;
}
ASTs InterpreterShowCreateAccessEntityQuery::getCreateQueries() const
{
auto entities = getEntities();
ASTs list;
const auto & access_control = getContext()->getAccessControlManager();
for (const auto & entity : entities)
list.push_back(getCreateQuery(*entity, access_control));
return list;
}
ASTPtr InterpreterShowCreateAccessEntityQuery::getCreateQuery(const IAccessEntity & entity, const AccessControlManager & access_control)
{
return getCreateQueryImpl(entity, &access_control, false);
}
ASTPtr InterpreterShowCreateAccessEntityQuery::getAttachQuery(const IAccessEntity & entity)
{
return getCreateQueryImpl(entity, nullptr, true);
}
AccessRightsElements InterpreterShowCreateAccessEntityQuery::getRequiredAccess() const
{
const auto & show_query = query_ptr->as<const ASTShowCreateAccessEntityQuery &>();
AccessRightsElements res;
switch (show_query.type)
{
case EntityType::USER: res.emplace_back(AccessType::SHOW_USERS); return res;
case EntityType::ROLE: res.emplace_back(AccessType::SHOW_ROLES); return res;
case EntityType::SETTINGS_PROFILE: res.emplace_back(AccessType::SHOW_SETTINGS_PROFILES); return res;
case EntityType::ROW_POLICY: res.emplace_back(AccessType::SHOW_ROW_POLICIES); return res;
case EntityType::QUOTA: res.emplace_back(AccessType::SHOW_QUOTAS); return res;
case EntityType::MAX: break;
}
throw Exception(toString(show_query.type) + ": type is not supported by SHOW CREATE query", ErrorCodes::NOT_IMPLEMENTED);
}
}
| 34.855263 | 136 | 0.641752 | [
"vector"
] |
33e31264686e3c0872663e78bfa47d412623a4cd | 3,667 | cc | C++ | DQM/SiStripMonitorSummary/plugins/SiStripPlotGain.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | DQM/SiStripMonitorSummary/plugins/SiStripPlotGain.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | DQM/SiStripMonitorSummary/plugins/SiStripPlotGain.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z | #include "DQM/SiStripMonitorSummary/plugins/SiStripPlotGain.h"
#include "DataFormats/TrackerCommon/interface/TrackerTopology.h"
#include "Geometry/Records/interface/TrackerTopologyRcd.h"
SiStripPlotGain::SiStripPlotGain(const edm::ParameterSet& iConfig):
cacheID(0xFFFFFFFF)
{
//now do what ever initialization is needed
if(!edm::Service<SiStripDetInfoFileReader>().isAvailable()){
edm::LogError("TkLayerMap") <<
"\n------------------------------------------"
"\nUnAvailable Service SiStripDetInfoFileReader: please insert in the configuration file an instance like"
"\n\tprocess.SiStripDetInfoFileReader = cms.Service(\"SiStripDetInfoFileReader\")"
"\n------------------------------------------";
}
fr=edm::Service<SiStripDetInfoFileReader>().operator->();
file = new TFile("correlTest.root","RECREATE");
tkmap = new TrackerMap();
}
SiStripPlotGain::~SiStripPlotGain()
{}
//
void
SiStripPlotGain::beginRun(const edm::Run& run, const edm::EventSetup& es){
if(getCache(es)==cacheID )
return;
cacheID=getCache(es);
edm::LogInfo("") << "[SiStripPlotGain::beginRun] cacheID " << cacheID << std::endl;
es.get<SiStripApvGainRcd>().get(Handle_);
DoAnalysis(es, *Handle_.product());
}
void
SiStripPlotGain::DoAnalysis(const edm::EventSetup& es, const SiStripApvGain& gain){
edm::LogInfo("") << "[Doanalysis]";
//Retrieve tracker topology from geometry
edm::ESHandle<TrackerTopology> tTopoHandle;
es.get<TrackerTopologyRcd>().get(tTopoHandle);
const TrackerTopology* const tTopo = tTopoHandle.product();
std::vector<TH1F *>histos;
SiStripApvGain::RegistryPointers p=gain.getRegistryPointers();
SiStripApvGain::RegistryConstIterator iter, iterE;
iter=p.detid_begin;
iterE=p.detid_end;
float value;
//Divide result by d
for(;iter!=iterE;++iter){
getHistos(*iter,tTopo,histos);
SiStripApvGain::Range range=SiStripApvGain::Range(p.getFirstElement(iter),p.getLastElement(iter));
edm::LogInfo("") << "[Doanalysis] detid " << *iter << " range " << range.second-range.first;
size_t apv=0, apvE= (range.second-range.first);
for (;apv<apvE;apv+=2){
value=gain.getApvGain(apv,range);
tkmap->fill(*iter,value);
for(size_t i=0;i<histos.size();++i)
histos[i]->Fill(value);
}
}
}
void
SiStripPlotGain::getHistos(const uint32_t& detid, const TrackerTopology* tTopo, std::vector<TH1F*>& histos){
histos.clear();
int subdet=-999; int component=-999;
SiStripDetId a(detid);
if ( a.subdetId() == 3 ){
subdet=0;
component=tTopo->tibLayer(detid);
} else if ( a.subdetId() == 4 ) {
subdet=1;
component=tTopo->tidSide(detid)==2?tTopo->tidWheel(detid):tTopo->tidWheel(detid)+3;
} else if ( a.subdetId() == 5 ) {
subdet=2;
component=tTopo->tobLayer(detid);
} else if ( a.subdetId() == 6 ) {
subdet=3;
component=tTopo->tecSide(detid)==2?tTopo->tecWheel(detid):tTopo->tecWheel(detid)+9;
}
int index=100+subdet*100+component;
histos.push_back(getHisto(subdet+1));
histos.push_back(getHisto(index));
}
TH1F*
SiStripPlotGain::getHisto(const long unsigned int& index){
if(vTH1.size()<index+1)
vTH1.resize(index+1,nullptr);
if(vTH1[index]==nullptr){
char name[128];
sprintf(name,"%lu",index);
edm::LogInfo("")<<"[getHisto] creating index " << index << std::endl;
vTH1[index]=new TH1F(name,name,150,0.,5.);
}
return vTH1[index];
}
void
SiStripPlotGain::endJob() {
for(size_t i=0;i<vTH1.size();i++)
if(vTH1[i]!=nullptr)
vTH1[i]->Write();
file->Write();
file->Close();
tkmap->save(false,0,0,"testTkMap.png");
}
| 26.192857 | 112 | 0.658304 | [
"geometry",
"vector"
] |
33e3e2cb0b0e1aafd11e501dd932b107a26065c5 | 7,488 | cpp | C++ | src/Vortex/Debug/Profiler.cpp | Auxione/VortexEngine | 6c443a4b8cdf17c36a280f7c160b2006aac0d33b | [
"MIT"
] | null | null | null | src/Vortex/Debug/Profiler.cpp | Auxione/VortexEngine | 6c443a4b8cdf17c36a280f7c160b2006aac0d33b | [
"MIT"
] | null | null | null | src/Vortex/Debug/Profiler.cpp | Auxione/VortexEngine | 6c443a4b8cdf17c36a280f7c160b2006aac0d33b | [
"MIT"
] | null | null | null | #ifdef VORTEX_DEBUG
#include "Vortex/Debug/Profiler.h"
namespace Vortex::DebugProfiler {
MapType ProfileMap;
MapType FrameProfileMap;
std::chrono::steady_clock::time_point ProfileStartTime;
std::chrono::steady_clock::time_point FrameStartTime;
bool FrameCall{false};
std::size_t FrameCount{0};
DurationType TotalFrameTime{0};
ProfilerResultData::ProfilerResultData(NameType name,
DurationType total_time,
DurationType max_time,
DurationType average_time,
CallCountType call_count,
double utilization):
Name{std::move(name)},
TotalTime{total_time},
MaxTime{max_time},
AverageTime{average_time},
CallCount{call_count},
Utilization{utilization} {}
void BeginProfile() {
ProfileMap.clear();
ProfileStartTime = std::chrono::steady_clock::now();
}
ProfilerResult EndProfile() {
auto profile_duration = std::chrono::steady_clock::now() - ProfileStartTime;
ProfilerResult results;
results.TotalTime = std::chrono::duration_cast<DurationType>(profile_duration);
results.TotalFrameTime = TotalFrameTime;
results.FrameCount = FrameCount;
results.Data.reserve(ProfileMap.size());
for (const auto& data : ProfileMap) {
const auto& name = data.first;
const auto& profile_data = data.second;
auto average_time = profile_data.TotalTime / profile_data.CallCount;
auto utilization = static_cast<double>(profile_data.TotalTime.count()) / static_cast<double>(results.TotalTime.count());
results.Data.emplace_back(
name,
profile_data.TotalTime,
profile_data.MaxTime,
average_time,
profile_data.CallCount,
utilization
);
}
results.FrameData.reserve(FrameProfileMap.size());
for (const auto& data : FrameProfileMap) {
const auto& name = data.first;
const auto& profile_data = data.second;
auto average_time = profile_data.TotalTime / profile_data.CallCount;
auto utilization = static_cast<double>(profile_data.TotalTime.count()) / static_cast<double>(results.TotalTime.count());
results.FrameData.emplace_back(
name,
profile_data.TotalTime,
profile_data.MaxTime,
average_time,
profile_data.CallCount,
utilization
);
}
return results;
}
void BeginFrame() {
FrameCall = true;
FrameStartTime = std::chrono::steady_clock::now();
}
void EndFrame() {
TotalFrameTime += std::chrono::duration_cast<DebugProfiler::DurationType>(std::chrono::steady_clock::now() - FrameStartTime);;
FrameCall = false;
++FrameCount;
}
void RawProfileData::AddTime(const DurationType& elapsed) {
if (MaxTime < elapsed) {
MaxTime = elapsed;
}
TotalTime += elapsed;
++CallCount;
}
void WriteResultsSorted(std::ostream& ostream, const std::vector<ProfilerResultData>& result, std::size_t count) {
char line_buffer[1024];
std::vector<ProfilerResultData> sorted_data{result};
count = count > sorted_data.size() ? sorted_data.size() : count;
sprintf_s(line_buffer, "%-2s : %-16s - %-16s\n", "#", "AverageTime (ms)", "Method Name");
ostream << "\t" << line_buffer;
std::sort(sorted_data.begin(), sorted_data.end(), [](const ProfilerResultData& a, const ProfilerResultData& b) {
return a.AverageTime > b.AverageTime;
});
for (std::size_t i = 0; i < count; ++i) {
sprintf_s(line_buffer, "%-2zu : %-16f - %-16s\n", i + 1, sorted_data[i].AverageTime.count(), sorted_data[i].Name.c_str());
ostream << "\t" << line_buffer;
}
ostream << "\n";
sprintf_s(line_buffer, "%-2s : %-16s - %-16s\n", "#", "MaxTime (ms)", "Method Name");
ostream << "\t" << line_buffer;
std::sort(sorted_data.begin(), sorted_data.end(), [](const ProfilerResultData& a, const ProfilerResultData& b) {
return a.MaxTime > b.MaxTime;
});
for (std::size_t i = 0; i < count; ++i) {
sprintf_s(line_buffer, "%-2zu : %-16f - %-16s\n", i + 1, sorted_data[i].MaxTime.count(), sorted_data[i].Name.c_str());
ostream << "\t" << line_buffer;
}
ostream << "\n";
sprintf_s(line_buffer, "%-2s : %-16s - %-16s\n", "#", "Utilization (%)", "Method Name");
ostream << "\t" << line_buffer;
std::sort(sorted_data.begin(), sorted_data.end(), [](const ProfilerResultData& a, const ProfilerResultData& b) {
return a.Utilization > b.Utilization;
});
for (std::size_t i = 0; i < count; ++i) {
sprintf_s(line_buffer, "%-2zu : %-16.3f - %-16s\n", i + 1, sorted_data[i].Utilization * 100, sorted_data[i].Name.c_str());
ostream << "\t" << line_buffer;
}
}
void WriteExtendedTable(std::ostream& ostream, const std::vector<ProfilerResultData>& result) {
std::vector<ProfilerResultData> sorted_data{result};
std::sort(sorted_data.begin(), sorted_data.end(), [](const ProfilerResultData& a, const ProfilerResultData& b) {
return a.CallCount > b.CallCount;
});
char line_buffer[1024];
sprintf_s(line_buffer, "%-16s | %-16s | %-16s | %-16s | %-16s\n",
"Call Count",
"Utilization (%)",
"AverageTime (ms)",
"MaximumTime (ms)",
"Method Name");
ostream << "\t" << line_buffer;
sprintf_s(line_buffer, "%-16s | %-16s | %-16s | %-16s | %-16s\n",
"----------------",
"----------------",
"----------------",
"----------------",
"----------------");
ostream << "\t" << line_buffer;
for (auto& i : sorted_data) {
sprintf_s(line_buffer, "%-16llu | %-16.3f | %-16f | %-16f | %s\n",
i.CallCount,
i.Utilization * 100,
i.AverageTime.count(),
i.MaxTime.count(),
i.Name.c_str()
);
ostream << "\t" << line_buffer;
}
}
void WriteToStream(std::ostream& ostream, const ProfilerResult& result) {
auto finish_time = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
auto& app_data = result.Data;
auto& app_time = result.TotalTime;
auto& frame_data = result.FrameData;
auto& frame_time = result.TotalFrameTime;
auto& frame_count = result.FrameCount;
std::vector<ProfilerResultData> sorted_data{result.Data};
ostream << "Vortex Profiler\n";
ostream << "\t" << "Creation Time : " << std::put_time(std::localtime(&finish_time), "%Y-%m-%d %X") << "\n";
ostream << "\t" << "Application Time : " << app_time.count() / 1000 << " seconds\n";
ostream << "\t" << "Frame Time : " << frame_time.count() / 1000 << " seconds\n";
ostream << "\t" << "Frame Count : " << frame_count << "\n";
ostream << "\t" << "Average FPS : " << static_cast<double>(frame_count) / (frame_time.count() / 1000) << "\n";
ostream << "\n";
ostream << "Frame Profiling Data:\n";
WriteResultsSorted(ostream, result.FrameData, 5);
ostream << "\n";
WriteExtendedTable(ostream, result.FrameData);
ostream << "\n";
ostream << "Application Profiling Data:\n";
WriteResultsSorted(ostream, result.Data, 5);
ostream << "\n";
WriteExtendedTable(ostream, result.Data);
}
void WriteToFile(const std::filesystem::path& path, const ProfilerResult& result) {
std::ofstream file{path};
WriteToStream(file, result);
}
}
namespace Vortex {
UniqueProfiler::UniqueProfiler(DebugProfiler::KeyType name):
m_Name(std::move(name)),
m_Start(std::chrono::steady_clock::now()) {}
UniqueProfiler::~UniqueProfiler() {
auto end_time = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<DebugProfiler::DurationType>(end_time - m_Start);
if (DebugProfiler::FrameCall) {
DebugProfiler::FrameProfileMap[m_Name].AddTime(duration);
} else {
DebugProfiler::ProfileMap[m_Name].AddTime(duration);
}
}
}
#endif | 33.132743 | 128 | 0.656918 | [
"vector"
] |
33e3e8f293f4373f11531c7adf778a611dfb5e81 | 2,980 | cpp | C++ | py_agc_api/py_agc_api.cpp | agnieszkadanek/agc | f667e75d0c09fa7e046cf6b7df67af9f973c451c | [
"MIT"
] | 52 | 2021-12-22T17:50:47.000Z | 2022-03-23T17:08:50.000Z | py_agc_api/py_agc_api.cpp | agnieszkadanek/agc | f667e75d0c09fa7e046cf6b7df67af9f973c451c | [
"MIT"
] | 1 | 2022-01-26T08:11:52.000Z | 2022-01-26T08:11:52.000Z | py_agc_api/py_agc_api.cpp | agnieszkadanek/agc | f667e75d0c09fa7e046cf6b7df67af9f973c451c | [
"MIT"
] | 4 | 2021-12-22T22:09:22.000Z | 2022-03-18T12:43:09.000Z | #include <pybind11/pybind11.h>
#include <pybind11/operators.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <core/agc_decompressor.h>
#include <lib-cxx/agc-api.h>
//binding STL container std::vector<std::string>
PYBIND11_MAKE_OPAQUE(std::vector<std::string>);
namespace py = pybind11;
PYBIND11_MODULE(py_agc_api, m) {
m.doc() = "Python wrapper for AGC_API."; // optional module docstring
// StringVector can be used in Python code (binding std::vector<std::string>)
py::bind_vector<std::vector<std::string>>(m, "StringVector");
// Class that represents agc archive
py::class_<CAGCFile>(m, "CAGCFile")
.def(py::init<>()) //parameterless constructor
//Open(file_name, prefetching = true) opens agc archive
//
//@return true for success and false for error
.def("Open", &CAGCFile::Open)
//Close() closes opened archive
//@return true for success and false for error
.def("Close", &CAGCFile::Close) //Close() closes opened archive
//NSample()
//@returns number of samples in the archive
.def("NSample", &CAGCFile::NSample)
//NCtg(sample)
//@returns number of contig in sample
.def("NCtg", &CAGCFile::NCtg)
//ListSample(samples: StringVector)
//@param samples vector of strings (StringVector) with sample names (returned value)
//@return number of samples to be written to
.def("ListSample", &CAGCFile::ListSample)
//ListCtg(sample, names: StringVector)
//@param sample sample name
//@param names vector of strings (StringVector) with contig names (returned value)
//@return number of contigs in the sample
.def("ListCtg", &CAGCFile::ListCtg)
//GetCtgLen(sample, name)
//Get the length of a contig.
//@param sample sample name;
//@param name contig name
//@return contig length, or <0 for errors
.def("GetCtgLen", &CAGCFile::GetCtgLen)
//GetCtgSeq(sample, name, start, end)
//@param sample sample name
//@param name contig name
//@param start start offset
//@param end end offset
//@return contig sequence
.def("GetCtgSeq", [](CAGCFile& ptr, const std::string& sample, const std::string& name, int start, int end) { std::string s; s.resize(end-start+1); ptr.GetCtgSeq(sample, name, start, end, s); return s;})
//GetCtgSeq(name, start, end)
//@param name contig name
//@param start start offset
//@param end end offset
//@return contig sequence (if unique name across all contigs in all samples)
.def("GetCtgSeq", [](CAGCFile& ptr, const std::string& name, int start, int end) { std::string s; s.resize(end-start+1); std::string empty; ptr.GetCtgSeq(empty, name, start, end, s); return s;})
;
}
| 38.701299 | 212 | 0.615101 | [
"vector"
] |
33e55d59e16cd5701f25d0a33b8efcc71fc27d74 | 1,686 | hpp | C++ | src/game_api/containers/game_allocator.hpp | spelunky-fyi/rust-injector | 45ba8acbb6c8505ace288640e764e8557c6f298f | [
"MIT"
] | null | null | null | src/game_api/containers/game_allocator.hpp | spelunky-fyi/rust-injector | 45ba8acbb6c8505ace288640e764e8557c6f298f | [
"MIT"
] | null | null | null | src/game_api/containers/game_allocator.hpp | spelunky-fyi/rust-injector | 45ba8acbb6c8505ace288640e764e8557c6f298f | [
"MIT"
] | 1 | 2020-11-15T05:43:12.000Z | 2020-11-15T05:43:12.000Z | #pragma once
#include <cstddef>
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
void* game_malloc(std::size_t size);
void game_free(void* mem);
// This is an allocator that always uses the malloc/free implementations that the game provides
// Thus it avoids CRT-mismatch while debugging and should be used in stl-containers that the
// game creates/destroys but we want to modify anyways
template <typename T>
struct game_allocator
{
game_allocator() = default;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template <class U>
struct rebind
{
typedef game_allocator<U> other;
};
template <class U>
game_allocator(const game_allocator<U>&)
{
}
pointer address(reference x) const
{
return &x;
}
const_pointer address(const_reference x) const
{
return &x;
}
size_type max_size() const throw()
{
return size_type(-1) / sizeof(value_type);
}
pointer allocate(size_type n, [[maybe_unused]] void* hint = nullptr)
{
return static_cast<pointer>(game_malloc(n * sizeof(T)));
}
void deallocate(pointer p, [[maybe_unused]] size_type n)
{
game_free(p);
}
void construct(pointer p, const T& val)
{
new (static_cast<void*>(p)) T(val);
}
void construct(pointer p)
{
new (static_cast<void*>(p)) T();
}
void destroy(pointer p)
{
p->~T();
}
};
| 21.341772 | 95 | 0.638197 | [
"vector"
] |
33e5a644f6455e1b6f5ad660bb931cd63fb2ec13 | 1,334 | cpp | C++ | chap4/ex4_16.cpp | ksvbka/pppuc | 840962dd612ab4f2b2c638409089cd889c417c8f | [
"MIT"
] | 2 | 2016-05-06T02:08:38.000Z | 2016-05-10T02:19:05.000Z | chap4/ex4_16.cpp | ksvbka/pppuc | 840962dd612ab4f2b2c638409089cd889c417c8f | [
"MIT"
] | null | null | null | chap4/ex4_16.cpp | ksvbka/pppuc | 840962dd612ab4f2b2c638409089cd889c417c8f | [
"MIT"
] | 1 | 2020-11-01T13:06:15.000Z | 2020-11-01T13:06:15.000Z | /*Ex 4.16 In the drill, you wrote a program that, given a series of numbers, found
the max and min of that series. The number that appears the most times in a
sequence is called the mode. Create a program that finds the mode of a set of
positive integers.*/
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
/*Create data struct to hold number and count*/
struct Number {
int value;
int count;
Number(): value(0), count(0) {}
Number(int _value) : value(_value), count(0) {}
};
int main(int argc, char const *argv[]) {
vector<Number> vec;
int flag = 0;
/* Input value */
cout << "Enter the series integer, end with \"e\" " << endl;
for (int n; cin >> n;) {
if (vec.size() == 0)
vec.push_back(n);
else {
for (int i = 0; i < vec.size(); ++i) {
if (vec[i].value == n) {
vec[i].count++;
flag = 1;
}
}
if (!flag)
vec.push_back(n);
flag = 0;
}
}
/*Find "mode" */
Number mode = vec[0];
for (auto elem : vec) {
if (mode.count < elem.count)
mode = elem;
}
cout << "Mode of array is: " << mode.value << " Count: " << mode.count << endl;
return 0;
}
| 24.254545 | 83 | 0.516492 | [
"vector"
] |
33e7e4d5eb9805b6a82d3c5fd88e210227e068da | 38,082 | cpp | C++ | worker/src/RTC/DtlsTransport.cpp | wangxiaoliang04/mediasoup | af7ba8ac0ed49827555fd555ef8b6c7db114f25f | [
"0BSD"
] | 1 | 2020-03-27T13:52:45.000Z | 2020-03-27T13:52:45.000Z | worker/src/RTC/DtlsTransport.cpp | wangxiaoliang04/mediasoup | af7ba8ac0ed49827555fd555ef8b6c7db114f25f | [
"0BSD"
] | null | null | null | worker/src/RTC/DtlsTransport.cpp | wangxiaoliang04/mediasoup | af7ba8ac0ed49827555fd555ef8b6c7db114f25f | [
"0BSD"
] | null | null | null | #define MS_CLASS "RTC::DtlsTransport"
// #define MS_LOG_DEV_LEVEL 3
#include "RTC/DtlsTransport.hpp"
#include "Logger.hpp"
#include "MediaSoupErrors.hpp"
#include "Settings.hpp"
#include "Utils.hpp"
#include <openssl/asn1.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <uv.h>
#include <cstdio> // std::sprintf(), std::fopen()
#include <cstring> // std::memcpy(), std::strcmp()
#define LOG_OPENSSL_ERROR(desc) \
do \
{ \
if (ERR_peek_error() == 0) \
MS_ERROR("OpenSSL error [desc:'%s']", desc); \
else \
{ \
int64_t err; \
while ((err = ERR_get_error()) != 0) \
{ \
MS_ERROR("OpenSSL error [desc:'%s', error:'%s']", desc, ERR_error_string(err, nullptr)); \
} \
ERR_clear_error(); \
} \
} while (false)
/* Static methods for OpenSSL callbacks. */
inline static int onSslCertificateVerify(int /*preverifyOk*/, X509_STORE_CTX* /*ctx*/)
{
MS_TRACE();
// Always valid since DTLS certificates are self-signed.
return 1;
}
inline static void onSslInfo(const SSL* ssl, int where, int ret)
{
static_cast<RTC::DtlsTransport*>(SSL_get_ex_data(ssl, 0))->OnSslInfo(where, ret);
}
inline static unsigned int onSslDtlsTimer(SSL* /*ssl*/, unsigned int timerUs)
{
if (timerUs == 0)
return 100000;
else if (timerUs >= 4000000)
return 4000000;
else
return 2 * timerUs;
}
namespace RTC
{
/* Static. */
// clang-format off
static constexpr int DtlsMtu{ 1350 };
static constexpr int SslReadBufferSize{ 65536 };
// AES-HMAC: http://tools.ietf.org/html/rfc3711
static constexpr size_t SrtpMasterKeyLength{ 16 };
static constexpr size_t SrtpMasterSaltLength{ 14 };
static constexpr size_t SrtpMasterLength{ SrtpMasterKeyLength + SrtpMasterSaltLength };
// AES-GCM: http://tools.ietf.org/html/rfc7714
static constexpr size_t SrtpAesGcm256MasterKeyLength{ 32 };
static constexpr size_t SrtpAesGcm256MasterSaltLength{ 12 };
static constexpr size_t SrtpAesGcm256MasterLength{ SrtpAesGcm256MasterKeyLength + SrtpAesGcm256MasterSaltLength };
static constexpr size_t SrtpAesGcm128MasterKeyLength{ 16 };
static constexpr size_t SrtpAesGcm128MasterSaltLength{ 12 };
static constexpr size_t SrtpAesGcm128MasterLength{ SrtpAesGcm128MasterKeyLength + SrtpAesGcm128MasterSaltLength };
// clang-format on
/* Class variables. */
X509* DtlsTransport::certificate{ nullptr };
EVP_PKEY* DtlsTransport::privateKey{ nullptr };
SSL_CTX* DtlsTransport::sslCtx{ nullptr };
uint8_t DtlsTransport::sslReadBuffer[SslReadBufferSize];
// clang-format off
std::map<std::string, DtlsTransport::FingerprintAlgorithm> DtlsTransport::string2FingerprintAlgorithm =
{
{ "sha-1", DtlsTransport::FingerprintAlgorithm::SHA1 },
{ "sha-224", DtlsTransport::FingerprintAlgorithm::SHA224 },
{ "sha-256", DtlsTransport::FingerprintAlgorithm::SHA256 },
{ "sha-384", DtlsTransport::FingerprintAlgorithm::SHA384 },
{ "sha-512", DtlsTransport::FingerprintAlgorithm::SHA512 }
};
std::map<DtlsTransport::FingerprintAlgorithm, std::string> DtlsTransport::fingerprintAlgorithm2String =
{
{ DtlsTransport::FingerprintAlgorithm::SHA1, "sha-1" },
{ DtlsTransport::FingerprintAlgorithm::SHA224, "sha-224" },
{ DtlsTransport::FingerprintAlgorithm::SHA256, "sha-256" },
{ DtlsTransport::FingerprintAlgorithm::SHA384, "sha-384" },
{ DtlsTransport::FingerprintAlgorithm::SHA512, "sha-512" }
};
std::map<std::string, DtlsTransport::Role> DtlsTransport::string2Role =
{
{ "auto", DtlsTransport::Role::AUTO },
{ "client", DtlsTransport::Role::CLIENT },
{ "server", DtlsTransport::Role::SERVER }
};
std::vector<DtlsTransport::Fingerprint> DtlsTransport::localFingerprints;
std::vector<DtlsTransport::SrtpCryptoSuiteMapEntry> DtlsTransport::srtpCryptoSuites =
{
{ RTC::SrtpSession::CryptoSuite::AEAD_AES_256_GCM, "SRTP_AEAD_AES_256_GCM" },
{ RTC::SrtpSession::CryptoSuite::AEAD_AES_128_GCM, "SRTP_AEAD_AES_128_GCM" },
{ RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_80, "SRTP_AES128_CM_SHA1_80" },
{ RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_32, "SRTP_AES128_CM_SHA1_32" }
};
// clang-format on
/* Class methods. */
void DtlsTransport::ClassInit()
{
MS_TRACE();
// Generate a X509 certificate and private key (unless PEM files are provided).
if (
Settings::configuration.dtlsCertificateFile.empty() ||
Settings::configuration.dtlsPrivateKeyFile.empty())
{
GenerateCertificateAndPrivateKey();
}
else
{
ReadCertificateAndPrivateKeyFromFiles();
}
// Create a global SSL_CTX.
CreateSslCtx();
// Generate certificate fingerprints.
GenerateFingerprints();
}
void DtlsTransport::ClassDestroy()
{
MS_TRACE();
if (DtlsTransport::privateKey)
EVP_PKEY_free(DtlsTransport::privateKey);
if (DtlsTransport::certificate)
X509_free(DtlsTransport::certificate);
if (DtlsTransport::sslCtx)
SSL_CTX_free(DtlsTransport::sslCtx);
}
void DtlsTransport::GenerateCertificateAndPrivateKey()
{
MS_TRACE();
int ret{ 0 };
BIGNUM* bne{ nullptr };
RSA* rsaKey{ nullptr };
int numBits{ 1024 };
X509_NAME* certName{ nullptr };
std::string subject =
std::string("mediasoup") + std::to_string(Utils::Crypto::GetRandomUInt(100000, 999999));
// Create a big number object.
bne = BN_new();
if (!bne)
{
LOG_OPENSSL_ERROR("BN_new() failed");
goto error;
}
ret = BN_set_word(bne, RSA_F4); // RSA_F4 == 65537.
if (ret == 0)
{
LOG_OPENSSL_ERROR("BN_set_word() failed");
goto error;
}
// Generate a RSA key.
rsaKey = RSA_new();
if (!rsaKey)
{
LOG_OPENSSL_ERROR("RSA_new() failed");
goto error;
}
// This takes some time.
ret = RSA_generate_key_ex(rsaKey, numBits, bne, nullptr);
if (ret == 0)
{
LOG_OPENSSL_ERROR("RSA_generate_key_ex() failed");
goto error;
}
// Create a private key object (needed to hold the RSA key).
DtlsTransport::privateKey = EVP_PKEY_new();
if (!DtlsTransport::privateKey)
{
LOG_OPENSSL_ERROR("EVP_PKEY_new() failed");
goto error;
}
ret = EVP_PKEY_assign_RSA(DtlsTransport::privateKey, rsaKey); // NOLINT
if (ret == 0)
{
LOG_OPENSSL_ERROR("EVP_PKEY_assign_RSA() failed");
goto error;
}
// The RSA key now belongs to the private key, so don't clean it up separately.
rsaKey = nullptr;
// Create the X509 certificate.
DtlsTransport::certificate = X509_new();
if (!DtlsTransport::certificate)
{
LOG_OPENSSL_ERROR("X509_new() failed");
goto error;
}
// Set version 3 (note that 0 means version 1).
X509_set_version(DtlsTransport::certificate, 2);
// Set serial number (avoid default 0).
ASN1_INTEGER_set(
X509_get_serialNumber(DtlsTransport::certificate),
static_cast<uint64_t>(Utils::Crypto::GetRandomUInt(1000000, 9999999)));
// Set valid period.
X509_gmtime_adj(X509_get_notBefore(DtlsTransport::certificate), -315360000); // -10 years.
X509_gmtime_adj(X509_get_notAfter(DtlsTransport::certificate), 315360000); // 10 years.
// Set the public key for the certificate using the key.
ret = X509_set_pubkey(DtlsTransport::certificate, DtlsTransport::privateKey);
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_set_pubkey() failed");
goto error;
}
// Set certificate fields.
certName = X509_get_subject_name(DtlsTransport::certificate);
if (!certName)
{
LOG_OPENSSL_ERROR("X509_get_subject_name() failed");
goto error;
}
X509_NAME_add_entry_by_txt(
certName, "O", MBSTRING_ASC, reinterpret_cast<const uint8_t*>(subject.c_str()), -1, -1, 0);
X509_NAME_add_entry_by_txt(
certName, "CN", MBSTRING_ASC, reinterpret_cast<const uint8_t*>(subject.c_str()), -1, -1, 0);
// It is self-signed so set the issuer name to be the same as the subject.
ret = X509_set_issuer_name(DtlsTransport::certificate, certName);
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_set_issuer_name() failed");
goto error;
}
// Sign the certificate with its own private key.
ret = X509_sign(DtlsTransport::certificate, DtlsTransport::privateKey, EVP_sha1());
if (ret == 0)
{
LOG_OPENSSL_ERROR("X509_sign() failed");
goto error;
}
// Free stuff and return.
BN_free(bne);
return;
error:
if (bne)
BN_free(bne);
if (rsaKey && !DtlsTransport::privateKey)
RSA_free(rsaKey);
if (DtlsTransport::privateKey)
EVP_PKEY_free(DtlsTransport::privateKey); // NOTE: This also frees the RSA key.
if (DtlsTransport::certificate)
X509_free(DtlsTransport::certificate);
MS_THROW_ERROR("DTLS certificate and private key generation failed");
}
void DtlsTransport::ReadCertificateAndPrivateKeyFromFiles()
{
MS_TRACE();
FILE* file{ nullptr };
file = fopen(Settings::configuration.dtlsCertificateFile.c_str(), "r");
if (!file)
{
MS_ERROR("error reading DTLS certificate file: %s", std::strerror(errno));
goto error;
}
DtlsTransport::certificate = PEM_read_X509(file, nullptr, nullptr, nullptr);
if (!DtlsTransport::certificate)
{
LOG_OPENSSL_ERROR("PEM_read_X509() failed");
goto error;
}
fclose(file);
file = fopen(Settings::configuration.dtlsPrivateKeyFile.c_str(), "r");
if (!file)
{
MS_ERROR("error reading DTLS private key file: %s", std::strerror(errno));
goto error;
}
DtlsTransport::privateKey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
if (!DtlsTransport::privateKey)
{
LOG_OPENSSL_ERROR("PEM_read_PrivateKey() failed");
goto error;
}
fclose(file);
return;
error:
MS_THROW_ERROR("error reading DTLS certificate and private key PEM files");
}
void DtlsTransport::CreateSslCtx()
{
MS_TRACE();
std::string dtlsSrtpCryptoSuites;
EC_KEY* ecdh{ nullptr };
int ret;
/* Set the global DTLS context. */
// Both DTLS 1.0 and 1.2 (requires OpenSSL >= 1.1.0).
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
DtlsTransport::sslCtx = SSL_CTX_new(DTLS_method());
// Just DTLS 1.0 (requires OpenSSL >= 1.0.1).
#elif (OPENSSL_VERSION_NUMBER >= 0x10001000L)
DtlsTransport::sslCtx = SSL_CTX_new(DTLSv1_method());
#else
#error "too old OpenSSL version"
#endif
if (!DtlsTransport::sslCtx)
{
LOG_OPENSSL_ERROR("SSL_CTX_new() failed");
goto error;
}
ret = SSL_CTX_use_certificate(DtlsTransport::sslCtx, DtlsTransport::certificate);
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_use_certificate() failed");
goto error;
}
ret = SSL_CTX_use_PrivateKey(DtlsTransport::sslCtx, DtlsTransport::privateKey);
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_use_PrivateKey() failed");
goto error;
}
ret = SSL_CTX_check_private_key(DtlsTransport::sslCtx);
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_check_private_key() failed");
goto error;
}
// Set options.
SSL_CTX_set_options(
DtlsTransport::sslCtx,
SSL_OP_CIPHER_SERVER_PREFERENCE | SSL_OP_NO_TICKET | SSL_OP_SINGLE_ECDH_USE |
SSL_OP_NO_QUERY_MTU);
// Don't use sessions cache.
SSL_CTX_set_session_cache_mode(DtlsTransport::sslCtx, SSL_SESS_CACHE_OFF);
// Read always as much into the buffer as possible.
// NOTE: This is the default for DTLS, but a bug in non latest OpenSSL
// versions makes this call required.
SSL_CTX_set_read_ahead(DtlsTransport::sslCtx, 1);
SSL_CTX_set_verify_depth(DtlsTransport::sslCtx, 4);
// Require certificate from peer.
SSL_CTX_set_verify(
DtlsTransport::sslCtx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, onSslCertificateVerify);
// Set SSL info callback.
SSL_CTX_set_info_callback(DtlsTransport::sslCtx, onSslInfo);
// Set ciphers.
ret = SSL_CTX_set_cipher_list(
DtlsTransport::sslCtx, "ALL:!ADH:!LOW:!EXP:!MD5:!aNULL:!eNULL:@STRENGTH");
if (ret == 0)
{
LOG_OPENSSL_ERROR("SSL_CTX_set_cipher_list() failed");
goto error;
}
// Enable ECDH ciphers.
// DOC: http://en.wikibooks.org/wiki/OpenSSL/Diffie-Hellman_parameters
// NOTE: https://code.google.com/p/chromium/issues/detail?id=406458
// NOTE: https://bugs.ruby-lang.org/issues/12324
//
// Nothing to be done in OpenSSL >= 1.1.0.
#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
// For OpenSSL >= 1.0.2.
#elif (OPENSSL_VERSION_NUMBER >= 0x10002000L)
SSL_CTX_set_ecdh_auto(DtlsTransport::sslCtx, 1);
// Older versions.
#else
ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
if (!ecdh)
{
LOG_OPENSSL_ERROR("EC_KEY_new_by_curve_name() failed");
goto error;
}
if (SSL_CTX_set_tmp_ecdh(DtlsTransport::sslCtx, ecdh) != 1)
{
LOG_OPENSSL_ERROR("SSL_CTX_set_tmp_ecdh() failed");
goto error;
}
EC_KEY_free(ecdh);
ecdh = nullptr;
#endif
// Set the "use_srtp" DTLS extension.
for (auto it = DtlsTransport::srtpCryptoSuites.begin();
it != DtlsTransport::srtpCryptoSuites.end();
++it)
{
if (it != DtlsTransport::srtpCryptoSuites.begin())
dtlsSrtpCryptoSuites += ":";
SrtpCryptoSuiteMapEntry* cryptoSuiteEntry = std::addressof(*it);
dtlsSrtpCryptoSuites += cryptoSuiteEntry->name;
}
MS_DEBUG_2TAGS(dtls, srtp, "setting SRTP cryptoSuites for DTLS: %s", dtlsSrtpCryptoSuites.c_str());
// NOTE: This function returns 0 on success.
ret = SSL_CTX_set_tlsext_use_srtp(DtlsTransport::sslCtx, dtlsSrtpCryptoSuites.c_str());
if (ret != 0)
{
MS_ERROR(
"SSL_CTX_set_tlsext_use_srtp() failed when entering '%s'", dtlsSrtpCryptoSuites.c_str());
LOG_OPENSSL_ERROR("SSL_CTX_set_tlsext_use_srtp() failed");
goto error;
}
return;
error:
if (DtlsTransport::sslCtx)
{
SSL_CTX_free(DtlsTransport::sslCtx);
DtlsTransport::sslCtx = nullptr;
}
if (ecdh)
EC_KEY_free(ecdh);
MS_THROW_ERROR("SSL context creation failed");
}
void DtlsTransport::GenerateFingerprints()
{
MS_TRACE();
for (auto& kv : DtlsTransport::string2FingerprintAlgorithm)
{
const std::string& algorithmString = kv.first;
FingerprintAlgorithm algorithm = kv.second;
uint8_t binaryFingerprint[EVP_MAX_MD_SIZE];
unsigned int size{ 0 };
char hexFingerprint[(EVP_MAX_MD_SIZE * 3) + 1];
const EVP_MD* hashFunction;
int ret;
switch (algorithm)
{
case FingerprintAlgorithm::SHA1:
hashFunction = EVP_sha1();
break;
case FingerprintAlgorithm::SHA224:
hashFunction = EVP_sha224();
break;
case FingerprintAlgorithm::SHA256:
hashFunction = EVP_sha256();
break;
case FingerprintAlgorithm::SHA384:
hashFunction = EVP_sha384();
break;
case FingerprintAlgorithm::SHA512:
hashFunction = EVP_sha512();
break;
default:
MS_THROW_ERROR("unknown algorithm");
}
ret = X509_digest(DtlsTransport::certificate, hashFunction, binaryFingerprint, &size);
if (ret == 0)
{
MS_ERROR("X509_digest() failed");
MS_THROW_ERROR("Fingerprints generation failed");
}
// Convert to hexadecimal format in uppercase with colons.
for (unsigned int i{ 0 }; i < size; ++i)
{
std::sprintf(hexFingerprint + (i * 3), "%.2X:", binaryFingerprint[i]);
}
hexFingerprint[(size * 3) - 1] = '\0';
MS_DEBUG_TAG(dtls, "%-7s fingerprint: %s", algorithmString.c_str(), hexFingerprint);
// Store it in the vector.
DtlsTransport::Fingerprint fingerprint;
fingerprint.algorithm = DtlsTransport::GetFingerprintAlgorithm(algorithmString);
fingerprint.value = hexFingerprint;
DtlsTransport::localFingerprints.push_back(fingerprint);
}
}
/* Instance methods. */
DtlsTransport::DtlsTransport(Listener* listener) : listener(listener)
{
MS_TRACE();
/* Set SSL. */
this->ssl = SSL_new(DtlsTransport::sslCtx);
if (!this->ssl)
{
LOG_OPENSSL_ERROR("SSL_new() failed");
goto error;
}
// Set this as custom data.
SSL_set_ex_data(this->ssl, 0, static_cast<void*>(this));
this->sslBioFromNetwork = BIO_new(BIO_s_mem());
if (!this->sslBioFromNetwork)
{
LOG_OPENSSL_ERROR("BIO_new() failed");
SSL_free(this->ssl);
goto error;
}
this->sslBioToNetwork = BIO_new(BIO_s_mem());
if (!this->sslBioToNetwork)
{
LOG_OPENSSL_ERROR("BIO_new() failed");
BIO_free(this->sslBioFromNetwork);
SSL_free(this->ssl);
goto error;
}
SSL_set_bio(this->ssl, this->sslBioFromNetwork, this->sslBioToNetwork);
// Set the MTU so that we don't send packets that are too large with no fragmentation.
SSL_set_mtu(this->ssl, DtlsMtu);
DTLS_set_link_mtu(this->ssl, DtlsMtu);
// Set callback handler for setting DTLS timer interval.
DTLS_set_timer_cb(this->ssl, onSslDtlsTimer);
// Set the DTLS timer.
this->timer = new Timer(this);
return;
error:
// NOTE: At this point SSL_set_bio() was not called so we must free BIOs as
// well.
if (this->sslBioFromNetwork)
BIO_free(this->sslBioFromNetwork);
if (this->sslBioToNetwork)
BIO_free(this->sslBioToNetwork);
if (this->ssl)
SSL_free(this->ssl);
// NOTE: If this is not catched by the caller the program will abort, but
// this should never happen.
MS_THROW_ERROR("DtlsTransport instance creation failed");
}
DtlsTransport::~DtlsTransport()
{
MS_TRACE();
if (IsRunning())
{
// Send close alert to the peer.
SSL_shutdown(this->ssl);
SendPendingOutgoingDtlsData();
}
if (this->ssl)
{
SSL_free(this->ssl);
this->ssl = nullptr;
this->sslBioFromNetwork = nullptr;
this->sslBioToNetwork = nullptr;
}
// Close the DTLS timer.
delete this->timer;
}
void DtlsTransport::Dump() const
{
MS_TRACE();
std::string state{ "new" };
std::string role{ "none " };
switch (this->state)
{
case DtlsState::CONNECTING:
state = "connecting";
break;
case DtlsState::CONNECTED:
state = "connected";
break;
case DtlsState::FAILED:
state = "failed";
break;
case DtlsState::CLOSED:
state = "closed";
break;
default:;
}
switch (this->localRole)
{
case Role::AUTO:
role = "auto";
break;
case Role::SERVER:
role = "server";
break;
case Role::CLIENT:
role = "client";
break;
default:;
}
MS_DUMP("<DtlsTransport>");
MS_DUMP(" state : %s", state.c_str());
MS_DUMP(" role : %s", role.c_str());
MS_DUMP(" handshake done: : %s", this->handshakeDone ? "yes" : "no");
MS_DUMP("</DtlsTransport>");
}
void DtlsTransport::Run(Role localRole)
{
MS_TRACE();
MS_ASSERT(
localRole == Role::CLIENT || localRole == Role::SERVER,
"local DTLS role must be 'client' or 'server'");
Role previousLocalRole = this->localRole;
if (localRole == previousLocalRole)
{
MS_ERROR("same local DTLS role provided, doing nothing");
return;
}
// If the previous local DTLS role was 'client' or 'server' do reset.
if (previousLocalRole == Role::CLIENT || previousLocalRole == Role::SERVER)
{
MS_DEBUG_TAG(dtls, "resetting DTLS due to local role change");
Reset();
}
// Update local role.
this->localRole = localRole;
// Set state and notify the listener.
this->state = DtlsState::CONNECTING;
this->listener->OnDtlsTransportConnecting(this);
switch (this->localRole)
{
case Role::CLIENT:
{
MS_DEBUG_TAG(dtls, "running [role:client]");
SSL_set_connect_state(this->ssl);
SSL_do_handshake(this->ssl);
SendPendingOutgoingDtlsData();
SetTimeout();
break;
}
case Role::SERVER:
{
MS_DEBUG_TAG(dtls, "running [role:server]");
SSL_set_accept_state(this->ssl);
SSL_do_handshake(this->ssl);
break;
}
default:
{
MS_ABORT("invalid local DTLS role");
}
}
}
bool DtlsTransport::SetRemoteFingerprint(Fingerprint fingerprint)
{
MS_TRACE();
MS_ASSERT(
fingerprint.algorithm != FingerprintAlgorithm::NONE, "no fingerprint algorithm provided");
this->remoteFingerprint = fingerprint;
// The remote fingerpring may have been set after DTLS handshake was done,
// so we may need to process it now.
if (this->handshakeDone && this->state != DtlsState::CONNECTED)
{
MS_DEBUG_TAG(dtls, "handshake already done, processing it right now");
return ProcessHandshake();
}
return true;
}
void DtlsTransport::ProcessDtlsData(const uint8_t* data, size_t len)
{
MS_TRACE();
int written;
int read;
if (!IsRunning())
{
MS_ERROR("cannot process data while not running");
return;
}
// Write the received DTLS data into the sslBioFromNetwork.
written =
BIO_write(this->sslBioFromNetwork, static_cast<const void*>(data), static_cast<int>(len));
if (written != static_cast<int>(len))
{
MS_WARN_TAG(
dtls,
"OpenSSL BIO_write() wrote less (%zu bytes) than given data (%zu bytes)",
static_cast<size_t>(written),
len);
}
// Must call SSL_read() to process received DTLS data.
read = SSL_read(this->ssl, static_cast<void*>(DtlsTransport::sslReadBuffer), SslReadBufferSize);
// Send data if it's ready.
SendPendingOutgoingDtlsData();
// Check SSL status and return if it is bad/closed.
if (!CheckStatus(read))
return;
// Set/update the DTLS timeout.
if (!SetTimeout())
return;
// Application data received. Notify to the listener.
if (read > 0)
{
// It is allowed to receive DTLS data even before validating remote fingerprint.
if (!this->handshakeDone)
{
MS_WARN_TAG(dtls, "ignoring application data received while DTLS handshake not done");
return;
}
// Notify the listener.
this->listener->OnDtlsTransportApplicationDataReceived(
this, (uint8_t*)DtlsTransport::sslReadBuffer, static_cast<size_t>(read));
}
}
void DtlsTransport::SendApplicationData(const uint8_t* data, size_t len)
{
MS_TRACE();
// We cannot send data to the peer if its remote fingerprint is not validated.
if (this->state != DtlsState::CONNECTED)
{
MS_WARN_TAG(dtls, "cannot send application data while DTLS is not fully connected");
return;
}
if (len == 0)
{
MS_WARN_TAG(dtls, "ignoring 0 length data");
return;
}
int written;
written = SSL_write(this->ssl, static_cast<const void*>(data), static_cast<int>(len));
if (written < 0)
{
LOG_OPENSSL_ERROR("SSL_write() failed");
if (!CheckStatus(written))
return;
}
else if (written != static_cast<int>(len))
{
MS_WARN_TAG(
dtls, "OpenSSL SSL_write() wrote less (%d bytes) than given data (%zu bytes)", written, len);
}
// Send data.
SendPendingOutgoingDtlsData();
}
void DtlsTransport::Reset()
{
MS_TRACE();
int ret;
if (!IsRunning())
return;
MS_WARN_TAG(dtls, "resetting DTLS transport");
// Stop the DTLS timer.
this->timer->Stop();
// We need to reset the SSL instance so we need to "shutdown" it, but we
// don't want to send a Close Alert to the peer, so just don't call
// SendPendingOutgoingDTLSData().
SSL_shutdown(this->ssl);
this->localRole = Role::NONE;
this->state = DtlsState::NEW;
this->handshakeDone = false;
this->handshakeDoneNow = false;
// Reset SSL status.
// NOTE: For this to properly work, SSL_shutdown() must be called before.
// NOTE: This may fail if not enough DTLS handshake data has been received,
// but we don't care so just clear the error queue.
ret = SSL_clear(this->ssl);
if (ret == 0)
ERR_clear_error();
}
inline bool DtlsTransport::CheckStatus(int returnCode)
{
MS_TRACE();
int err;
bool wasHandshakeDone = this->handshakeDone;
err = SSL_get_error(this->ssl, returnCode);
switch (err)
{
case SSL_ERROR_NONE:
break;
case SSL_ERROR_SSL:
LOG_OPENSSL_ERROR("SSL status: SSL_ERROR_SSL");
break;
case SSL_ERROR_WANT_READ:
break;
case SSL_ERROR_WANT_WRITE:
MS_WARN_TAG(dtls, "SSL status: SSL_ERROR_WANT_WRITE");
break;
case SSL_ERROR_WANT_X509_LOOKUP:
MS_DEBUG_TAG(dtls, "SSL status: SSL_ERROR_WANT_X509_LOOKUP");
break;
case SSL_ERROR_SYSCALL:
LOG_OPENSSL_ERROR("SSL status: SSL_ERROR_SYSCALL");
break;
case SSL_ERROR_ZERO_RETURN:
break;
case SSL_ERROR_WANT_CONNECT:
MS_WARN_TAG(dtls, "SSL status: SSL_ERROR_WANT_CONNECT");
break;
case SSL_ERROR_WANT_ACCEPT:
MS_WARN_TAG(dtls, "SSL status: SSL_ERROR_WANT_ACCEPT");
break;
default:
MS_WARN_TAG(dtls, "SSL status: unknown error");
}
// Check if the handshake (or re-handshake) has been done right now.
if (this->handshakeDoneNow)
{
this->handshakeDoneNow = false;
this->handshakeDone = true;
// Stop the timer.
this->timer->Stop();
// Process the handshake just once (ignore if DTLS renegotiation).
if (!wasHandshakeDone && this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE)
return ProcessHandshake();
return true;
}
// Check if the peer sent close alert or a fatal error happened.
else if (((SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN) != 0) || err == SSL_ERROR_SSL || err == SSL_ERROR_SYSCALL)
{
if (this->state == DtlsState::CONNECTED)
{
MS_DEBUG_TAG(dtls, "disconnected");
Reset();
// Set state and notify the listener.
this->state = DtlsState::CLOSED;
this->listener->OnDtlsTransportClosed(this);
}
else
{
MS_WARN_TAG(dtls, "connection failed");
Reset();
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
}
return false;
}
else
{
return true;
}
}
inline void DtlsTransport::SendPendingOutgoingDtlsData()
{
MS_TRACE();
if (BIO_eof(this->sslBioToNetwork))
return;
int64_t read;
char* data{ nullptr };
read = BIO_get_mem_data(this->sslBioToNetwork, &data); // NOLINT
if (read <= 0)
return;
MS_DEBUG_DEV("%" PRIu64 " bytes of DTLS data ready to sent to the peer", read);
// Notify the listener.
this->listener->OnDtlsTransportSendData(
this, reinterpret_cast<uint8_t*>(data), static_cast<size_t>(read));
// Clear the BIO buffer.
// NOTE: the (void) avoids the -Wunused-value warning.
(void)BIO_reset(this->sslBioToNetwork);
}
inline bool DtlsTransport::SetTimeout()
{
MS_TRACE();
MS_ASSERT(
this->state == DtlsState::CONNECTING || this->state == DtlsState::CONNECTED,
"invalid DTLS state");
int64_t ret;
uv_timeval_t dtlsTimeout{ 0, 0 };
uint64_t timeoutMs;
// NOTE: If ret == 0 then ignore the value in dtlsTimeout.
// NOTE: No DTLSv_1_2_get_timeout() or DTLS_get_timeout() in OpenSSL 1.1.0-dev.
ret = DTLSv1_get_timeout(this->ssl, static_cast<void*>(&dtlsTimeout)); // NOLINT
if (ret == 0)
return true;
timeoutMs = (dtlsTimeout.tv_sec * static_cast<uint64_t>(1000)) + (dtlsTimeout.tv_usec / 1000);
if (timeoutMs == 0)
{
return true;
}
else if (timeoutMs < 30000)
{
MS_DEBUG_DEV("DTLS timer set in %" PRIu64 "ms", timeoutMs);
this->timer->Start(timeoutMs);
return true;
}
// NOTE: Don't start the timer again if the timeout is greater than 30 seconds.
else
{
MS_WARN_TAG(dtls, "DTLS timeout too high (%" PRIu64 "ms), resetting DLTS", timeoutMs);
Reset();
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
return false;
}
}
inline bool DtlsTransport::ProcessHandshake()
{
MS_TRACE();
MS_ASSERT(this->handshakeDone, "handshake not done yet");
MS_ASSERT(
this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE, "remote fingerprint not set");
// Validate the remote fingerprint.
if (!CheckRemoteFingerprint())
{
Reset();
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
return false;
}
// Get the negotiated SRTP crypto suite.
RTC::SrtpSession::CryptoSuite srtpCryptoSuite = GetNegotiatedSrtpCryptoSuite();
if (srtpCryptoSuite != RTC::SrtpSession::CryptoSuite::NONE)
{
// Extract the SRTP keys (will notify the listener with them).
ExtractSrtpKeys(srtpCryptoSuite);
return true;
}
// NOTE: We assume that "use_srtp" DTLS extension is required even if
// there is no audio/video.
MS_WARN_2TAGS(dtls, srtp, "SRTP crypto suite not negotiated");
Reset();
// Set state and notify the listener.
this->state = DtlsState::FAILED;
this->listener->OnDtlsTransportFailed(this);
return false;
}
inline bool DtlsTransport::CheckRemoteFingerprint()
{
MS_TRACE();
MS_ASSERT(
this->remoteFingerprint.algorithm != FingerprintAlgorithm::NONE, "remote fingerprint not set");
X509* certificate;
uint8_t binaryFingerprint[EVP_MAX_MD_SIZE];
unsigned int size{ 0 };
char hexFingerprint[(EVP_MAX_MD_SIZE * 3) + 1];
const EVP_MD* hashFunction;
int ret;
certificate = SSL_get_peer_certificate(this->ssl);
if (!certificate)
{
MS_WARN_TAG(dtls, "no certificate was provided by the peer");
return false;
}
switch (this->remoteFingerprint.algorithm)
{
case FingerprintAlgorithm::SHA1:
hashFunction = EVP_sha1();
break;
case FingerprintAlgorithm::SHA224:
hashFunction = EVP_sha224();
break;
case FingerprintAlgorithm::SHA256:
hashFunction = EVP_sha256();
break;
case FingerprintAlgorithm::SHA384:
hashFunction = EVP_sha384();
break;
case FingerprintAlgorithm::SHA512:
hashFunction = EVP_sha512();
break;
default:
MS_ABORT("unknown algorithm");
}
// Compare the remote fingerprint with the value given via signaling.
ret = X509_digest(certificate, hashFunction, binaryFingerprint, &size);
if (ret == 0)
{
MS_ERROR("X509_digest() failed");
X509_free(certificate);
return false;
}
// Convert to hexadecimal format in uppercase with colons.
for (unsigned int i{ 0 }; i < size; ++i)
{
std::sprintf(hexFingerprint + (i * 3), "%.2X:", binaryFingerprint[i]);
}
hexFingerprint[(size * 3) - 1] = '\0';
if (this->remoteFingerprint.value != hexFingerprint)
{
MS_WARN_TAG(
dtls,
"fingerprint in the remote certificate (%s) does not match the announced one (%s)",
hexFingerprint,
this->remoteFingerprint.value.c_str());
X509_free(certificate);
return false;
}
MS_DEBUG_TAG(dtls, "valid remote fingerprint");
// Get the remote certificate in PEM format.
BIO* bio = BIO_new(BIO_s_mem());
// Ensure the underlying BUF_MEM structure is also freed.
// NOTE: Avoid stupid "warning: value computed is not used [-Wunused-value]" since
// BIO_set_close() always returns 1.
(void)BIO_set_close(bio, BIO_CLOSE);
ret = PEM_write_bio_X509(bio, certificate);
if (ret != 1)
{
LOG_OPENSSL_ERROR("PEM_write_bio_X509() failed");
X509_free(certificate);
BIO_free(bio);
return false;
}
BUF_MEM* mem;
BIO_get_mem_ptr(bio, &mem); // NOLINT[cppcoreguidelines-pro-type-cstyle-cast]
if (!mem || !mem->data || mem->length == 0u)
{
LOG_OPENSSL_ERROR("BIO_get_mem_ptr() failed");
X509_free(certificate);
BIO_free(bio);
return false;
}
this->remoteCert = std::string(mem->data, mem->length);
X509_free(certificate);
BIO_free(bio);
return true;
}
inline void DtlsTransport::ExtractSrtpKeys(RTC::SrtpSession::CryptoSuite srtpCryptoSuite)
{
MS_TRACE();
size_t srtpKeyLength{ 0 };
size_t srtpSaltLength{ 0 };
size_t srtpMasterLength{ 0 };
switch (srtpCryptoSuite)
{
case RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_80:
case RTC::SrtpSession::CryptoSuite::AES_CM_128_HMAC_SHA1_32:
{
srtpKeyLength = SrtpMasterKeyLength;
srtpSaltLength = SrtpMasterSaltLength;
srtpMasterLength = SrtpMasterLength;
break;
}
case RTC::SrtpSession::CryptoSuite::AEAD_AES_256_GCM:
{
srtpKeyLength = SrtpAesGcm256MasterKeyLength;
srtpSaltLength = SrtpAesGcm256MasterSaltLength;
srtpMasterLength = SrtpAesGcm256MasterLength;
break;
}
case RTC::SrtpSession::CryptoSuite::AEAD_AES_128_GCM:
{
srtpKeyLength = SrtpAesGcm128MasterKeyLength;
srtpSaltLength = SrtpAesGcm128MasterSaltLength;
srtpMasterLength = SrtpAesGcm128MasterLength;
break;
}
default:
{
MS_ABORT("unknown SRTP crypto suite");
}
}
auto* srtpMaterial = new uint8_t[srtpMasterLength * 2];
uint8_t* srtpLocalKey{ nullptr };
uint8_t* srtpLocalSalt{ nullptr };
uint8_t* srtpRemoteKey{ nullptr };
uint8_t* srtpRemoteSalt{ nullptr };
auto* srtpLocalMasterKey = new uint8_t[srtpMasterLength];
auto* srtpRemoteMasterKey = new uint8_t[srtpMasterLength];
int ret;
ret = SSL_export_keying_material(
this->ssl, srtpMaterial, srtpMasterLength * 2, "EXTRACTOR-dtls_srtp", 19, nullptr, 0, 0);
MS_ASSERT(ret != 0, "SSL_export_keying_material() failed");
switch (this->localRole)
{
case Role::SERVER:
{
srtpRemoteKey = srtpMaterial;
srtpLocalKey = srtpRemoteKey + srtpKeyLength;
srtpRemoteSalt = srtpLocalKey + srtpKeyLength;
srtpLocalSalt = srtpRemoteSalt + srtpSaltLength;
break;
}
case Role::CLIENT:
{
srtpLocalKey = srtpMaterial;
srtpRemoteKey = srtpLocalKey + srtpKeyLength;
srtpLocalSalt = srtpRemoteKey + srtpKeyLength;
srtpRemoteSalt = srtpLocalSalt + srtpSaltLength;
break;
}
default:
{
MS_ABORT("no DTLS role set");
}
}
// Create the SRTP local master key.
std::memcpy(srtpLocalMasterKey, srtpLocalKey, srtpKeyLength);
std::memcpy(srtpLocalMasterKey + srtpKeyLength, srtpLocalSalt, srtpSaltLength);
// Create the SRTP remote master key.
std::memcpy(srtpRemoteMasterKey, srtpRemoteKey, srtpKeyLength);
std::memcpy(srtpRemoteMasterKey + srtpKeyLength, srtpRemoteSalt, srtpSaltLength);
// Set state and notify the listener.
this->state = DtlsState::CONNECTED;
this->listener->OnDtlsTransportConnected(
this,
srtpCryptoSuite,
srtpLocalMasterKey,
srtpMasterLength,
srtpRemoteMasterKey,
srtpMasterLength,
this->remoteCert);
delete[] srtpMaterial;
delete[] srtpLocalMasterKey;
delete[] srtpRemoteMasterKey;
}
inline RTC::SrtpSession::CryptoSuite DtlsTransport::GetNegotiatedSrtpCryptoSuite()
{
MS_TRACE();
RTC::SrtpSession::CryptoSuite negotiatedSrtpCryptoSuite = RTC::SrtpSession::CryptoSuite::NONE;
// Ensure that the SRTP crypto suite has been negotiated.
// NOTE: This is a OpenSSL type.
SRTP_PROTECTION_PROFILE* sslSrtpCryptoSuite = SSL_get_selected_srtp_profile(this->ssl);
if (!sslSrtpCryptoSuite)
return negotiatedSrtpCryptoSuite;
// Get the negotiated SRTP crypto suite.
for (auto& srtpCryptoSuite : DtlsTransport::srtpCryptoSuites)
{
SrtpCryptoSuiteMapEntry* cryptoSuiteEntry = std::addressof(srtpCryptoSuite);
if (std::strcmp(sslSrtpCryptoSuite->name, cryptoSuiteEntry->name) == 0)
{
MS_DEBUG_2TAGS(dtls, srtp, "chosen SRTP crypto suite: %s", cryptoSuiteEntry->name);
negotiatedSrtpCryptoSuite = cryptoSuiteEntry->cryptoSuite;
}
}
MS_ASSERT(
negotiatedSrtpCryptoSuite != RTC::SrtpSession::CryptoSuite::NONE,
"chosen SRTP crypto suite is not an available one");
return negotiatedSrtpCryptoSuite;
}
inline void DtlsTransport::OnSslInfo(int where, int ret)
{
MS_TRACE();
int w = where & -SSL_ST_MASK;
const char* role;
if ((w & SSL_ST_CONNECT) != 0)
role = "client";
else if ((w & SSL_ST_ACCEPT) != 0)
role = "server";
else
role = "undefined";
if ((where & SSL_CB_LOOP) != 0)
{
MS_DEBUG_TAG(dtls, "[role:%s, action:'%s']", role, SSL_state_string_long(this->ssl));
}
else if ((where & SSL_CB_ALERT) != 0)
{
const char* alertType;
switch (*SSL_alert_type_string(ret))
{
case 'W':
alertType = "warning";
break;
case 'F':
alertType = "fatal";
break;
default:
alertType = "undefined";
}
if ((where & SSL_CB_READ) != 0)
{
MS_WARN_TAG(dtls, "received DTLS %s alert: %s", alertType, SSL_alert_desc_string_long(ret));
}
else if ((where & SSL_CB_WRITE) != 0)
{
MS_DEBUG_TAG(dtls, "sending DTLS %s alert: %s", alertType, SSL_alert_desc_string_long(ret));
}
else
{
MS_DEBUG_TAG(dtls, "DTLS %s alert: %s", alertType, SSL_alert_desc_string_long(ret));
}
}
else if ((where & SSL_CB_EXIT) != 0)
{
if (ret == 0)
MS_DEBUG_TAG(dtls, "[role:%s, failed:'%s']", role, SSL_state_string_long(this->ssl));
else if (ret < 0)
MS_DEBUG_TAG(dtls, "role: %s, waiting:'%s']", role, SSL_state_string_long(this->ssl));
}
else if ((where & SSL_CB_HANDSHAKE_START) != 0)
{
MS_DEBUG_TAG(dtls, "DTLS handshake start");
}
else if ((where & SSL_CB_HANDSHAKE_DONE) != 0)
{
MS_DEBUG_TAG(dtls, "DTLS handshake done");
this->handshakeDoneNow = true;
}
// NOTE: checking SSL_get_shutdown(this->ssl) & SSL_RECEIVED_SHUTDOWN here upon
// receipt of a close alert does not work (the flag is set after this callback).
}
inline void DtlsTransport::OnTimer(Timer* /*timer*/)
{
MS_TRACE();
// Workaround for https://github.com/openssl/openssl/issues/7998.
if (this->handshakeDone)
{
MS_DEBUG_DEV("handshake is done so return");
return;
}
DTLSv1_handle_timeout(this->ssl);
// If required, send DTLS data.
SendPendingOutgoingDtlsData();
// Set the DTLS timer again.
SetTimeout();
}
} // namespace RTC
| 24.873939 | 124 | 0.671052 | [
"object",
"vector"
] |
33e9995f2adfb5afa6f07ec5252e768880a9e66a | 4,300 | cpp | C++ | plugins/community/repos/HetrickCV/src/Delta.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/HetrickCV/src/Delta.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/HetrickCV/src/Delta.cpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | #include "HetrickCV.hpp"
namespace rack_plugin_HetrickCV {
struct Delta : Module
{
enum ParamIds
{
AMOUNT_PARAM,
SCALE_PARAM,
NUM_PARAMS
};
enum InputIds
{
MAIN_INPUT,
AMOUNT_INPUT,
NUM_INPUTS
};
enum OutputIds
{
GT_GATE_OUTPUT,
GT_TRIG_OUTPUT,
LT_GATE_OUTPUT,
LT_TRIG_OUTPUT,
CHANGE_OUTPUT,
DELTA_OUTPUT,
NUM_OUTPUTS
};
enum LightIds
{
GT_LIGHT,
LT_LIGHT,
CHANGE_LIGHT,
NUM_LIGHTS
};
Delta() : Module(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS)
{
}
TriggerGenWithSchmitt ltTrig, gtTrig;
float lastInput = 0.0f;
bool rising = false;
bool falling = false;
void step() override;
// For more advanced Module features, read Rack's engine.hpp header file
// - toJson, fromJson: serialization of internal data
// - onSampleRateChange: event triggered by a change of sample rate
// - reset, randomize: implements special behavior when user clicks these from the context menu
};
void Delta::step()
{
float input = inputs[MAIN_INPUT].value;
float delta = input - lastInput;
lastInput = input;
rising = (delta > 0.0f);
falling = (delta < 0.0f);
float boost = params[AMOUNT_PARAM].value + (inputs[AMOUNT_INPUT].value * params[SCALE_PARAM].value);
boost = clampf(boost, 0.0f, 5.0f) * 8000.0f + 1;
outputs[GT_TRIG_OUTPUT].value = gtTrig.process(rising) ? 5.0f : 0.0f;
outputs[LT_TRIG_OUTPUT].value = ltTrig.process(falling) ? 5.0f : 0.0f;
outputs[GT_GATE_OUTPUT].value = rising ? 5.0f : 0.0f;
outputs[LT_GATE_OUTPUT].value = falling ? 5.0f : 0.0f;
float allTrigs = outputs[GT_TRIG_OUTPUT].value + outputs[LT_TRIG_OUTPUT].value;
allTrigs = clampf(allTrigs, 0.0f, 5.0f);
const float deltaOutput = clampf(delta * boost, -5.0f, 5.0f);
outputs[CHANGE_OUTPUT].value = allTrigs;
outputs[DELTA_OUTPUT].value = deltaOutput;
lights[GT_LIGHT].setBrightnessSmooth(outputs[GT_GATE_OUTPUT].value);
lights[LT_LIGHT].setBrightnessSmooth(outputs[LT_GATE_OUTPUT].value);
lights[CHANGE_LIGHT].setBrightnessSmooth(allTrigs);
}
struct DeltaWidget : ModuleWidget { DeltaWidget(Delta *module); };
DeltaWidget::DeltaWidget(Delta *module) : ModuleWidget(module)
{
box.size = Vec(6 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT);
{
auto *panel = new SVGPanel();
panel->box.size = box.size;
panel->setBackground(SVG::load(assetPlugin(plugin, "res/Delta.svg")));
addChild(panel);
}
addChild(Widget::create<ScrewSilver>(Vec(15, 0)));
addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 30, 0)));
addChild(Widget::create<ScrewSilver>(Vec(15, 365)));
addChild(Widget::create<ScrewSilver>(Vec(box.size.x - 30, 365)));
//////PARAMS//////
addParam(ParamWidget::create<Davies1900hBlackKnob>(Vec(27, 62), module, Delta::AMOUNT_PARAM, 0.0, 5.0, 0.0));
addParam(ParamWidget::create<Trimpot>(Vec(36, 112), module, Delta::SCALE_PARAM, -1.0, 1.0, 1.0));
//////INPUTS//////
addInput(Port::create<PJ301MPort>(Vec(12, 195), Port::INPUT, module, Delta::MAIN_INPUT));
addInput(Port::create<PJ301MPort>(Vec(33, 145), Port::INPUT, module, Delta::AMOUNT_INPUT));
//////OUTPUTS//////
addOutput(Port::create<PJ301MPort>(Vec(53, 195), Port::OUTPUT, module, Delta::DELTA_OUTPUT));
addOutput(Port::create<PJ301MPort>(Vec(12, 285), Port::OUTPUT, module, Delta::LT_GATE_OUTPUT));
addOutput(Port::create<PJ301MPort>(Vec(53, 285), Port::OUTPUT, module, Delta::GT_GATE_OUTPUT));
addOutput(Port::create<PJ301MPort>(Vec(12, 315), Port::OUTPUT, module, Delta::LT_TRIG_OUTPUT));
addOutput(Port::create<PJ301MPort>(Vec(53, 315), Port::OUTPUT, module, Delta::GT_TRIG_OUTPUT));
addOutput(Port::create<PJ301MPort>(Vec(32.5, 245), Port::OUTPUT, module, Delta::CHANGE_OUTPUT));
//////BLINKENLIGHTS//////
addChild(ModuleLightWidget::create<SmallLight<RedLight>>(Vec(22, 275), module, Delta::LT_LIGHT));
addChild(ModuleLightWidget::create<SmallLight<GreenLight>>(Vec(62, 275), module, Delta::GT_LIGHT));
addChild(ModuleLightWidget::create<SmallLight<RedLight>>(Vec(42, 275), module, Delta::CHANGE_LIGHT));
}
} // namespace rack_plugin_HetrickCV
using namespace rack_plugin_HetrickCV;
RACK_PLUGIN_MODEL_INIT(HetrickCV, Delta) {
Model *modelDelta = Model::create<Delta, DeltaWidget>("HetrickCV", "Delta", "Delta", LOGIC_TAG);
return modelDelta;
}
| 31.386861 | 110 | 0.705581 | [
"model"
] |
33e9c60d1221702315e9d021dec348d014c7a368 | 5,763 | hpp | C++ | Reflection/build/External/Windows/include/SFML/Graphics/Vertex.hpp | perezite/sandbox-2 | cfe3be85170f8d305bd0766ee6b3ef6420a23915 | [
"MIT"
] | null | null | null | Reflection/build/External/Windows/include/SFML/Graphics/Vertex.hpp | perezite/sandbox-2 | cfe3be85170f8d305bd0766ee6b3ef6420a23915 | [
"MIT"
] | null | null | null | Reflection/build/External/Windows/include/SFML/Graphics/Vertex.hpp | perezite/sandbox-2 | cfe3be85170f8d305bd0766ee6b3ef6420a23915 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_VERTEX_HPP
#define SFML_VERTEX_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/System/Vector2.hpp>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Define a point with color and texture coordinates
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Vertex
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
Vertex();
////////////////////////////////////////////////////////////
/// \brief Construct the vertex from its position
///
/// The vertex color is white and texture coordinates are (0, 0).
///
/// \param thePosition Vertex position
///
////////////////////////////////////////////////////////////
Vertex(const Vector2f& thePosition);
////////////////////////////////////////////////////////////
/// \brief Construct the vertex from its position and color
///
/// The texture coordinates are (0, 0).
///
/// \param thePosition Vertex position
/// \param theColor Vertex color
///
////////////////////////////////////////////////////////////
Vertex(const Vector2f& thePosition, const Color& theColor);
////////////////////////////////////////////////////////////
/// \brief Construct the vertex from its position and texture coordinates
///
/// The vertex color is white.
///
/// \param thePosition Vertex position
/// \param theTexCoords Vertex texture coordinates
///
////////////////////////////////////////////////////////////
Vertex(const Vector2f& thePosition, const Vector2f& theTexCoords);
////////////////////////////////////////////////////////////
/// \brief Construct the vertex from its position, color and texture coordinates
///
/// \param thePosition Vertex position
/// \param theColor Vertex color
/// \param theTexCoords Vertex texture coordinates
///
////////////////////////////////////////////////////////////
Vertex(const Vector2f& thePosition, const Color& theColor, const Vector2f& theTexCoords);
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Vector2f position; ///< 2D position of the vertex
Color color; ///< Color of the vertex
Vector2f texCoords; ///< Coordinates of the texture's pixel to map to the vertex
};
} // namespace sf
#endif // SFML_VERTEX_HPP
////////////////////////////////////////////////////////////
/// \class sf::Vertex
/// \ingroup graphics
///
/// A vertex is an improved point. It has a position and other
/// extra attributes that will be used for drawing: in SFML,
/// vertices also have a color and a pair of texture coordinates.
///
/// The vertex is the building block of drawing. Everything which
/// is visible on screen is made of vertices. They are grouped
/// as 2D primitives (triangles, quads, ...), and these primitives
/// are grouped to create even more complex 2D entities such as
/// sprites, texts, etc.
///
/// If you use the graphical entities of SFML (sprite, text, shape)
/// you won't have to deal with vertices directly. But if you want
/// to define your own 2D entities, such as tiled maps or particle
/// systems, using vertices will allow you to get maximum performances.
///
/// Example:
/// \code
/// // define a 100x100 square, red, with a 10x10 texture mapped on it
/// sf::Vertex vertices[] =
/// {
/// sf::Vertex(sf::Vector2f( 0, 0), sf::Color::Red, sf::Vector2f( 0, 0)),
/// sf::Vertex(sf::Vector2f( 0, 100), sf::Color::Red, sf::Vector2f( 0, 10)),
/// sf::Vertex(sf::Vector2f(100, 100), sf::Color::Red, sf::Vector2f(10, 10)),
/// sf::Vertex(sf::Vector2f(100, 0), sf::Color::Red, sf::Vector2f(10, 0))
/// };
///
/// // draw it
/// window.draw(vertices, 4, sf::Quads);
/// \endcode
///
/// Note: although texture coordinates are supposed to be an integer
/// amount of pixels, their type is float because of some buggy graphics
/// drivers that are not able to process integer coordinates correctly.
///
/// \see sf::VertexArray
///
////////////////////////////////////////////////////////////
| 38.677852 | 102 | 0.515183 | [
"shape"
] |
33ea50faa5822be5a81c6cd543b153a06411d5bb | 70,575 | cpp | C++ | wlib/PreferenceDlg.cpp | xwang2713/eclide | 1c844c94ca44df5aa861f2c66eb2ff9f00caa3df | [
"Apache-2.0"
] | null | null | null | wlib/PreferenceDlg.cpp | xwang2713/eclide | 1c844c94ca44df5aa861f2c66eb2ff9f00caa3df | [
"Apache-2.0"
] | null | null | null | wlib/PreferenceDlg.cpp | xwang2713/eclide | 1c844c94ca44df5aa861f2c66eb2ff9f00caa3df | [
"Apache-2.0"
] | null | null | null | #include "StdAfx.h"
#include "..\en_us\resource.h"
#include "preferencedlg.h"
#include "global.h"
#include "cmdProcess.h"
#include "loginDlg.h"
#include "SimplePromptDlg.h"
#include "Combo.h"
#include "Dali.h"
#include "ShellHelper.h"
#include "ColorButton.h"
#include "LangRef.h"
#include "EclCommand.h"
#include "EclParser.h"
//#include "atlGraphView.h"
//#include "GraphViewCtl.h"
#include "cmdProcess.h"
#include <EclCC.h>
#include "npHPCCSystemsGraphViewControl.h"
#include "HListBox.h"
#include <UtilFilesystem.h>
// ===========================================================================
#define GLYPH_WIDTH 15
void SetComboText(CComboBox & combo, const std::_tstring & text)
{
int nItem = combo.FindStringExact(-1, text.c_str());
if (nItem >= 0) {
combo.SetCurSel(nItem);
} else {
combo.SetWindowText(text.c_str());
}
}
class CFontComboBox : public CWindowImpl<CFontComboBox, CComboBox>, public COwnerDraw<CFontComboBox>
{
typedef CWindowImpl<CFontComboBox, CComboBox> thisClass;
typedef COwnerDraw<CFontComboBox> baseClass;
protected:
CImageList m_img;
int m_cyItem;
public:
CFontComboBox()
{
m_cyItem = -1;
}
void Init()
{
HFONT hFont = ((HFONT)GetStockObject( DEFAULT_GUI_FONT ));
SetFont(hFont);
m_img.CreateFromImage(IDB_TRUETYPE_FONTTYPE, GLYPH_WIDTH, 1, RGB(255,255,255), IMAGE_BITMAP);
CClientDC dc(m_hWnd);
EnumFonts(dc, 0,(FONTENUMPROC) EnumFontProc,(LPARAM)this); //Enumerate font
}
static BOOL CALLBACK EnumFontProc (LPLOGFONT lplf, LPTEXTMETRIC /*lptm*/, DWORD dwType, LPARAM lpData)
{
CFontComboBox * pThis = reinterpret_cast<CFontComboBox *>(lpData);
int index = pThis->AddString(lplf->lfFaceName);
pThis->SetItemData(index, dwType);
return TRUE;
}
void DrawItem(LPDRAWITEMSTRUCT lpDIS)
{
ATLASSERT(lpDIS->CtlType == ODT_COMBOBOX);
ATLASSERT(lpDIS->CtlType == ODT_COMBOBOX);
CDCHandle dc = lpDIS->hDC;
RECT rc = lpDIS->rcItem;
if (lpDIS->itemState & ODS_FOCUS)
dc.DrawFocusRect(&rc);
int nIndexDC = dc.SaveDC();
CBrush br;
if (lpDIS->itemState & ODS_SELECTED)
{
br.CreateSolidBrush(::GetSysColor(COLOR_HIGHLIGHT));
dc.SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
}
else
{
br.CreateSolidBrush(dc.GetBkColor());
}
dc.SetBkMode(TRANSPARENT);
dc.FillRect(&rc, br);
int nLen = GetLBTextLen(lpDIS->itemID);
TCHAR* psFont = (TCHAR *)_alloca(sizeof TCHAR * (nLen + 1));
GetLBText(lpDIS->itemID, psFont);
DWORD dwData = GetItemData(lpDIS->itemID);
if (dwData & TRUETYPE_FONTTYPE)
m_img.Draw(dc, 0, rc.left+5, rc.top+4,ILD_TRANSPARENT);
rc.left += GLYPH_WIDTH + 2;
CFont cf;
cf.CreateFont(20,0,0,0,FW_NORMAL,FALSE, FALSE, FALSE,DEFAULT_CHARSET ,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,ANTIALIASED_QUALITY,DEFAULT_PITCH,psFont);
HFONT hf = dc.SelectFont(cf);
dc.TextOut(rc.left+10, rc.top, psFont);
dc.SelectFont(hf);
dc.RestoreDC(nIndexDC);
}
void MeasureItem(LPMEASUREITEMSTRUCT pmis)
{
ATLASSERT(pmis->CtlType == ODT_COMBOBOX);
if (m_cyItem == -1)
{
// calculate height
CClientDC dc(m_hWnd);
HFONT hFont = ((HFONT)GetStockObject( DEFAULT_GUI_FONT ));
dc.SelectFont( hFont ); //GetFont()
TEXTMETRIC tm;
dc.GetTextMetrics(&tm);
m_cyItem = tm.tmHeight + tm.tmInternalLeading;
}else
m_cyItem = 20;
pmis->itemHeight = m_cyItem;
}
BEGIN_MSG_MAP(thisClass)
CHAIN_MSG_MAP_ALT(baseClass, 1)
DEFAULT_REFLECTION_HANDLER()
END_MSG_MAP()
};
// ===========================================================================
__interface IOwner
{
void SetChanged(bool bChanged=true);
bool GetChanged();
};
// ===========================================================================
const TCHAR g_DefaultConfig[] = _T("Default");
class CPrefServerDlg : public CDialogImpl<CPrefServerDlg>,
public CWinDataExchange<CPrefServerDlg>
{
typedef CPrefServerDlg thisClass;
typedef CDialogImpl<thisClass> baseClass;
protected:
IOwner * m_owner;
IConfigAdapt m_config;
CString m_clusterIP;
CComPtr<CCustomAutoComplete> m_TopologyServerAC;
CComPtr<CCustomAutoComplete> m_WorkunitServerAC;
CComPtr<CCustomAutoComplete> m_AttributeServerAC;
CComPtr<CCustomAutoComplete> m_AccountServerAC;
CComPtr<CCustomAutoComplete> m_SMCServerAC;
CComPtr<CCustomAutoComplete> m_SprayServerAC;
CComPtr<CCustomAutoComplete> m_DfuServerAC;
CString m_ServerIP;
CString m_TopologyServer;
CString m_WorkunitServer;
CString m_AttributeServer;
CString m_AccountServer;
CString m_SMCServer;
CString m_SprayServer;
CString m_DfuServer;
bool m_Advanced;
bool m_SSL;
bool m_disableEnvironmentSettings;
public:
CPrefServerDlg(IOwner * owner, IConfig * config, bool disableEnvironmentSettings) : m_owner(owner), m_config(config)
{
m_Advanced = false;
m_SSL = false;
m_disableEnvironmentSettings = disableEnvironmentSettings;
}
enum { IDD = IDD_PREF_SERVER };
void LoadFromConfig(IConfig * config)
{
m_config = config;
PopulateControls();
DoChanged(false);
}
void PopulateControls()
{
m_ServerIP = m_config->Get(GLOBAL_SERVER_IP);
m_Advanced = m_config->Get(GLOBAL_SERVER_ADVANCED);
m_TopologyServer = m_config->Get(GLOBAL_SERVER_TOPOLOGY);
//to preserve "old" configs, go to advanced if they had a topo server defined
if (!m_Advanced)
{
CString defaultServer(GLOBAL_SERVER_TOPOLOGY.second);
m_Advanced = (m_TopologyServer != defaultServer && m_ServerIP.IsEmpty());
if (m_Advanced)
{
CUrl url;
if (url.CrackUrl(m_TopologyServer))
m_ServerIP = url.GetHostName();
}
}
m_WorkunitServer = m_config->Get(GLOBAL_SERVER_WORKUNIT);
m_AttributeServer = m_config->Get(GLOBAL_SERVER_ATTRIBUTE);
m_AccountServer = m_config->Get(GLOBAL_SERVER_ACCOUNT);
m_SMCServer = m_config->Get(GLOBAL_SERVER_SMC);
m_SprayServer = m_config->Get(GLOBAL_SERVER_FILESPRAY);
m_DfuServer = m_config->Get(GLOBAL_SERVER_DFU);
m_SSL = m_config->Get(GLOBAL_SERVER_SSL);
EnableServerSettings();
DoDataExchange();
DoChanged(false);
}
void UpdateConfig()
{
DoDataExchange(true);
m_config->Set(GLOBAL_SERVER_TOPOLOGY, m_TopologyServer);
m_config->Set(GLOBAL_SERVER_WORKUNIT, m_WorkunitServer);
m_config->Set(GLOBAL_SERVER_ATTRIBUTE, m_AttributeServer);
m_config->Set(GLOBAL_SERVER_ACCOUNT, m_AccountServer);
m_config->Set(GLOBAL_SERVER_SMC, m_SMCServer);
m_config->Set(GLOBAL_SERVER_FILESPRAY, m_SprayServer);
m_config->Set(GLOBAL_SERVER_DFU, m_DfuServer);
m_config->Set(GLOBAL_SERVER_SSL, m_SSL);
m_config->Set(GLOBAL_SERVER_ADVANCED, m_Advanced);
m_config->Set(GLOBAL_SERVER_IP, m_ServerIP);
}
bool DoValidate()
{
if (!ValidateIPServer())
{
SendMessage(WM_NEXTDLGCTL, (WPARAM)(HWND)GetDlgItem(IDC_EDIT_IPADDRESS), TRUE);
return false;
}
return true;
}
void DoApply(bool bMakeGlobal)
{
DoDataExchange(true);
m_TopologyServerAC->AddItem(m_TopologyServer);
m_WorkunitServerAC->AddItem(m_WorkunitServer);
m_AttributeServerAC->AddItem(m_AttributeServer);
m_AccountServerAC->AddItem(m_AccountServer);
m_SMCServerAC->AddItem(m_SMCServer);
m_SprayServerAC->AddItem(m_SprayServer);
m_DfuServerAC->AddItem(m_DfuServer);
UpdateConfig();
DoChanged(false);
}
void DoChanged(bool bChanged=true)
{
m_owner->SetChanged(bChanged);
}
BEGIN_MSG_MAP(thisClass)
MSG_WM_INITDIALOG(OnInitDialog)
MSG_WM_DESTROY(OnDestroy)
COMMAND_HANDLER(IDC_EDIT_IPADDRESS, EN_CHANGE, OnIpFieldChanged)
COMMAND_HANDLER(IDC_CHECK_SSL, BN_CLICKED, OnClickedSSL)
COMMAND_HANDLER(IDC_CHECK_ADVANCED, BN_CLICKED, OnClickedAdvanced)
COMMAND_CODE_HANDLER(EN_CHANGE, OnChangedEdit)
NOTIFY_CODE_HANDLER(UDN_DELTAPOS, OnSpinChange)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
BEGIN_DDX_MAP(thisClass)
DDX_TEXT(IDC_EDIT_TOPOLOGYSERVER, m_TopologyServer)
DDX_TEXT(IDC_EDIT_WORKUNITSERVER, m_WorkunitServer)
DDX_TEXT(IDC_EDIT_ATTRIBUTESERVER, m_AttributeServer)
DDX_TEXT(IDC_EDIT_ACCOUNTSERVER, m_AccountServer)
DDX_TEXT(IDC_EDIT_SMCSERVER, m_SMCServer)
DDX_TEXT(IDC_EDIT_SPRAYSERVER, m_SprayServer)
DDX_TEXT(IDC_EDIT_DFUSERVER, m_DfuServer)
DDX_CHECK(IDC_CHECK_SSL, m_SSL)
DDX_CHECK(IDC_CHECK_ADVANCED, m_Advanced)
DDX_TEXT(IDC_EDIT_IPADDRESS, m_ServerIP)
END_DDX_MAP()
LRESULT OnInitDialog(HWND /*wParam*/, LPARAM /*lParam*/)
{
CWaitCursor wait;
boost::filesystem::path iniPath;
IConfigAdapt ini = CreateIConfig(QUERYBUILDER_INI, GetIniPath(iniPath));
CString regPath(::GetRegPathQB());
regPath += _T("\\Preferences\\");
m_TopologyServerAC = new CCustomAutoComplete(HKEY_CURRENT_USER, regPath+_T("TopologyServer"));
m_WorkunitServerAC = new CCustomAutoComplete(HKEY_CURRENT_USER, regPath+_T("WorkunitServer"));
m_AttributeServerAC = new CCustomAutoComplete(HKEY_CURRENT_USER, regPath+_T("AttributeServer"));
m_AccountServerAC = new CCustomAutoComplete(HKEY_CURRENT_USER, regPath+_T("AccountServer"));
m_SMCServerAC = new CCustomAutoComplete(HKEY_CURRENT_USER, regPath+_T("SMCServer"));
m_SprayServerAC = new CCustomAutoComplete(HKEY_CURRENT_USER, regPath+_T("SprayServer"));
m_DfuServerAC = new CCustomAutoComplete(HKEY_CURRENT_USER, regPath+_T("DfuServer"));
m_TopologyServerAC->Bind(GetDlgItem(IDC_EDIT_TOPOLOGYSERVER), ACO_AUTOSUGGEST | ACO_AUTOAPPEND | ACO_UPDOWNKEYDROPSLIST);
m_WorkunitServerAC->Bind(GetDlgItem(IDC_EDIT_WORKUNITSERVER), ACO_AUTOSUGGEST | ACO_AUTOAPPEND | ACO_UPDOWNKEYDROPSLIST);
m_AttributeServerAC->Bind(GetDlgItem(IDC_EDIT_ATTRIBUTESERVER), ACO_AUTOSUGGEST | ACO_AUTOAPPEND | ACO_UPDOWNKEYDROPSLIST);
m_AccountServerAC->Bind(GetDlgItem(IDC_EDIT_ACCOUNTSERVER), ACO_AUTOSUGGEST | ACO_AUTOAPPEND | ACO_UPDOWNKEYDROPSLIST);
m_SMCServerAC->Bind(GetDlgItem(IDC_EDIT_SMCSERVER), ACO_AUTOSUGGEST | ACO_AUTOAPPEND | ACO_UPDOWNKEYDROPSLIST);
m_SprayServerAC->Bind(GetDlgItem(IDC_EDIT_SPRAYSERVER), ACO_AUTOSUGGEST | ACO_AUTOAPPEND | ACO_UPDOWNKEYDROPSLIST);
m_DfuServerAC->Bind(GetDlgItem(IDC_EDIT_DFUSERVER), ACO_AUTOSUGGEST | ACO_AUTOAPPEND | ACO_UPDOWNKEYDROPSLIST);
LoadFromConfig(m_config); //this calls PopulateControls
DoChanged(false);
return TRUE;
}
void OnDestroy()
{
SetMsgHandled(false);
m_TopologyServerAC->Unbind();
m_WorkunitServerAC->Unbind();
m_AttributeServerAC->Unbind();
m_AccountServerAC->Unbind();
m_SMCServerAC->Unbind();
m_SprayServerAC->Unbind();
m_DfuServerAC->Unbind();
}
LRESULT OnChangedEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
return 0;
}
LRESULT OnSpinChange(int idCtrl, LPNMHDR pnmHdr, BOOL &bHandled)
{
DoChanged();
return 0;
}
LRESULT OnCheckClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
EnableServerSettings();
return 0;
}
void SetLimit(int nId, int lower, int upper)
{
CUpDownCtrl ctrl = GetDlgItem(nId);
ctrl.SetRange(lower, upper);
}
LRESULT OnClickedAdvanced(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoDataExchange(true);
//if switching to non-advanced, update the server fields, with whatever is
//in the IP field
if ( !m_Advanced )
{
UpdateServerFields();
}
DoChanged();
EnableServerSettings();
if ( m_Advanced )
GetDlgItem(IDC_EDIT_TOPOLOGYSERVER).SetFocus();
return 0;
}
LRESULT OnClickedSSL(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoDataExchange(true);
DoChanged();
if ( !m_Advanced )
{
UpdateServerFields();
}
return 0;
}
void SerializeIPAddress(CString &addr, DWORD nAddr)
{
//0 24 through 31
//1 16 through 23
//2 8 through 15
//3 0 through 7
BYTE *bytes = (BYTE *)&nAddr;
addr.Format(_T("%u.%u.%u.%u"), bytes[3], bytes[2], bytes[1], bytes[0] );
}
bool ValidateIPServer()
{
CString serverIP = m_ServerIP;
DoDataExchange(true);
if (boost::algorithm::contains(static_cast<const TCHAR *>(m_ServerIP), _T(":")) || boost::algorithm::contains(static_cast<const TCHAR *>(m_ServerIP), _T("/")))
{
::MessageBox(NULL, _T("\"Server\" should consist of only the IP address or machine name (no port or http prefix)."), _T("ECL IDE"), MB_ICONEXCLAMATION);
m_ServerIP = serverIP;
DoDataExchange(false);
return false;
}
DoChanged();
if ( !m_Advanced )
{
UpdateServerFields();
}
return true;
}
LRESULT OnIpFieldChanged(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoDataExchange(true);
DoChanged();
if ( !m_Advanced )
{
UpdateServerFields();
}
return 0;
}
void UpdateServerFields()
{
if (m_ServerIP.IsEmpty())
{
SetDlgItemText(IDC_EDIT_TOPOLOGYSERVER, _T(""));
SetDlgItemText(IDC_EDIT_WORKUNITSERVER, _T(""));
SetDlgItemText(IDC_EDIT_ATTRIBUTESERVER, _T(""));
SetDlgItemText(IDC_EDIT_ACCOUNTSERVER, _T(""));
SetDlgItemText(IDC_EDIT_SMCSERVER, _T(""));
SetDlgItemText(IDC_EDIT_SPRAYSERVER, _T(""));
SetDlgItemText(IDC_EDIT_DFUSERVER, _T(""));
}
else
{
CString url = m_SSL ? _T("https://") : _T("http://");
url += m_ServerIP;
url += (m_SSL ? _T(":1") : _T(":"));
SetDlgItemText(IDC_EDIT_TOPOLOGYSERVER,url+_T("8010/WsTopology"));
SetDlgItemText(IDC_EDIT_WORKUNITSERVER,url+_T("8010/WsWorkunits"));
SetDlgItemText(IDC_EDIT_ATTRIBUTESERVER,url+_T("8145/WsAttributes"));
SetDlgItemText(IDC_EDIT_ACCOUNTSERVER,url+_T("8010/Ws_Account"));
SetDlgItemText(IDC_EDIT_SMCSERVER,url+_T("8010/WsSMC"));
SetDlgItemText(IDC_EDIT_SPRAYSERVER,url+_T("8010/FileSpray"));
SetDlgItemText(IDC_EDIT_DFUSERVER,url+_T("8010/WsDfu"));
}
}
void EnableServerSettings()
{
if (m_disableEnvironmentSettings)
{
GetDlgItem(IDC_STATIC_ONLYVIALOGIN).ShowWindow(SW_SHOW);
GetDlgItem(IDC_EDIT_IPADDRESS).EnableWindow(false);
GetDlgItem(IDC_CHECK_SSL).EnableWindow(false);
GetDlgItem(IDC_CHECK_ADVANCED).EnableWindow(false);
GetDlgItem(IDC_EDIT_TOPOLOGYSERVER).EnableWindow(false);
GetDlgItem(IDC_EDIT_WORKUNITSERVER).EnableWindow(false);
GetDlgItem(IDC_EDIT_ATTRIBUTESERVER).EnableWindow(false);
GetDlgItem(IDC_EDIT_ACCOUNTSERVER).EnableWindow(false);
GetDlgItem(IDC_EDIT_SMCSERVER).EnableWindow(false);
GetDlgItem(IDC_EDIT_SPRAYSERVER).EnableWindow(false);
GetDlgItem(IDC_EDIT_DFUSERVER).EnableWindow(false);
}
else
{
GetDlgItem(IDC_EDIT_IPADDRESS).EnableWindow(!m_Advanced);
GetDlgItem(IDC_CHECK_SSL).EnableWindow(!m_Advanced);
GetDlgItem(IDC_EDIT_TOPOLOGYSERVER).EnableWindow(m_Advanced);
GetDlgItem(IDC_EDIT_WORKUNITSERVER).EnableWindow(m_Advanced);
GetDlgItem(IDC_EDIT_ATTRIBUTESERVER).EnableWindow(m_Advanced);
GetDlgItem(IDC_EDIT_ACCOUNTSERVER).EnableWindow(m_Advanced);
GetDlgItem(IDC_EDIT_SMCSERVER).EnableWindow(m_Advanced);
GetDlgItem(IDC_EDIT_SPRAYSERVER).EnableWindow(m_Advanced);
GetDlgItem(IDC_EDIT_DFUSERVER).EnableWindow(m_Advanced);
}
}
DWORD ParseAddress(const CString &addr)
{
DWORD nAddr = 0;
CString token;
int curPos = 0;
int count = 0;
do
{
token = addr.Tokenize(_T("."),curPos);
if (!token.IsEmpty())
{
nAddr = (nAddr << 8);
unsigned x = _ttoi(token);
nAddr |= x;
count++;
}
}
while ( !token.IsEmpty() && count < 4 );
return nAddr;
}
};
// ===========================================================================
class CPrefEditorDlg : public CDialogImpl<CPrefEditorDlg>,
public CWinDataExchange<CPrefEditorDlg>
{
typedef CPrefEditorDlg thisClass;
typedef CDialogImpl<thisClass> baseClass;
protected:
IOwner * m_owner;
int m_TabWidth;
int m_TabUseSpaces;
IConfigAdapt m_config;
IConfigAdapt m_ini;
CString m_ConfigLabel;
int m_MaintainIndent;
int m_OpenMDIChildMax;
int m_AutoSaveFreq;
int m_LineNo;
int m_Tree;
int m_Tooltip;
int m_ShowWS;
int m_TargetColor;
int m_SyncRepository;
int m_autoCompleteOnDot;
int m_doubleClickSelQual;
public:
CPrefEditorDlg(IOwner * owner, IConfig * config) : m_config(config), m_owner(owner)
{
m_ConfigLabel = m_config->GetLabel();
if (m_ConfigLabel.IsEmpty())
{
m_ConfigLabel = g_DefaultConfig;
}
}
enum { IDD = IDD_PREF_EDITOR };
void LoadFromConfig(IConfig * config)
{
m_config = config;
m_TabWidth = m_config->Get(GLOBAL_TAB_WIDTH);
m_TabUseSpaces = m_config->Get(GLOBAL_TAB_USESPACES);
m_MaintainIndent = m_config->Get(GLOBAL_MAINTAININDENT);
m_OpenMDIChildMax = m_config->Get(GLOBAL_OPENMDICHILDMAX);
m_AutoSaveFreq = m_config->Get(GLOBAL_AUTOSAVEFREQ);
m_LineNo = m_config->Get(GLOBAL_LINENO);
m_Tree = m_config->Get(GLOBAL_TREE);
m_Tooltip = m_config->Get(GLOBAL_TOOLTIP);
m_ShowWS = m_config->Get(GLOBAL_SHOW_WS);
m_TargetColor = m_config->Get(GLOBAL_TARGETCOLOR);
m_SyncRepository = m_config->Get(GLOBAL_SYNCREPOSITORY);
m_autoCompleteOnDot = m_config->Get(GLOBAL_AUTOCOMPLETEONDOT);
m_doubleClickSelQual = m_config->Get(GLOBAL_DOUBLECLICKSELQUAL);
DoDataExchange();
}
void SaveToConfig()
{
DoDataExchange(true);
m_config->Set(GLOBAL_TAB_WIDTH, m_TabWidth);
m_config->Set(GLOBAL_TAB_USESPACES, m_TabUseSpaces);
m_config->Set(GLOBAL_MAINTAININDENT, m_MaintainIndent);
m_config->Set(GLOBAL_OPENMDICHILDMAX, m_OpenMDIChildMax);
m_config->Set(GLOBAL_AUTOSAVEFREQ, m_AutoSaveFreq);
m_config->Set(GLOBAL_LINENO, m_LineNo);
m_config->Set(GLOBAL_TREE, m_Tree);
m_config->Set(GLOBAL_TOOLTIP, m_Tooltip);
m_config->Set(GLOBAL_SHOW_WS, m_ShowWS);
m_config->Set(GLOBAL_TARGETCOLOR, m_TargetColor);
m_config->Set(GLOBAL_SYNCREPOSITORY, m_SyncRepository);
m_config->Set(GLOBAL_AUTOCOMPLETEONDOT, m_autoCompleteOnDot);
m_config->Set(GLOBAL_DOUBLECLICKSELQUAL, m_doubleClickSelQual);
}
void DoApply(bool bMakeGlobal)
{
DoDataExchange(true);
SaveToConfig();
DoChanged(false);
}
void DoChanged(bool bChanged=true)
{
m_owner->SetChanged(bChanged);
}
BEGIN_MSG_MAP(thisClass)
MSG_WM_INITDIALOG(OnInitDialog)
MSG_WM_DESTROY(OnDestroy)
COMMAND_HANDLER(IDC_CHECK_TABUSESPACES, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_LINENO, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_TREE, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_MAINTAININDENT, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_OPENMDICHILDMAX, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_TOOLTIP, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_SHOWWS, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_TARGETCOLOR, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_SYNCREPOSITORY, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_AUTOCOMPLETEONDOT, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_DOUBLECLICKSEL, BN_CLICKED, OnCheckClicked)
COMMAND_CODE_HANDLER(EN_CHANGE, OnChangedEdit)
NOTIFY_CODE_HANDLER(UDN_DELTAPOS, OnSpinChange)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
BEGIN_DDX_MAP(thisClass)
DDX_INT(IDC_EDIT_TABWIDTH, m_TabWidth)
DDX_CHECK(IDC_CHECK_TABUSESPACES, m_TabUseSpaces)
DDX_CHECK(IDC_CHECK_MAINTAININDENT, m_MaintainIndent)
DDX_CHECK(IDC_CHECK_OPENMDICHILDMAX, m_OpenMDIChildMax)
DDX_INT(IDC_EDIT_AUTOSAVEFREQ, m_AutoSaveFreq)
DDX_CHECK(IDC_CHECK_LINENO, m_LineNo)
DDX_CHECK(IDC_CHECK_TREE, m_Tree)
DDX_CHECK(IDC_CHECK_TOOLTIP, m_Tooltip)
DDX_CHECK(IDC_CHECK_SHOWWS, m_ShowWS)
DDX_CHECK(IDC_CHECK_TARGETCOLOR, m_TargetColor)
DDX_CHECK(IDC_CHECK_SYNCREPOSITORY, m_SyncRepository)
DDX_CHECK(IDC_CHECK_AUTOCOMPLETEONDOT, m_autoCompleteOnDot)
DDX_CHECK(IDC_CHECK_DOUBLECLICKSEL, m_doubleClickSelQual)
END_DDX_MAP()
LRESULT OnInitDialog(HWND /*wParam*/, LPARAM /*lParam*/)
{
CWaitCursor wait;
boost::filesystem::path iniPath;
m_ini = CreateIConfig(QUERYBUILDER_INI, GetIniPath(iniPath));
CString regPath(::GetRegPathQB());
regPath += _T("\\Preferences\\");
SetLimit(IDC_SPIN_AUTOSAVEFREQ, 0, 60);
LoadFromConfig(m_config);
DoChanged(false);
return TRUE;
}
void OnDestroy()
{
SetMsgHandled(false);
}
LRESULT OnChangedEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
return 0;
}
LRESULT OnSpinChange(int idCtrl, LPNMHDR pnmHdr, BOOL &bHandled)
{
DoChanged();
return 0;
}
LRESULT OnCheckClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
return 0;
}
void SetLimit(int nId, int lower, int upper)
{
CUpDownCtrl ctrl = GetDlgItem(nId);
ctrl.SetRange(lower, upper);
}
};
// ===========================================================================
class CPrefCompilerDlg : public CDialogImpl<CPrefCompilerDlg>,
public CWinDataExchange<CPrefCompilerDlg>
{
typedef CPrefCompilerDlg thisClass;
typedef CDialogImpl<thisClass> baseClass;
protected:
IOwner * m_owner;
IConfigAdapt m_config;
IConfigAdapt m_ini;
CString m_ConfigLabel;
bool m_overrideAutoCompilerSelect;
bool m_metaData;
CString m_Location;
CString m_Arguments;
CString m_WUArguments;
CString m_EclWorkingFolder;
CHListBox m_listFolders;
CButton m_moveUp;
CButton m_moveDown;
public:
CPrefCompilerDlg(IOwner * owner, IConfig * config) : m_config(config), m_owner(owner)
{
m_ConfigLabel = m_config->GetLabel();
if (m_ConfigLabel.IsEmpty())
{
m_ConfigLabel = g_DefaultConfig;
}
}
enum { IDD = IDD_PREF_COMPILER };
void LoadDefaults()
{
m_overrideAutoCompilerSelect = false;
m_metaData = false;
m_Arguments = _T("");
m_WUArguments = _T("");
m_listFolders.ResetContent();
boost::filesystem::path clientToolsPath;
GetProgramFolder(clientToolsPath);
if (!clientToolsPath.empty())
clientToolsPath = clientToolsPath.parent_path();
if (!clientToolsPath.empty())
clientToolsPath = clientToolsPath.parent_path();
clientToolsPath /= "clienttools";
boost::filesystem::path eclccPath = clientToolsPath / "bin" / "eclcc.exe";
if (clib::filesystem::exists(eclccPath))
{
m_Location = pathToWString(eclccPath).c_str();
boost::filesystem::path docsFolder;
GetDocumentsFolder(docsFolder);
docsFolder = docsFolder / "HPCC Systems" / "ECL";
boost::filesystem::path wuFolder = docsFolder / "wu" / static_cast<const char *>(CT2A(m_config->GetLabel()));
boost::filesystem::create_directories(wuFolder);
m_EclWorkingFolder = pathToWString(wuFolder).c_str();
boost::filesystem::path repositoryPath = docsFolder / "My Files";
boost::filesystem::create_directories(repositoryPath);
m_listFolders.AddString(pathToWString(repositoryPath).c_str());
boost::filesystem::path samplesPath = clientToolsPath / "examples";
if (clib::filesystem::exists(samplesPath))
m_listFolders.AddString(pathToWString(samplesPath).c_str());
}
else
{
const TCHAR * hpccbin = _tgetenv(_T("HPCCBIN"));
if (hpccbin)
{
boost::filesystem::wpath eclccPath = hpccbin;
eclccPath /= _T("eclcc.exe");
if (clib::filesystem::exists(eclccPath))
m_Location = pathToWString(eclccPath).c_str();
}
const TCHAR * hpccEcl = _tgetenv(_T("HPCCECL"));
if (hpccEcl)
{
boost::filesystem::wpath wuFolder = hpccEcl;
wuFolder /= _T("wu");
boost::filesystem::create_directories(wuFolder);
m_EclWorkingFolder = pathToWString(wuFolder).c_str();
boost::filesystem::wpath repositoryPath = hpccEcl;
repositoryPath = repositoryPath.parent_path();
repositoryPath /= _T("My Files");
boost::filesystem::create_directories(repositoryPath);
m_listFolders.AddString(pathToWString(repositoryPath).c_str());
}
}
DoDataExchange();
SaveToConfig();
EnableLocationSettings();
}
void LoadFromConfig(IConfig * config)
{
m_config = config;
m_overrideAutoCompilerSelect = m_config->Get(GLOBAL_COMPILER_OVERRIDEDEFAULTSELECTION);
m_Location = m_config->Get(GLOBAL_COMPILER_LOCATION);
m_Arguments = m_config->Get(GLOBAL_COMPILER_ARGUMENTS);
m_WUArguments = m_config->Get(GLOBAL_COMPILER_WUARGUMENTS);
m_EclWorkingFolder = m_config->Get(GLOBAL_COMPILER_ECLWORKINGFOLDER);
m_listFolders.ResetContent();
for (int i = 0; i < 10; ++i)
{
CString text;
switch (i)
{
case 0:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER00);
break;
case 1:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER01);
break;
case 2:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER02);
break;
case 3:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER03);
break;
case 4:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER04);
break;
case 5:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER05);
break;
case 6:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER06);
break;
case 7:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER07);
break;
case 8:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER08);
break;
case 9:
text = m_config->Get(GLOBAL_COMPILER_ECLFOLDER09);
break;
}
if (text.GetLength() > 0)
m_listFolders.InsertString(i, text);
}
DoDataExchange();
EnableLocationSettings();
}
void SaveToConfig()
{
DoDataExchange(true);
m_config->Set(GLOBAL_COMPILER_OVERRIDEDEFAULTSELECTION, m_overrideAutoCompilerSelect);
m_config->Set(GLOBAL_COMPILER_LOCATION, m_Location);
m_config->Set(GLOBAL_COMPILER_ARGUMENTS, m_Arguments);
m_config->Set(GLOBAL_COMPILER_WUARGUMENTS, m_WUArguments);
m_config->Set(GLOBAL_COMPILER_ECLWORKINGFOLDER, m_EclWorkingFolder);
for (int i = 0; i < 10; ++i)
{
CString text;
m_listFolders.GetText(i, text);
switch (i)
{
case 0:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER00, text);
break;
case 1:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER01, text);
break;
case 2:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER02, text);
break;
case 3:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER03, text);
break;
case 4:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER04, text);
break;
case 5:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER05, text);
break;
case 6:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER06, text);
break;
case 7:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER07, text);
break;
case 8:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER08, text);
break;
case 9:
m_config->Set(GLOBAL_COMPILER_ECLFOLDER09, text);
break;
}
}
}
void DoApply(bool bMakeGlobal)
{
DoDataExchange(true);
SaveToConfig();
DoChanged(false);
}
void DoChanged(bool bChanged=true)
{
m_owner->SetChanged(bChanged);
}
void EnableLocationSettings()
{
GetDlgItem(IDC_STATIC_LOCATION).EnableWindow(m_overrideAutoCompilerSelect);
GetDlgItem(IDC_EDIT_LOCATION).EnableWindow(m_overrideAutoCompilerSelect);
GetDlgItem(IDC_BUTTON_ECLCOMPILER).EnableWindow(m_overrideAutoCompilerSelect);
}
BEGIN_MSG_MAP(thisClass)
MSG_WM_INITDIALOG(OnInitDialog)
MSG_WM_DESTROY(OnDestroy)
COMMAND_CODE_HANDLER(EN_CHANGE, OnChangedEdit)
COMMAND_HANDLER(IDC_CHECK_OVERRIDEDEFAULTCOMPILERSELECTION, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_METADATA, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_BUTTON_ECLCOMPILER, BN_CLICKED, OnEclCompilerClicked)
COMMAND_HANDLER(IDC_BUTTON_ECLWORKINGFOLDER, BN_CLICKED, OnEclWorkingFolderClicked)
COMMAND_HANDLER(IDC_BUTTON_MOVEUP, BN_CLICKED, OnEclFolderMoveUpClicked)
COMMAND_HANDLER(IDC_BUTTON_MOVEDOWN, BN_CLICKED, OnEclFolderMoveDownClicked)
COMMAND_HANDLER(IDC_BUTTON_DEFAULTS, BN_CLICKED, OnEclFolderDefaults)
COMMAND_HANDLER(IDC_BUTTON_ECLFOLDERADD, BN_CLICKED, OnEclFolderAddClicked)
COMMAND_HANDLER(IDC_BUTTON_ECLFOLDERDELETE, BN_CLICKED, OnEclFolderDeleteClicked)
NOTIFY_HANDLER(IDC_LIST_ECLFOLDERS, LBN_SELCHANGE, OnSelChange)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
BEGIN_DDX_MAP(thisClass)
DDX_CHECK(IDC_CHECK_OVERRIDEDEFAULTCOMPILERSELECTION, m_overrideAutoCompilerSelect)
DDX_CHECK(IDC_CHECK_METADATA, m_metaData)
DDX_TEXT(IDC_EDIT_LOCATION, m_Location)
DDX_TEXT(IDC_EDIT_ARGUMENTS, m_Arguments)
DDX_TEXT(IDC_EDIT_WUARGUMENTS, m_WUArguments)
DDX_TEXT(IDC_EDIT_ECLWORKINGFOLDER, m_EclWorkingFolder)
END_DDX_MAP()
LRESULT OnInitDialog(HWND /*wParam*/, LPARAM /*lParam*/)
{
CWaitCursor wait;
boost::filesystem::path iniPath;
m_ini = CreateIConfig(QUERYBUILDER_INI, GetIniPath(iniPath));
m_listFolders = GetDlgItem(IDC_LIST_ECLFOLDERS);
ATLASSERT(m_listFolders);
m_moveUp = GetDlgItem(IDC_BUTTON_MOVEUP);
m_moveDown = GetDlgItem(IDC_BUTTON_MOVEDOWN);
LoadFromConfig(m_config);
DoChanged(false);
return TRUE;
}
void OnDestroy()
{
SetMsgHandled(false);
}
LRESULT OnChangedEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
return 0;
}
LRESULT OnCheckClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoDataExchange(true);
DoChanged();
EnableLocationSettings();
return 0;
}
LRESULT OnEclCompilerClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
static const TCHAR szEclFilter[] = _T("ECL Compiler (eclcc.exe)\0eclcc.exe\0All Files (*.*)\0*.*\0\0");
CFileDialog dlg(TRUE, NULL, NULL, OFN_FILEMUSTEXIST, szEclFilter, m_hWnd);
if (IDOK == dlg.DoModal())
{
m_Location = dlg.m_szFileName;
::SetWindowText(::GetDlgItem(m_hWnd, IDC_EDIT_LOCATION), m_Location);
DoChanged();
}
return 0;
}
LRESULT OnEclWorkingFolderClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CFolderDialog dlg(NULL, _T("Select working folder for the compiler:"), BIF_RETURNONLYFSDIRS|BIF_EDITBOX|BIF_NEWDIALOGSTYLE);
dlg.SetInitialFolder(m_EclWorkingFolder);
if (IDOK == dlg.DoModal())
{
m_EclWorkingFolder = dlg.GetFolderPath();
::SetWindowText(::GetDlgItem(m_hWnd, IDC_EDIT_ECLWORKINGFOLDER), m_EclWorkingFolder);
DoChanged();
}
return 0;
}
LRESULT OnEclFolderDefaults(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
LoadDefaults();
DoChanged();
return 0;
}
LRESULT OnEclFolderAddClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CFolderDialog dlg(NULL, _T("Select folder that contains ECL:"), BIF_RETURNONLYFSDIRS|BIF_EDITBOX|BIF_NEWDIALOGSTYLE);
dlg.SetInitialFolder(m_EclWorkingFolder);
if (IDOK == dlg.DoModal())
{
std::_tstring folder = dlg.GetFolderPath();
boost::filesystem::wpath path = folder;
for (int i = 0; i < m_listFolders.GetCount(); ++i)
{
CString otherFolder;
m_listFolders.GetText(i, otherFolder);
boost::filesystem::wpath otherPath = static_cast<const TCHAR *>(otherFolder);
if (boost::algorithm::iequals(pathToString(path.leaf()), pathToString(otherPath.leaf())))
{
std::_tstring msg = _T("ECL folders must have unique name. \"") + pathToWString(otherPath.leaf()) + _T("\" is already used.");
MessageBox(msg.c_str(), CString(MAKEINTRESOURCE(IDR_MAINFRAME)), MB_OK);
return 0;
}
}
m_listFolders.AddString(folder.c_str());
DoChanged();
}
return 0;
}
LRESULT OnEclFolderDeleteClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
m_listFolders.DeleteString(m_listFolders.GetCurSel());
DoChanged();
return 0;
}
LRESULT OnEclFolderMoveUpClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int idx = m_listFolders.GetCurSel();
if(idx > 0 && idx <= m_listFolders.GetCount() - 1)
{
CString prevLine;
m_listFolders.GetText(idx - 1, prevLine);
m_listFolders.DeleteString(idx - 1);
m_listFolders.InsertString(idx, prevLine);
DoChanged();
}
else
::MessageBeep(MB_ICONEXCLAMATION);
return 0;
}
LRESULT OnEclFolderMoveDownClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int idx = m_listFolders.GetCurSel();
if(idx >= 0 && idx < m_listFolders.GetCount() - 1)
{
CString nextLine;
m_listFolders.GetText(idx + 1, nextLine);
m_listFolders.DeleteString(idx + 1);
m_listFolders.InsertString(idx, nextLine);
DoChanged();
}
else
::MessageBeep(MB_ICONEXCLAMATION);
return 0;
}
LRESULT OnSelChange(int wParam, LPNMHDR lParam, BOOL &/*bHandled*/)
{
return 0;
}
};
// ===========================================================================
class CPrefColorDlg : public CDialogImpl<CPrefColorDlg>,
public CWinDataExchange<CPrefColorDlg>,
public CSourceSlotImpl,
public CEclCommandMixin<CPrefColorDlg>
{
typedef CPrefColorDlg thisClass;
typedef CDialogImpl<thisClass> baseClass;
typedef std::map<std::_tstring, std::_tstring> SampleMap;
protected:
IOwner * m_owner;
IConfigAdapt m_config;
IConfigAdapt m_ini;
CString m_ConfigLabel;
AttrInfo m_attrInfo;
CFontComboBox m_comboFont;
CComboBox m_comboFontSize;
std::_tstring m_Font;
std::_tstring m_FontSize;
CColorButton m_buttForeground;
CColorButton m_buttBackground;
CComPtr<ILangRef> m_langRef;
CComboBox m_comboElementType;
CComboBox m_comboElement;
CSourceCtrl m_sourceCtrl;
CButton m_checkBold;
CString m_currentElementTypeStr;
CString m_currentElementStr;
public:
CPrefColorDlg(IOwner * owner, IConfig * config) : m_config(config), m_owner(owner), m_sourceCtrl(m_attrInfo, this)
{
m_ConfigLabel = m_config->GetLabel();
if (m_ConfigLabel.IsEmpty())
{
m_ConfigLabel = g_DefaultConfig;
}
}
enum { IDD = IDD_PREF_COLOR };
void LoadFromConfig(IConfig * config)
{
m_config = config;
m_Font = CString(m_config->Get(GLOBAL_FONT));
m_FontSize = CString(m_config->Get(GLOBAL_FONTSIZE));
SetComboText(m_comboFont, m_Font);
SetComboText(m_comboFontSize, m_FontSize);
}
void SaveToConfig()
{
//DoDataExchange(true);
//CString font, fontSize;
//m_comboFont.GetLBText(m_comboFont.GetCurSel(), font);
//m_comboFontSize.GetLBText(m_comboFontSize.GetCurSel(), fontSize);
//m_Font = font;
//m_FontSize = fontSize;
//m_config->Set(GLOBAL_FONT, m_Font);
//m_config->Set(GLOBAL_FONTSIZE, m_FontSize);
m_langRef->Save();
}
void DoApply(bool bMakeGlobal)
{
DoDataExchange(true);
SaveToConfig();
DoChanged(false);
}
void DoRestore()
{
m_langRef->Restore();
}
void DoChanged(bool bChanged=true)
{
m_owner->SetChanged(bChanged);
}
void GetTitle(CString & title)
{
}
void PathToClipboard()
{
}
IAttribute * GetAttribute()
{
return NULL;
}
void DoLoadElementType()
{
m_langRef = CreateLangRef(CurrentElementType().GetString(), NULL);
LoadType();
m_comboElement.ResetContent();
m_langRef->SetElementType(CurrentElementType());
m_langRef->loadReference();
m_langRef->loadMergedColor();
LoadComboElement();
m_sourceCtrl.DoInit();
m_comboElement.SetCurSel(0);
LoadSampleText();
DoLoadElement();
m_sourceCtrl.InitColors(m_langRef);
}
void LoadType()
{
if (ElementTypeEqual(ATTRIBUTE_TYPE_GENERAL))
{
m_sourceCtrl.SetType(CreateIAttributeGENERALType());
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_ECM) || ElementTypeEqual(ATTRIBUTE_TYPE_ESDL))
{
m_sourceCtrl.SetType(CreateIAttributeESDLType());
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_KEL))
{
m_sourceCtrl.SetType(CreateIAttributeKELType());
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_DUD))
{
m_sourceCtrl.SetType(CreateIAttributeDUDType());
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_SALT))
{
m_sourceCtrl.SetType(CreateIAttributeSALTType());
}
else
{
m_sourceCtrl.SetType(CreateIAttributeECLType());
}
}
CString CurrentElementType()
{
int row = m_comboElementType.GetCurSel();
if (row < 0)
return _T("");
CString str1;
int n;
n = m_comboElementType.GetLBTextLen(row);
m_comboElementType.GetLBText(row, str1.GetBuffer(n));
str1.ReleaseBuffer();
str1.MakeLower();
m_currentElementTypeStr = str1;
return str1;
}
CString CurrentElement()
{
int row = m_comboElement.GetCurSel();
if (row < 0)
return _T("");
CString str1;
int n;
n = m_comboElement.GetLBTextLen(row);
m_comboElement.GetLBText(row, str1.GetBuffer(n));
str1.ReleaseBuffer();
str1.MakeLower();
m_currentElementStr = str1;
return str1;
}
void DoLoadElement()
{
int row = m_comboElement.GetCurSel();
if (row < 0 || row >= m_langRef->GetColorRowCount())
return;
int catID = m_langRef->GetColorCatID(row);
m_buttBackground.SetColor(m_langRef->GetColorBack(catID));
m_buttForeground.SetColor(m_langRef->GetColorFore(catID));
std::_tstring font = CString(m_config->Get(GLOBAL_FONT));
font = m_comboFont.SetWindowText(m_langRef->GetFontName(catID));
m_comboFontSize.SetWindowText(boost::lexical_cast<std::_tstring>(m_langRef->GetFontSize(catID)).c_str());
m_checkBold.SetCheck(m_langRef->GetFontBold(catID));
if (ElementTypeEqual("general"))
{
if (CurrentElement().CompareNoCase(_T("caret")) == 0)
{
m_buttBackground.EnableWindow(false);
}
else
{
m_buttBackground.EnableWindow(true);
}
m_buttForeground.EnableWindow(true);
m_comboFont.EnableWindow(false);
m_comboFontSize.EnableWindow(false);
m_checkBold.EnableWindow(false);
}
else
{
m_buttBackground.EnableWindow(true);
m_comboFont.EnableWindow(true);
m_comboFontSize.EnableWindow(true);
m_checkBold.EnableWindow(true);
}
}
void DoSaveElement()
{
int row = m_comboElement.GetCurSel();
if (row < 0 || row >= m_langRef->GetColorRowCount())
return;
int catID = m_langRef->GetColorCatID(row);
m_langRef->SetColorFore(catID, m_buttBackground.GetColor());
m_langRef->SetColorBack(catID, m_buttForeground.GetColor());
CString font;
m_comboFont.GetWindowText(font);
m_langRef->SetFontName(catID, static_cast<const TCHAR *>(font));
CString fontSize;
m_comboFontSize.GetWindowText(fontSize);
m_langRef->SetFontSize(catID, boost::lexical_cast<int>(static_cast<const TCHAR *>(fontSize)));
m_langRef->SetFontBold(catID, m_checkBold.GetCheck() != 0);
}
BEGIN_MSG_MAP(thisClass)
MSG_WM_INITDIALOG(OnInitDialog)
MSG_WM_DESTROY(OnDestroy)
COMMAND_HANDLER(IDC_CHECK_BOLD, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_COMBO_ELEMENT_TYPE, CBN_SELENDOK, OnCbnSelendokComboElementType)
COMMAND_HANDLER(IDC_COMBO_ELEMENT, CBN_SELENDOK, OnCbnSelendokComboElement)
COMMAND_HANDLER(IDC_COMBO_FONT, CBN_SELENDOK, OnCbnSelendokComboFont)
COMMAND_HANDLER(IDC_COMBO_FONTSIZE, CBN_SELENDOK, OnCbnSelendokComboFontSize)
NOTIFY_HANDLER(IDC_BUTTON_FOREGROUND, CPN_SELENDOK, OnBnSelendokForeground)
NOTIFY_HANDLER(IDC_BUTTON_BACKGROUND, CPN_SELENDOK, OnBnSelendokBackground)
COMMAND_HANDLER(IDC_BUTTON_DEFAULTS, BN_CLICKED, OnBnClickedButtonDefaults)
COMMAND_CODE_HANDLER(EN_CHANGE, OnChangedEdit)
NOTIFY_CODE_HANDLER(UDN_DELTAPOS, OnSpinChange)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
BEGIN_DDX_MAP(thisClass)
//DDX_TEXT(IDC_EDIT_FONT, m_Font)
//DDX_INT(IDC_EDIT_FONTSIZE, m_FontSize)
END_DDX_MAP()
void InitComboFont()
{
CWindow wndPlaceholder = GetDlgItem(IDC_COMBO_FONT);
CRect rc;
wndPlaceholder.GetWindowRect(rc);
ScreenToClient(rc);
wndPlaceholder.DestroyWindow();
m_comboFont.Create(m_hWnd, rc, _T(""), WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VSCROLL | CBS_DROPDOWN | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | CBS_SORT , 0, IDC_COMBO_FONT);
m_comboFont.Init();
}
void InitComboFontSize()
{
m_comboFontSize = GetDlgItem(IDC_COMBO_FONTSIZE);
m_comboFontSize.AddString(_T("8"));
m_comboFontSize.AddString(_T("9"));
m_comboFontSize.AddString(_T("10"));
m_comboFontSize.AddString(_T("11"));
m_comboFontSize.AddString(_T("12"));
m_comboFontSize.AddString(_T("14"));
m_comboFontSize.AddString(_T("16"));
m_comboFontSize.AddString(_T("18"));
m_comboFontSize.AddString(_T("20"));
m_comboFontSize.AddString(_T("22"));
m_comboFontSize.AddString(_T("24"));
m_comboFontSize.AddString(_T("26"));
m_comboFontSize.AddString(_T("28"));
m_comboFontSize.AddString(_T("36"));
m_comboFontSize.AddString(_T("48"));
m_comboFontSize.AddString(_T("78"));
}
std::vector<CString> m_elementTypes = {
ATTRIBUTE_TYPE_GENERAL,
ATTRIBUTE_TYPE_ECL,
ATTRIBUTE_TYPE_ESDL,
ATTRIBUTE_TYPE_DUD,
ATTRIBUTE_TYPE_KEL,
ATTRIBUTE_TYPE_SALT
};
int GetElementTypeCount()
{
return static_cast<int>(m_elementTypes.size());
}
CString GetElementType(int typeID)
{
return m_elementTypes[typeID];
}
void InitComboElementType()
{
m_comboElementType = GetDlgItem(IDC_COMBO_ELEMENT_TYPE);
for (int i = 0; i < GetElementTypeCount(); i++)
{
m_comboElementType.AddString(GetElementType(i).MakeUpper());
}
}
void InitComboElement()
{
m_comboElement = GetDlgItem(IDC_COMBO_ELEMENT);
}
void LoadComboElement()
{
for (int row = 0; row < m_langRef->GetColorRowCount(); ++row)
{
m_comboElement.AddString(m_langRef->GetColorName(m_langRef->GetColorCatID(row)));
}
}
void InitEditColors()
{
CWindow wndPlaceholder = GetDlgItem(IDC_ECL_PLACEHOLDER);
CRect rc;
wndPlaceholder.GetWindowRect ( rc );
ScreenToClient(rc);
wndPlaceholder.DestroyWindow();
m_sourceCtrl.Create(*this, rc, _T(""), WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE, WS_EX_CLIENTEDGE, IDC_ECL_PLACEHOLDER);
LoadSampleText();
}
bool ElementTypeEqual(CString elementType)
{
return m_currentElementTypeStr.CompareNoCase(elementType) == 0;
}
void LoadSampleText()
{
std::_tstring textSample = _T("");
bool filled = false;
if (m_langRef)
{
//m_langRef->loadSamples();
textSample = m_langRef->GetSample();
filled = true;
if (textSample == _T(""))
{
if (ElementTypeEqual(ATTRIBUTE_TYPE_KEL))
{
textSample =
_T("// KEL sample file illustrating color syntax") _T("\r\n")
_T("/* This is a comment between delimiters */") _T("\r\n")
_T("Person := ENTITY(FLAT(UID = did, STRING fname = name));") _T("\r\n")
_T("USE fdc.GLUE_fdc.File(FDC, Person,") _T("\r\n")
_T("Person: => age := YEARSBETWEEN(bdate, CURRENTDATE());") _T("\r\n")
_T("QUERY: HiMaleInc <= Person(sex = 'M' AND") _T("\r\n")
_T(" income = income$Person(sex = 'M') :Max);") _T("\r\n")
_T("QUERY: IncMoreAveVal <= ") _T("\r\n")
_T(" Person(income > MAX(Vehicle(make = 'TOYOTA'), value));");
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_ECM) || ElementTypeEqual(ATTRIBUTE_TYPE_ESDL))
{
textSample =
_T("// ESDL sample for illustrating color syntax") _T("\r\n")
_T("/* This is a comment between delimiters */") _T("\r\n")
_T("ESPInclude(ModThis);") _T("\r\n")
_T("ESPservice MathService{") _T("\r\n")
_T(" ESPmethod DivThis(DivThisRequest, DivThisResponse);") _T("\r\n")
_T("ESPmethod ModThis(ModThisRequest, ModThisResponse);") _T("\r\n")
_T("};") _T("\r\n")
_T("ESPrequest DivThisRequest{") _T("\r\n")
_T(" int FirstNumber;") _T("\r\n")
_T(" int SecondNumber;") _T("\r\n")
_T("};") _T("\r\n")
_T("ESPresponse DivThisResponse{") _T("\r\n")
_T(" int Answer;") _T("\r\n")
_T("};") _T("\r\n")
_T("ESPstruct Date {") _T("\r\n")
_T(" [leading_zero(4)] Year;") _T("\r\n")
_T(" [leading_zero(2)] Month;") _T("\r\n")
_T(" [leading_zero(2)] Day;") _T("\r\n")
_T("}") _T("\r\n")
_T("ESPservice MyService {") _T("\r\n")
_T(" ESPmethod MyMethod1(MyMethod1Req, MyMethod1Resp);") _T("\r\n")
_T(" ESPmethod [") _T("\r\n")
_T(" description(\"MyMethod Two\"),") _T("\r\n")
_T(" help(\"This method does everything...\"),") _T("\r\n")
_T(" min_ver(\"1.2\")") _T("\r\n")
_T(" ]") _T("\r\n")
_T(" MyMethod2(MyMethod2Req, MyMethod2Resp);") _T("\r\n")
_T("};");
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_SALT))
{
textSample =
_T("// SALT sample for illustrating color syntax") _T("\r\n")
_T("/* This is a comment between delimiters */") _T("\r\n")
_T("FIELD:dt_first_seen:RECORDDATE(FIRST)") _T("\r\n")
_T("CONCEPT : locale : +: zip : state : 2, 0") _T("\r\n")
_T("ATTRIBUTEFILE : VEHICLES : ") _T("\r\n")
_T(" NAMED(SALT_Examples.File_Vehicle_Matches_S") _T("\r\n");
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_DUD))
{
textSample =
_T("// DUDE sample for illustrating color syntax") _T("\r\n")
_T("/* This is a comment between delimiters */") _T("\r\n")
_T("NAME RawDataset;") _T("\r\n")
_T("PERMISSIONS") _T("\r\n")
_T(" EDIT:PRIVATE;") _T("\r\n")
_T(" VIEW:PUBLIC;") _T("\r\n")
_T("END") _T("\r\n")
_T("INPUTS") _T("\r\n")
_T(" STRING Name : MAXLENGTH(30);") _T("\r\n")
_T(" RECORD Structure;") _T("\r\n")
_T(" ENUM(CSV,XML,FLAT) Method;") _T("\r\n")
_T("END") _T("\r\n")
_T("OUTPUTS") _T("\r\n")
_T(" DATASET Out1(Structure);") _T("\r\n")
_T(" INT Cnt;") _T("\r\n")
_T(" END") _T("\r\n")
_T("GENERATES INLINE") _T("\r\n")
_T(" %^eOut1% := DATASET(%^qName%,%Structure%,%Method%);") _T("\r\n")
_T(" %C% := COUNT(%Out1%);") _T("\r\n")
_T("ENDGENERATES") _T("\r\n")
_T("VISUALIZE TestPins :TITLE(\"Test pins\")") _T("\r\n")
_T(" CHORO pin2(...TITLE(\"Pins2\"),GEOHASH(pinge...2") _T("\r\n")
_T("END") _T("\r\n")
_T("RESOURCES") _T("\r\n")
_T(" LOGICALFILE File1:FILENAME(\"~thor::temp...20160810\"),") _T("\r\n")
_T(" URL(\"http://10.241.100.159:8010\"),") _T("\r\n")
_T(" ECL Ecl:FILENAME(\"ECL\"),") _T("\r\n")
_T("END") _T("\r\n");
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_ECL))
{
textSample =
_T("// ECL sample for illustrating color syntax") _T("\r\n")
_T("/* This is a comment between delimiters */") _T("\r\n")
_T("import ut;") _T("\r\n")
_T("r := ") _T("\r\n")
_T(" record") _T("\r\n")
_T(" string22 s1 := '123';") _T("\r\n")
_T(" integer4 i1 := 123;") _T("\r\n")
_T(" end;") _T("\r\n")
_T("#option('tmp', true);") _T("\r\n")
_T("d := dataset('tmp::qb', r, thor);") _T("\r\n")
_T("output(d);") _T("\r\n")
_T("Compare: Added") _T("\r\n")
_T("Compare: Deleted") _T("\r\n")
_T("Compare: Changed") _T("\r\n")
_T("Compare: Moved");
}
else if (ElementTypeEqual(ATTRIBUTE_TYPE_GENERAL))
{
textSample =
_T("Caret : #") _T("\r\n")
_T("Target: Thor ") _T("\r\n")
_T("Target: HThor ") _T("\r\n")
_T("Target: Roxie ") _T("\r\n")
_T("Target: Local ") _T("\r\n")
_T("Target: ReadOnly ") _T("\r\n");
}
else
{
filled = false;
}
}
}
m_sourceCtrl.SetText(textSample.c_str());
if (ElementTypeEqual("ecl"))
{
m_sourceCtrl.SetLineState(11, SCE_ECL_ADDED);
m_sourceCtrl.SetLineState(12, SCE_ECL_DELETED);
m_sourceCtrl.SetLineState(13, SCE_ECL_CHANGED);
m_sourceCtrl.SetLineState(14, SCE_ECL_MOVED);
}
else if (ElementTypeEqual("general"))
{
m_sourceCtrl.SetFocus(true);
m_sourceCtrl.SetSel(9, 9);
}
}
LRESULT OnInitDialog(HWND /*wParam*/, LPARAM /*lParam*/)
{
CWaitCursor wait;
CString regPath(::GetRegPathQB());
regPath += _T("\\Preferences\\");
InitComboFont();
InitComboFontSize();
InitComboElementType();
InitComboElement();
InitEditColors();
boost::filesystem::path iniPath;
m_ini = CreateIConfig(QUERYBUILDER_INI, GetIniPath(iniPath));
m_buttForeground.SubclassWindow(GetDlgItem(IDC_BUTTON_FOREGROUND));
m_buttForeground.SetDefaultColor(GetSysColor(COLOR_WINDOWTEXT));
m_buttBackground.SubclassWindow(GetDlgItem(IDC_BUTTON_BACKGROUND));
m_buttBackground.SetDefaultColor(GetSysColor(COLOR_WINDOW));
m_checkBold = GetDlgItem(IDC_CHECK_BOLD);
LoadFromConfig(m_config);
SelectElementType(_T("ecl"));
DoLoadElementType();
DoChanged(false);
NewSel();
return TRUE;
}
void SelectElementType(std::_tstring elementTypeStr)
{
m_langRef = CreateLangRef(elementTypeStr, NULL);
int index = m_comboElementType.FindString(0, elementTypeStr.c_str());
m_comboElementType.SetCurSel(index);
}
void OnDestroy()
{
SetMsgHandled(false);
}
LRESULT OnChangedEdit(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if (wID != IDC_ECL_PLACEHOLDER)
DoChanged();
return 0;
}
LRESULT OnSpinChange(int idCtrl, LPNMHDR pnmHdr, BOOL &bHandled)
{
DoChanged();
return 0;
}
LRESULT OnCheckClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int row = m_comboElement.GetCurSel();
if (row < 0 || row >= m_langRef->GetColorRowCount())
return 0;
int catID = m_langRef->GetColorCatID(row);
m_langRef->SetFontBold(catID, m_checkBold.GetCheck() != 0);
m_sourceCtrl.InitColors(m_langRef);
return 0;
}
void SetLimit(int nId, int lower, int upper)
{
CUpDownCtrl ctrl = GetDlgItem(nId);
ctrl.SetRange(lower, upper);
}
LRESULT OnCbnSelendokComboElementType(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoLoadElementType();
return 0;
}
LRESULT OnCbnSelendokComboElement(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoLoadElement();
return 0;
}
LRESULT OnCbnSelendokComboFont(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int row = m_comboElement.GetCurSel();
if (row < 0 || row >= m_langRef->GetColorRowCount())
return 0;
int catID = m_langRef->GetColorCatID(row);
CString font;
int fontRow = m_comboFont.GetCurSel();
m_comboFont.GetLBText(fontRow, font);
m_langRef->SetFontName(catID, static_cast<const TCHAR *>(font));
m_sourceCtrl.InitColors(m_langRef);
return 0;
}
LRESULT OnCbnSelendokComboFontSize(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int row = m_comboElement.GetCurSel();
if (row < 0 || row >= m_langRef->GetColorRowCount())
return 0;
int catID = m_langRef->GetColorCatID(row);
CString fontSize;
m_comboFontSize.GetLBText(m_comboFontSize.GetCurSel(), fontSize);
try
{
m_langRef->SetFontSize(catID, boost::lexical_cast<int>(static_cast<const TCHAR *>(fontSize)));
}
catch(boost::bad_lexical_cast &)
{
return 0;
}
m_sourceCtrl.InitColors(m_langRef);
DoChanged();
return 0;
}
LRESULT OnBnSelendokForeground(int /*wID*/, LPNMHDR /*nmhdr*/, BOOL& /*bHandled*/)
{
int row = m_comboElement.GetCurSel();
if (row < 0 || row >= m_langRef->GetColorRowCount())
return 0;
int catID = m_langRef->GetColorCatID(row);
m_langRef->SetColorFore(catID, m_buttForeground.GetColor());
m_sourceCtrl.InitColors(m_langRef);
DoChanged();
return 0;
}
LRESULT OnBnSelendokBackground(int /*wID*/, LPNMHDR /*nmhdr*/, BOOL& /*bHandled*/)
{
int row = m_comboElement.GetCurSel();
if (row < 0 || row >= m_langRef->GetColorRowCount())
return 0;
int catID = m_langRef->GetColorCatID(row);
m_langRef->SetColorBack(catID, m_buttBackground.GetColor());
m_sourceCtrl.InitColors(m_langRef);
DoChanged();
return 0;
}
// IEclSlot
void NewSel()
{
int catID = m_sourceCtrl.GetStyleAt(m_sourceCtrl.GetCurrentPos());
int row = m_langRef->GetColorRow(catID);
m_comboElement.SetCurSel(row);
DoLoadElement();
}
LRESULT OnBnClickedButtonDefaults(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
if (MessageBox(_T("Restore default color scheme. Are you sure you want to continue?"), CString(MAKEINTRESOURCE(IDR_MAINFRAME)), MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) == IDYES)
{
m_langRef->RestoreDefaults();
m_sourceCtrl.InitColors(m_langRef);
DoLoadElement();
}
return 0;
}
};
// ===========================================================================
class CPrefResultDlg : public CDialogImpl<CPrefResultDlg>,
public CWinDataExchange<CPrefResultDlg>
{
typedef CPrefResultDlg thisClass;
typedef CDialogImpl<thisClass> baseClass;
protected:
IOwner * m_owner;
IConfigAdapt m_config;
IConfigAdapt m_ini;
CString m_ConfigLabel;
int m_ResultLimit;
int m_AutoOpenResult;
std::_tstring m_Font;
int m_FontSizeResult;
CFontComboBox m_comboFont;
bool m_LegacyIE;
public:
CPrefResultDlg(IOwner *owner, IConfig * config) : m_config(config), m_owner(owner)
{
m_ConfigLabel = m_config->GetLabel();
if (m_ConfigLabel.IsEmpty())
{
m_ConfigLabel = g_DefaultConfig;
}
}
enum { IDD = IDD_PREF_RESULTS };
void LoadFromConfig(IConfig * config)
{
m_config = config;
PopulateControls();
DoChanged(false);
}
void PopulateControls()
{
m_ResultLimit = m_config->Get(GLOBAL_WORKUNIT_RESULTLIMIT);
m_AutoOpenResult = m_config->Get(GLOBAL_AUTOOPENRESULT);
m_Font = CString(m_config->Get(GLOBAL_FONT_RESULT));
m_FontSizeResult = m_config->Get(GLOBAL_FONTSIZE_RESULT);
SetComboText(m_comboFont, m_Font);
m_LegacyIE = m_config->Get(GLOBAL_LEGACY_IE);
DoDataExchange();
DoChanged(false);
}
void UpdateConfig()
{
m_config->Set(GLOBAL_WORKUNIT_RESULTLIMIT, m_ResultLimit);
m_config->Set(GLOBAL_AUTOOPENRESULT, m_AutoOpenResult);
CString font;
m_comboFont.GetWindowText(font);
m_config->Set(GLOBAL_FONT_RESULT, font);
m_config->Set(GLOBAL_FONTSIZE_RESULT, m_FontSizeResult);
m_config->Set(GLOBAL_LEGACY_IE, m_LegacyIE);
}
void DoApply(bool bMakeGlobal)
{
DoDataExchange(true);
UpdateConfig();
DoChanged(false);
}
void DoChanged(bool bChanged=true)
{
m_owner->SetChanged(bChanged);
}
BEGIN_MSG_MAP(thisClass)
MSG_WM_INITDIALOG(OnInitDialog)
MSG_WM_DESTROY(OnDestroy)
COMMAND_CODE_HANDLER(EN_CHANGE, OnChangedEdit)
COMMAND_HANDLER(IDC_COMBO_FONT, CBN_SELCHANGE, OnCbnSelendokComboFont)
COMMAND_HANDLER(IDC_COMBO_FONT, CBN_SELENDOK, OnCbnSelendokComboFont)
NOTIFY_CODE_HANDLER(UDN_DELTAPOS, OnSpinChange)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
BEGIN_DDX_MAP(thisClass)
DDX_INT(IDC_EDIT_LIMITRESULT, m_ResultLimit)
DDX_INT(IDC_EDIT_RESULT_FONTSIZE, m_FontSizeResult)
DDX_CHECK(IDC_CHECK_LEGACY_IE, m_LegacyIE)
END_DDX_MAP()
void InitComboFont()
{
CWindow wndPlaceholder = GetDlgItem(IDC_COMBO_FONT);
CRect rc;
wndPlaceholder.GetWindowRect(rc);
ScreenToClient(rc);
wndPlaceholder.DestroyWindow();
m_comboFont.Create(m_hWnd, rc, _T(""), WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VSCROLL | CBS_DROPDOWN | CBS_OWNERDRAWFIXED | CBS_HASSTRINGS | CBS_SORT , 0, IDC_COMBO_FONT);
m_comboFont.Init();
}
LRESULT OnInitDialog(HWND /*wParam*/, LPARAM /*lParam*/)
{
CWaitCursor wait;
boost::filesystem::path iniPath;
m_ini = CreateIConfig(QUERYBUILDER_INI, GetIniPath(iniPath));
CString regPath(::GetRegPathQB());
regPath += _T("\\Preferences\\");
InitComboFont();
SetLimit(IDC_SPIN_LIMITRESULT, 0, 9999);
SetLimit(IDC_SPIN_RESULT_FONTSIZE, 2, 32);
LoadFromConfig(m_config); //this calls PopulateControls
DoChanged(false);
return TRUE;
}
void OnDestroy()
{
SetMsgHandled(false);
}
LRESULT OnChangedEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
return 0;
}
LRESULT OnCbnSelendokComboFont(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
CString font;
m_Font = m_comboFont.GetLBText(m_comboFont.GetCurSel(), font);
return 0;
}
LRESULT OnSpinChange(int idCtrl, LPNMHDR pnmHdr, BOOL &bHandled)
{
DoChanged();
return 0;
}
void SetLimit(int nId, int lower, int upper)
{
CUpDownCtrl ctrl = GetDlgItem(nId);
ctrl.SetRange(lower, upper);
}
};
// ===========================================================================
class CPrefOtherDlg : public CDialogImpl<CPrefOtherDlg>,
public CWinDataExchange<CPrefOtherDlg>
{
typedef CPrefOtherDlg thisClass;
typedef CDialogImpl<thisClass> baseClass;
protected:
IOwner * m_owner;
IConfigAdapt m_config;
IConfigAdapt m_ini;
CString m_ConfigLabel;
int m_DisableInvoke;
int m_IgnoreWhitespace;
int m_IgnoreServerVersion;
int m_ShowCRLF;
int m_DisableAutoUpdate;
int m_DisableGraphControl;
int m_WorkUnitPollFreq;
int m_WorkUnitFetchLimit;
int m_WorkUnitPersistLimit;
std::_tstring m_comboHelpLocaleStr;
CComboBox m_comboHelpLocale;
public:
CPrefOtherDlg(IOwner * owner, IConfig * config) : m_config(config), m_owner(owner)
{
m_ConfigLabel = m_config->GetLabel();
if (m_ConfigLabel.IsEmpty())
{
m_ConfigLabel = g_DefaultConfig;
}
}
enum { IDD = IDD_PREF_OTHER };
void LoadFromConfig(IConfig * config)
{
m_config = config;
PopulateControls();
DoChanged(false);
}
void InitComboHelpLocale()
{
m_comboHelpLocale = GetDlgItem(IDC_COMBO_HELP);
m_comboHelpLocale.AddString(_T(""));
m_comboHelpLocale.AddString(_T("en"));
m_comboHelpLocale.AddString(_T("pt-BR"));
}
void PopulateControls()
{
SetDefaultConfig(m_ini, static_cast<const TCHAR *>(m_ConfigLabel));
m_DisableInvoke = m_config->Get(GLOBAL_DISABLEINVOKE);
m_IgnoreWhitespace = m_config->Get(GLOBAL_IGNOREWHITESPACE);
m_IgnoreServerVersion = m_config->Get(GLOBAL_IGNORESERVERVERSION);
m_ShowCRLF = m_config->Get(GLOBAL_SHOWCRLF);
m_DisableAutoUpdate = m_ini->Get(GLOBAL_DISABLEAUTOUPDATE);
m_WorkUnitPollFreq = m_config->Get(GLOBAL_ACTIVEWORKUNIT_REFRESH);
m_WorkUnitFetchLimit = m_config->Get(GLOBAL_WORKUNIT_FETCHLIMIT);
m_WorkUnitPersistLimit = m_config->Get(GLOBAL_WORKUNIT_PERSISTLIMIT);
m_comboHelpLocaleStr = CString(m_config->Get(GLOBAL_HELP_LOCALE));
SetComboText(m_comboHelpLocale, m_comboHelpLocaleStr);
DoDataExchange();
DoChanged(false);
}
void UpdateConfig()
{
m_config->Set(GLOBAL_DISABLEINVOKE, m_DisableInvoke);
m_config->Set(GLOBAL_IGNOREWHITESPACE, m_IgnoreWhitespace);
m_config->Set(GLOBAL_IGNORESERVERVERSION, m_IgnoreServerVersion);
m_config->Set(GLOBAL_SHOWCRLF, m_ShowCRLF);
m_ini->Set(GLOBAL_DISABLEAUTOUPDATE, m_DisableAutoUpdate);
m_config->Set(GLOBAL_ACTIVEWORKUNIT_REFRESH, m_WorkUnitPollFreq);
m_config->Set(GLOBAL_WORKUNIT_FETCHLIMIT, m_WorkUnitFetchLimit);
m_config->Set(GLOBAL_WORKUNIT_PERSISTLIMIT, m_WorkUnitPersistLimit);
CString comboHelpLocaleStr;
m_comboHelpLocale.GetWindowText(comboHelpLocaleStr);
m_config->Set(GLOBAL_HELP_LOCALE, comboHelpLocaleStr);
}
void DoApply(bool bMakeGlobal)
{
DoDataExchange(true);
UpdateConfig();
DoChanged(false);
}
void DoChanged(bool bChanged=true)
{
m_owner->SetChanged(bChanged);
}
BEGIN_MSG_MAP(thisClass)
MSG_WM_INITDIALOG(OnInitDialog)
COMMAND_HANDLER(IDC_CHECK_DISABLEINVOKE, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_IGNOREWHITESPACE, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_CHECK_IGNORESERVERVERSION, BN_CLICKED, OnCheckClicked)
COMMAND_CODE_HANDLER(EN_CHANGE, OnChangedEdit)
COMMAND_HANDLER(IDC_CHECK_DISABLEAUTOUPDATE, BN_CLICKED, OnCheckClicked)
COMMAND_HANDLER(IDC_COMBO_HELP, CBN_SELCHANGE, OnCbnSelendokComboHelp)
COMMAND_HANDLER(IDC_COMBO_HELP, CBN_SELENDOK, OnCbnSelendokComboHelp)
NOTIFY_CODE_HANDLER(UDN_DELTAPOS, OnSpinChange)
COMMAND_HANDLER(IDC_BUTTON_GPF, BN_CLICKED, OnBnClickedButtonGpf)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
BEGIN_DDX_MAP(thisClass)
DDX_CHECK(IDC_CHECK_DISABLEINVOKE, m_DisableInvoke)
DDX_CHECK(IDC_CHECK_IGNOREWHITESPACE, m_IgnoreWhitespace)
DDX_CHECK(IDC_CHECK_IGNORESERVERVERSION, m_IgnoreServerVersion)
DDX_CHECK(IDC_CHECK_SHOWCRLF, m_ShowCRLF)
DDX_CHECK(IDC_CHECK_DISABLEAUTOUPDATE, m_DisableAutoUpdate)
DDX_INT(IDC_EDIT_WORKUNITPOLL, m_WorkUnitPollFreq)
DDX_INT(IDC_EDIT_WORKUNITFETCHLIMIT, m_WorkUnitFetchLimit)
DDX_INT(IDC_EDIT_WORKUNITPERSISTLIMIT, m_WorkUnitPersistLimit)
END_DDX_MAP()
LRESULT OnInitDialog(HWND /*wParam*/, LPARAM /*lParam*/)
{
CWaitCursor wait;
boost::filesystem::path iniPath;
m_ini = CreateIConfig(QUERYBUILDER_INI, GetIniPath(iniPath));
SetLimit(IDC_SPIN_WORKUNITPOLL, 5, 999);
SetLimit(IDC_SPIN_WORKUNITFETCHLIMIT, 100, 999999);
SetLimit(IDC_SPIN_WORKUNITPERSISTLIMIT, 0, 10);
InitComboHelpLocale();
LoadFromConfig(m_config); //this calls PopulateControls
DoChanged(false);
return TRUE;
}
LRESULT OnChangedEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
return 0;
}
LRESULT OnSpinChange(int idCtrl, LPNMHDR pnmHdr, BOOL &bHandled)
{
DoChanged();
return 0;
}
LRESULT OnCheckClicked(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
return 0;
}
LRESULT OnCbnSelendokComboHelp(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DoChanged();
CString comboHelpLocaleStr;
m_comboHelpLocaleStr = m_comboHelpLocale.GetLBText(m_comboHelpLocale.GetCurSel(), comboHelpLocaleStr);
return 0;
}
void SetLimit(int nId, int lower, int upper)
{
CUpDownCtrl ctrl = GetDlgItem(nId);
ctrl.SetRange(lower, upper);
}
LRESULT OnBnClickedButtonGpf(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
//std::_tstring strOut;
//runProcess(_T("cmd /c dot"), _T("c:\\temp"), _T("123"), strOut);
int * ptr = NULL;
*ptr = 0;
return 0;
}
};
// ===========================================================================
class CMyTabView : public CTabViewImpl<CMyTabView>
{
public:
DECLARE_WND_CLASS(_T("WTL_MyTabView"))
void UpdateLayout()
{
RECT rect;
GetClientRect(&rect);
if (m_tab.IsWindow() && ((m_tab.GetStyle() & WS_VISIBLE) != 0))
m_tab.SetWindowPos(NULL, 0, 0, rect.right - rect.left, m_cyTabHeight, SWP_NOZORDER);
if (m_nActivePage != -1)
::SetWindowPos(GetPageHWND(m_nActivePage), NULL, 0, m_cyTabHeight, rect.right - rect.left, rect.bottom - rect.top - m_cyTabHeight, SWP_NOZORDER);
}
};
class CPrefDlg : public CDialogImpl<CPrefDlg>, public CWinDataExchange<CPrefDlg>, public IOwner
{
typedef CPrefDlg thisClass;
typedef CDialogImpl<thisClass> baseClass;
protected:
bool m_changed;
IConfigAdapt m_config;
IConfigAdapt m_ini;
CString m_ConfigLabel;
CComboBox m_cbConfig;
int m_ConfigId;
CMyTabView m_tabView;
CPrefServerDlg m_serverPref;
CPrefEditorDlg m_editorPref;
CPrefColorDlg m_colorPref;
CPrefResultDlg m_resultPref;
CPrefCompilerDlg m_compilerPref;
CPrefOtherDlg m_otherPref;
bool m_disableEnvironmentSettings;
public:
CPrefDlg(IConfig * config, bool disableEnvironmentSettings) : m_serverPref(this, config, disableEnvironmentSettings), m_editorPref(this, config), m_colorPref(this, config), m_resultPref(this, config), m_compilerPref(this, config), m_otherPref(this, config)
{
m_disableEnvironmentSettings = disableEnvironmentSettings;
m_changed = false;
m_config = config;
m_ConfigLabel = m_config->GetLabel();
if (m_ConfigLabel.IsEmpty())
{
m_ConfigLabel = g_DefaultConfig;
}
}
enum { IDD = IDD_PREF };
void SetChanged(bool bChanged=true)
{
if ( bChanged )
{
if (!m_changed)
{
m_changed = true;
}
}
else
{
m_changed = false;
}
CWindow apply = GetDlgItem(ID_APPLY);
if (apply.IsWindow())
{
apply.EnableWindow(m_changed);
}
}
bool GetChanged()
{
return m_changed;
}
void InitConfig()
{
//update our private config
if (m_ConfigLabel.CompareNoCase(m_config->GetLabel()) != 0)
{
m_config->SetLabel(static_cast<const TCHAR *>(m_ConfigLabel));
}
SetDefaultConfig(m_ini, static_cast<const TCHAR *>(m_ConfigLabel));
m_config = GetIConfig(QUERYBUILDER_CFG);
}
void DoLoadFromConfig(bool changed)
{
m_serverPref.LoadFromConfig(m_config);
m_serverPref.DoChanged(changed);
m_editorPref.LoadFromConfig(m_config);
m_editorPref.DoChanged(changed);
m_colorPref.LoadFromConfig(m_config);
m_colorPref.DoChanged(changed);
m_resultPref.LoadFromConfig(m_config);
m_resultPref.DoChanged(changed);
m_compilerPref.LoadFromConfig(m_config);
m_compilerPref.DoChanged(changed);
m_otherPref.LoadFromConfig(m_config);
m_otherPref.DoChanged(changed);
}
bool DoApply(bool bMakeGlobal)
{
if (!m_serverPref.DoValidate())
{
m_tabView.SetActivePage(m_tabView.PageIndexFromHwnd(m_serverPref));
return false;
}
if ( !bMakeGlobal )
{
//if this is the same as the global one, then update the global one
bMakeGlobal = (m_ConfigLabel.CompareNoCase(m_config->GetLabel()) != 0);
}
//we are setting this config as the global config
//TODO Gordon needs to retest this...
if ( bMakeGlobal )
{
m_config->SetLabel(static_cast<const TCHAR *>(m_ConfigLabel));
}
m_serverPref.DoApply(bMakeGlobal);
m_editorPref.DoApply(bMakeGlobal);
m_colorPref.DoApply(bMakeGlobal);
m_resultPref.DoApply(bMakeGlobal);
m_compilerPref.DoApply(bMakeGlobal);
m_otherPref.DoApply(bMakeGlobal);
SaveColorFiles();
return true;
}
BEGIN_MSG_MAP(thisClass)
MSG_WM_INITDIALOG(OnInitDialog)
COMMAND_HANDLER_EX(IDC_COMBO_CONFIG, CBN_SELENDOK, OnSelEndOkConfig)
COMMAND_HANDLER(IDC_LOCATE, BN_CLICKED, OnBnLocate)
COMMAND_HANDLER(IDC_SAVE_AS, BN_CLICKED, OnBnSaveAs)
COMMAND_HANDLER(IDC_CONFIG_DELETE, BN_CLICKED, OnBnDelete)
COMMAND_ID_HANDLER_EX(IDOK, OnOk)
COMMAND_ID_HANDLER_EX(IDCANCEL, OnCancel)
COMMAND_ID_HANDLER_EX(ID_APPLY, OnApply)
// REFLECT_NOTIFICATIONS()
END_MSG_MAP()
BEGIN_DDX_MAP(thisClass)
END_DDX_MAP()
LRESULT OnInitDialog(HWND /*wParam*/, LPARAM /*lParam*/)
{
//update our private config
if (m_ConfigLabel.CompareNoCase(m_config->GetLabel()) != 0)
{
m_config->SetLabel(static_cast<const TCHAR *>(m_ConfigLabel));
}
boost::filesystem::path iniPath;
m_ini = CreateIConfig(QUERYBUILDER_INI, GetIniPath(iniPath));
SetDefaultConfig(m_ini, static_cast<const TCHAR *>(m_ConfigLabel));
CWindow wndPlaceholder = GetDlgItem(IDC_SHEET);
CRect rc;
wndPlaceholder.GetWindowRect ( rc );
ScreenToClient(rc);
wndPlaceholder.DestroyWindow();
m_tabView.Create(*this, rc, _T(""), WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, NULL, IDC_SHEET);
m_serverPref.Create(m_tabView);
m_tabView.AddPage(m_serverPref, _T("Server"));
m_editorPref.Create(m_tabView);
m_tabView.AddPage(m_editorPref, _T("Editor"));
m_colorPref.Create(m_tabView);
m_tabView.AddPage(m_colorPref, _T("Colors"));
m_resultPref.Create(m_tabView);
m_tabView.AddPage(m_resultPref, _T("Results"));
m_compilerPref.Create(m_tabView);
m_tabView.AddPage(m_compilerPref, _T("Compiler"));
m_otherPref.Create(m_tabView);
m_tabView.AddPage(m_otherPref, _T("Other"));
m_tabView.SetActivePage(0);
m_cbConfig = GetDlgItem(IDC_COMBO_CONFIG);
if (!::PopulateConfigCombo(m_cbConfig, (const TCHAR *)m_ConfigLabel)) // No existing configurations
{
DoLoadFromConfig(false);
m_compilerPref.LoadDefaults();
DoApply(true);
}
m_ConfigId = m_cbConfig.GetCurSel();
GetDlgItem(IDC_LOCATE).EnableWindow(true);
if (m_disableEnvironmentSettings)
{
m_cbConfig.EnableWindow(false);
GetDlgItem(IDC_SAVE_AS).EnableWindow(false);
GetDlgItem(IDC_CONFIG_DELETE).EnableWindow(false);
}
else
{
GetDlgItem(IDC_SAVE_AS).EnableWindow(true);
GetDlgItem(IDC_CONFIG_DELETE).EnableWindow(m_ConfigLabel != g_DefaultConfig);
}
return 0;
}
void OnSelEndOkConfig(UINT /*nId*/, int /*wID*/, HWND /*hWndCtl*/)
{
CString title;
GetWindowText(title);
if ( GetChanged() && IDNO == MessageBox(_T("Lose Changes?"), title, MB_YESNO | MB_DEFBUTTON1 | MB_ICONQUESTION) )
{
//set it back
m_cbConfig.SetCurSel( m_ConfigId );
return;
}
CWaitCursor wait;
//get name of selected config
m_ConfigId = m_cbConfig.GetCurSel();
m_cbConfig.GetLBText(m_ConfigId, m_ConfigLabel);
InitConfig();
DoLoadFromConfig(false);
}
LRESULT OnBnLocate(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
boost::filesystem::path path;
GetApplicationFolder(path);
std::_tstring native_path = pathToWString(path);
::ShellExecute(m_hWnd, _T("open"), native_path.c_str(), _T(""), native_path.c_str(), SW_SHOW);
return 0;
}
LRESULT OnBnSaveAs(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CString newLabel(_T("New"));
tryagain:
if ( ::ShowSimplePrompt(m_hWnd,_T("New"),_T("Config:"), newLabel) )
{
CWaitCursor wait;
if (IsValidIdentifier(static_cast<const TCHAR *>(newLabel)))
{
m_ConfigLabel = newLabel;
m_cbConfig.SetCurSel(m_cbConfig.AddString(m_ConfigLabel));
InitConfig();
DoLoadFromConfig(true);
SetChanged(true);
m_compilerPref.LoadDefaults();
//don't need to create the file, it will get created when the hit OK
//m_iConfig->SaveAs(newLabel);
}
else
{
MessageBox(_T("Invalid configuration name..."), CString(MAKEINTRESOURCE(IDR_MAINFRAME)), MB_ICONEXCLAMATION);
goto tryagain;
}
}
return 0;
}
LRESULT OnBnDelete(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CString title;
GetWindowText(title);
CString prompt;
prompt.FormatMessage(_T("Delete Configuration '%1'?"), m_ConfigLabel);
if ( IDYES == MessageBox(prompt,title,MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) )
{
CWaitCursor wait;
SetChanged(false);
boost::filesystem::path path;
GetConfigPath(static_cast<const TCHAR *>(m_ConfigLabel), path);
boost::filesystem::remove(path);
//delete the current selection
m_cbConfig.DeleteString(m_cbConfig.GetCurSel());
//pick the next one
if(m_cbConfig.GetCount() == 0)
{
m_cbConfig.AddString(_T("default"));
}
m_cbConfig.SetCurSel(0);
m_cbConfig.GetLBText(0,m_ConfigLabel);
//if this is the global one reset it
//TODO Gordon needs to retest this...
m_config->SetLabel(static_cast<const TCHAR *>(m_ConfigLabel));
DoLoadFromConfig(false);
}
return 0;
}
void OnOk(UINT /*uNotifyCode*/, int nID, HWND /*hWnd*/)
{
if (DoApply(true))
{
EndDialog(nID);
}
}
void OnCancel(UINT /*uNotifyCode*/, int nID, HWND /*hWnd*/)
{
if ( m_changed )
{
CString title;
GetWindowText(title);
if ( IDNO == MessageBox(_T("Lose Changes?"),title,MB_YESNO | MB_DEFBUTTON1 | MB_ICONQUESTION) )
{
return;
}
}
m_colorPref.DoRestore();
EndDialog(nID);
}
void OnApply(UINT /*uNotifyCode*/, int /*nID*/, HWND /*hWnd*/)
{
DoApply(false);
}
};
// ===========================================================================
bool ShowPreferencesDlg(CComPtr<IConfig> config, bool disableEnvironmentSettings)
{
CPrefDlg dlg(config, disableEnvironmentSettings);
dlg.DoModal();
return true; //true if changed, it may have been
}
| 28.983573 | 257 | 0.708778 | [
"vector"
] |
33ea6d649f3e8727d3976d77dbf365cb39da964e | 1,348 | cpp | C++ | codeforces/anirudhak47/746/B.cpp | anirudhakulkarni/codes | d7a907951033b57314dfc0b837123aaa5c25a39a | [
"MIT"
] | 3 | 2020-07-09T16:15:42.000Z | 2020-07-17T13:19:42.000Z | codeforces/anirudhak47/746/B.cpp | anirudhakulkarni/codes | d7a907951033b57314dfc0b837123aaa5c25a39a | [
"MIT"
] | null | null | null | codeforces/anirudhak47/746/B.cpp | anirudhakulkarni/codes | d7a907951033b57314dfc0b837123aaa5c25a39a | [
"MIT"
] | 1 | 2020-07-17T13:19:48.000Z | 2020-07-17T13:19:48.000Z | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector< vi > vvi;
/////////////////////////
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define loop(i,a,b) for (int i = a; i < b; i++)
//////////////////////////
#define printvector(n) for(int i=0;i<n.size();i++){cout<<n[i]<<" ";}cout<<'\n'
#define printstack(n) for(int i=0;i<n.size();i++){cout<<n[i]<<" ";}cout<<'\n'
#define PI_val 3.14159265359
#define printpair(n) cout<<n.F<<" "<<n.S
#define printvop(n) loop(i,0,n.size()-1){printpair(n[i])<<endl;}
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define endl "\n"
long long int mod=1000000007;
//////////////////////////
int main()
{
#ifndef ONLINE_JUDGE
// for getting input from input.txt
freopen("E:/codes/testcases/input.in", "r", stdin);
// for writing output to output.txt
freopen("E:/codes/testcases/output.in", "w", stdout);
#endif
long long int a,b,x,n,m,k,sum=0,ans=0,res=0;
cin >> n;
string s,ss="";
cin>>s;
if(n%2==0){
for(int i=n-2;i>=0;i-=2){
ss+=s[i];
}
for(int i=1;i<n;i+=2){
ss+=s[i];
}
}
else{
for(int i=n-2;i>=0;i-=2){
ss+=s[i];
}
for(int i=0;i<n;i+=2){
ss+=s[i];
}
}
cout<<ss;
return 0;
} | 25.433962 | 79 | 0.540801 | [
"vector"
] |
33ec25dd89c291132a79fe4d65aa4a2c48d52e02 | 2,905 | cpp | C++ | src/Normalizer.cpp | BR903/percolator | 2d9315699cf3309421b83c4c21ce8275ede87089 | [
"Apache-2.0"
] | 71 | 2015-03-30T17:22:52.000Z | 2022-01-01T14:19:23.000Z | src/Normalizer.cpp | BR903/percolator | 2d9315699cf3309421b83c4c21ce8275ede87089 | [
"Apache-2.0"
] | 190 | 2015-01-27T16:18:58.000Z | 2022-03-31T16:49:58.000Z | src/Normalizer.cpp | BR903/percolator | 2d9315699cf3309421b83c4c21ce8275ede87089 | [
"Apache-2.0"
] | 45 | 2015-04-13T13:42:35.000Z | 2021-12-17T08:26:21.000Z | /*******************************************************************************
Copyright 2006-2012 Lukas Käll <lukas.kall@scilifelab.se>
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 <assert.h>
#include <iostream>
#include <vector>
#include <set>
#include <string>
using namespace std;
#include "Normalizer.h"
#include "StdvNormalizer.h"
#include "UniNormalizer.h"
#include "NoNormalizer.h"
#include "Globals.h"
int Normalizer::subclass_type = STDV;
Normalizer* Normalizer::theNormalizer = NULL;
Normalizer::Normalizer() {
}
Normalizer::~Normalizer() {
}
void Normalizer::normalizeSet(vector<double*>& featuresV,
vector<double*>& rtFeaturesV) {
normalizeSet(featuresV, 0, numFeatures);
normalizeSet(rtFeaturesV, numFeatures, numRetentionFeatures);
}
void Normalizer::normalizeSet(vector<double*>& featuresV,
size_t offset, size_t numFeatures) {
double* features;
vector<double*>::iterator it = featuresV.begin();
for (; it != featuresV.end(); ++it) {
features = *it;
normalize(features, features, offset, numFeatures);
}
}
void Normalizer::normalize(const double* in, double* out, size_t offset,
size_t numFeatures) {
for (unsigned int ix = 0; ix < numFeatures; ++ix) {
out[ix] = (in[ix] - sub[offset + ix]) / div[offset + ix];
}
}
Normalizer* Normalizer::getNormalizer() {
if (theNormalizer == NULL) {
if (subclass_type == UNI) {
theNormalizer = new UniNormalizer();
} else if (subclass_type == STDV) {
theNormalizer = new StdvNormalizer();
} else {
theNormalizer = new NoNormalizer();
}
} else {
assert(false);
cerr << "Multiple instantiations of Normalizer" << endl;
}
return theNormalizer;
}
void Normalizer::setType(int type) {
assert(type == UNI || type == STDV || type == NONORM);
subclass_type = type;
}
// Before merging cross validation bins, the scores are renormalized to an uniform range.
// This function is designed to transform weights so that they give scores in that range.
void Normalizer::endScoreNormalizeWeights(const std::vector<double>& in,
std::vector<double>& out, double subScore, double scale) {
size_t i = 0;
for (; i < in.size()-1; i++) {
out[i] = in[i] / scale;
}
out[i] = (in[i] - subScore)/scale;
}
| 31.576087 | 89 | 0.64475 | [
"vector",
"transform"
] |
33ef98af4f58ecc54abb38f3695a34032642c136 | 6,229 | cpp | C++ | map/map_tests/gps_track_test.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 2 | 2019-01-24T15:36:20.000Z | 2019-12-26T10:03:48.000Z | map/map_tests/gps_track_test.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 13 | 2015-09-28T13:59:23.000Z | 2015-10-08T20:12:45.000Z | map/map_tests/gps_track_test.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:31:29.000Z | 2019-08-09T21:31:29.000Z | #include "testing/testing.hpp"
#include "map/gps_track.hpp"
#include "platform/platform.hpp"
#include "coding/file_name_utils.hpp"
#include "coding/file_writer.hpp"
#include "geometry/latlon.hpp"
#include "base/logging.hpp"
#include "base/scope_guard.hpp"
#include "std/bind.hpp"
#include "std/chrono.hpp"
namespace
{
inline location::GpsInfo Make(double timestamp, ms::LatLon const & ll, double speed)
{
location::GpsInfo info;
info.m_timestamp = timestamp;
info.m_speed = speed;
info.m_latitude = ll.lat;
info.m_longitude = ll.lon;
info.m_horizontalAccuracy = 15;
info.m_source = location::EAndroidNative;
return info;
}
inline string GetGpsTrackFilePath()
{
return my::JoinFoldersToPath(GetPlatform().WritableDir(), "gpstrack_test.bin");
}
class GpsTrackCallback
{
public:
GpsTrackCallback()
: m_toRemove(make_pair(GpsTrack::kInvalidId, GpsTrack::kInvalidId))
, m_gotCallback(false)
{
}
void OnUpdate(vector<pair<size_t, location::GpsTrackInfo>> && toAdd,
pair<size_t, size_t> const & toRemove)
{
m_toAdd = move(toAdd);
m_toRemove = toRemove;
lock_guard<mutex> lg(m_mutex);
m_gotCallback = true;
m_cv.notify_one();
}
void Reset()
{
m_toAdd.clear();
m_toRemove = make_pair(GpsTrack::kInvalidId, GpsTrack::kInvalidId);
lock_guard<mutex> lg(m_mutex);
m_gotCallback = false;
}
bool WaitForCallback(seconds t)
{
unique_lock<mutex> ul(m_mutex);
return m_cv.wait_for(ul, t, [this]()->bool{ return m_gotCallback; });
}
vector<pair<size_t, location::GpsTrackInfo>> m_toAdd;
pair<size_t, size_t> m_toRemove;
private:
mutex m_mutex;
condition_variable m_cv;
bool m_gotCallback;
};
seconds const kWaitForCallbackTimeout = seconds(5);
} // namespace
UNIT_TEST(GpsTrack_Simple)
{
string const filePath = GetGpsTrackFilePath();
MY_SCOPE_GUARD(gpsTestFileDeleter, bind(FileWriter::DeleteFileX, filePath));
FileWriter::DeleteFileX(filePath);
time_t const t = system_clock::to_time_t(system_clock::now());
double const timestamp = t;
LOG(LINFO, ("Timestamp", ctime(&t), timestamp));
size_t const maxItemCount = 100000;
size_t const writeItemCount = 50000; // less than 24h
vector<location::GpsInfo> points;
points.reserve(writeItemCount);
for (size_t i = 0; i < writeItemCount; ++i)
points.emplace_back(Make(timestamp + i, ms::LatLon(-90.0 + i, -180.0 + i), 10 + i));
// Store points
{
GpsTrack track(filePath, maxItemCount, hours(24));
track.AddPoints(points);
GpsTrackCallback callback;
track.SetCallback(bind(&GpsTrackCallback::OnUpdate, &callback, _1, _2));
TEST(callback.WaitForCallback(kWaitForCallbackTimeout), ());
TEST_EQUAL(callback.m_toRemove.first, GpsTrack::kInvalidId, ());
TEST_EQUAL(callback.m_toRemove.second, GpsTrack::kInvalidId, ());
TEST_EQUAL(callback.m_toAdd.size(), writeItemCount, ());
for (size_t i = 0; i < writeItemCount; ++i)
{
TEST_EQUAL(i, callback.m_toAdd[i].first, ());
TEST_EQUAL(points[i].m_timestamp, callback.m_toAdd[i].second.m_timestamp, ());
TEST_EQUAL(points[i].m_speed, callback.m_toAdd[i].second.m_speed, ());
TEST_EQUAL(points[i].m_latitude, callback.m_toAdd[i].second.m_latitude, ());
TEST_EQUAL(points[i].m_longitude, callback.m_toAdd[i].second.m_longitude, ());
}
}
// Restore points
{
GpsTrack track(filePath, maxItemCount, hours(24));
GpsTrackCallback callback;
track.SetCallback(bind(&GpsTrackCallback::OnUpdate, &callback, _1, _2));
TEST(callback.WaitForCallback(kWaitForCallbackTimeout), ());
TEST_EQUAL(callback.m_toRemove.first, GpsTrack::kInvalidId, ());
TEST_EQUAL(callback.m_toRemove.second, GpsTrack::kInvalidId, ());
TEST_EQUAL(callback.m_toAdd.size(), writeItemCount, ());
for (size_t i = 0; i < writeItemCount; ++i)
{
TEST_EQUAL(i, callback.m_toAdd[i].first, ());
TEST_EQUAL(points[i].m_timestamp, callback.m_toAdd[i].second.m_timestamp, ());
TEST_EQUAL(points[i].m_speed, callback.m_toAdd[i].second.m_speed, ());
TEST_EQUAL(points[i].m_latitude, callback.m_toAdd[i].second.m_latitude, ());
TEST_EQUAL(points[i].m_longitude, callback.m_toAdd[i].second.m_longitude, ());
}
}
}
UNIT_TEST(GpsTrack_EvictedByAdd)
{
string const filePath = GetGpsTrackFilePath();
MY_SCOPE_GUARD(gpsTestFileDeleter, bind(FileWriter::DeleteFileX, filePath));
FileWriter::DeleteFileX(filePath);
time_t const t = system_clock::to_time_t(system_clock::now());
double const timestamp = t;
LOG(LINFO, ("Timestamp", ctime(&t), timestamp));
location::GpsInfo pt1 = Make(timestamp - 25 * 60 * 60, ms::LatLon(30.0, 45.0), 60.0);
location::GpsInfo pt2 = Make(timestamp, ms::LatLon(75.0, 90.0), 110.0);
GpsTrack track(filePath, 1000, hours(24));
GpsTrackCallback callback;
track.SetCallback(bind(&GpsTrackCallback::OnUpdate, &callback, _1, _2));
track.AddPoint(pt1);
TEST(callback.WaitForCallback(kWaitForCallbackTimeout), ());
// Check pt1 was added
TEST_EQUAL(1, callback.m_toAdd.size(), ());
TEST_EQUAL(0, callback.m_toAdd[0].first, ());
TEST_EQUAL(pt1.m_timestamp, callback.m_toAdd[0].second.m_timestamp, ());
TEST_EQUAL(pt1.m_speed, callback.m_toAdd[0].second.m_speed, ());
TEST_EQUAL(pt1.m_latitude, callback.m_toAdd[0].second.m_latitude, ());
TEST_EQUAL(pt1.m_longitude, callback.m_toAdd[0].second.m_longitude, ());
// and nothing was evicted
TEST_EQUAL(callback.m_toRemove.first, GpsTrack::kInvalidId, ());
TEST_EQUAL(callback.m_toRemove.second, GpsTrack::kInvalidId, ());
callback.Reset();
track.AddPoint(pt2);
TEST(callback.WaitForCallback(kWaitForCallbackTimeout), ());
// Check pt2 was added
TEST_EQUAL(1, callback.m_toAdd.size(), ());
TEST_EQUAL(1, callback.m_toAdd[0].first, ());
TEST_EQUAL(pt2.m_timestamp, callback.m_toAdd[0].second.m_timestamp, ());
TEST_EQUAL(pt2.m_speed, callback.m_toAdd[0].second.m_speed, ());
TEST_EQUAL(pt2.m_latitude, callback.m_toAdd[0].second.m_latitude, ());
TEST_EQUAL(pt2.m_longitude, callback.m_toAdd[0].second.m_longitude, ());
// and pt1 was evicted as old
TEST_EQUAL(callback.m_toRemove.first, 0, ());
TEST_EQUAL(callback.m_toRemove.second, 0, ());
}
| 31.145 | 88 | 0.707497 | [
"geometry",
"vector"
] |
33f20f13c64d2a0b92cd70b90dc8a6af30112348 | 682 | hpp | C++ | src/runtime/core_factory.hpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | 1 | 2021-07-10T21:25:03.000Z | 2021-07-10T21:25:03.000Z | src/runtime/core_factory.hpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | null | null | null | src/runtime/core_factory.hpp | GeniusVentures/SuperGenius | ae43304f4a2475498ef56c971296175acb88d0ee | [
"MIT"
] | null | null | null |
#ifndef SUPERGENIUS_SRC_RUNTIME_CORE_FACTORY
#define SUPERGENIUS_SRC_RUNTIME_CORE_FACTORY
#include "runtime/core.hpp"
namespace sgns::runtime {
namespace binaryen {
class RuntimeManager;
}
/**
* An abstract factory that enables construction of Core objects over specific
* WASM code
*/
class CoreFactory {
public:
virtual ~CoreFactory() = default;
/**
* Creates a Core API object backed by the code that \arg wasm_provider
* serves
*/
virtual std::unique_ptr<Core> createWithCode(
std::shared_ptr<WasmProvider> wasm_provider) = 0;
};
} // namespace sgns::runtime
#endif // SUPERGENIUS_SRC_RUNTIME_CORE_FACTORY
| 20.666667 | 80 | 0.705279 | [
"object"
] |
33f23153faa5b126f21796f9a41242a2bcb8877c | 29,409 | cpp | C++ | src/testrender/testrender.cpp | marsupial/OpenShadingLanguage | 62797a9032a73162a62e19d03261d7d8bd3a8ded | [
"BSD-3-Clause"
] | 2 | 2019-10-05T20:01:05.000Z | 2021-07-29T19:28:18.000Z | src/testrender/testrender.cpp | marsupial/OpenShadingLanguage | 62797a9032a73162a62e19d03261d7d8bd3a8ded | [
"BSD-3-Clause"
] | null | null | null | src/testrender/testrender.cpp | marsupial/OpenShadingLanguage | 62797a9032a73162a62e19d03261d7d8bd3a8ded | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks 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 <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
#include <OpenImageIO/argparse.h>
#include <OpenImageIO/strutil.h>
#include <OpenImageIO/timer.h>
#include <OpenImageIO/thread.h>
#ifdef USE_EXTERNAL_PUGIXML
# include <pugixml.hpp>
#else
# include <OpenImageIO/pugixml.hpp>
#endif
#include <OSL/oslexec.h>
#include "simplerend.h"
#include "raytracer.h"
#include "background.h"
#include "shading.h"
#include "sampling.h"
#include "util.h"
using namespace OSL;
namespace { // anonymous namespace
ShadingSystem *shadingsys = NULL;
bool debug1 = false;
bool debug2 = false;
bool verbose = false;
bool runstats = false;
int profile = 0;
bool O0 = false, O1 = false, O2 = false;
bool debugnan = false;
static std::string extraoptions;
int xres = 640, yres = 480, aa = 1, max_bounces = 1000000, rr_depth = 5;
int num_threads = 0;
ErrorHandler errhandler;
SimpleRenderer rend; // RendererServices
Camera camera;
Scene scene;
int backgroundShaderID = -1;
int backgroundResolution = 0;
Background background;
std::vector<ShaderGroupRef> shaders;
std::string scenefile, imagefile;
static std::string shaderpath;
static void
set_profile (int argc, const char *argv[])
{
profile = 1;
shadingsys->attribute ("profile", profile);
}
int get_filenames(int argc, const char *argv[])
{
for (int i = 0; i < argc; i++) {
if (scenefile.empty())
scenefile = argv[i];
else if (imagefile.empty())
imagefile = argv[i];
}
return 0;
}
void getargs(int argc, const char *argv[])
{
bool help = false;
OIIO::ArgParse ap;
ap.options ("Usage: testrender [options] scene.xml output.exr",
"%*", get_filenames, "",
"--help", &help, "Print help message",
"-v", &verbose, "Verbose messages",
"--debug", &debug1, "Lots of debugging info",
"--debug2", &debug2, "Even more debugging info",
"--runstats", &runstats, "Print run statistics",
"--stats", &runstats, "", // DEPRECATED 1.7
"--profile %@", &set_profile, NULL, "Print profile information",
"-r %d %d", &xres, &yres, "Render a WxH image",
"-aa %d", &aa, "Trace NxN rays per pixel",
"-t %d", &num_threads, "Render using N threads (default: auto-detect)",
"-O0", &O0, "Do no runtime shader optimization",
"-O1", &O1, "Do a little runtime shader optimization",
"-O2", &O2, "Do lots of runtime shader optimization",
"--debugnan", &debugnan, "Turn on 'debugnan' mode",
"--path %s", &shaderpath, "Specify oso search path",
"--options %s", &extraoptions, "Set extra OSL options",
NULL);
if (ap.parse(argc, argv) < 0) {
std::cerr << ap.geterror() << std::endl;
ap.usage ();
exit (EXIT_FAILURE);
}
if (help) {
std::cout <<
"testrender -- Test Renderer for Open Shading Language\n"
OSL_COPYRIGHT_STRING "\n";
ap.usage ();
exit (EXIT_SUCCESS);
}
if (scenefile.empty()) {
std::cerr << "testrender: Must specify an xml scene file to open\n";
ap.usage();
exit (EXIT_FAILURE);
}
if (imagefile.empty()) {
std::cerr << "testrender: Must specify a filename for output render\n";
ap.usage();
exit (EXIT_FAILURE);
}
if (debug1 || verbose)
errhandler.verbosity (ErrorHandler::VERBOSE);
}
Vec3 strtovec(const char* str) {
Vec3 v(0, 0, 0);
sscanf(str, " %f , %f , %f", &v.x, &v.y, &v.z);
return v;
}
int strtoint(const char* str) {
int i = 0;
sscanf(str, " %d", &i);
return i;
}
float strtoflt(const char* str) {
float f = 0;
sscanf(str, " %f", &f);
return f;
}
bool strtobool(const char* str) {
return strcmp(str, "1") == 0 ||
strcmp(str, "on") == 0 ||
strcmp(str, "yes") == 0;
}
template <int N>
struct ParamStorage {
ParamStorage() : fparamindex(0), iparamindex(0), sparamindex(0) {}
void* Int(int i) {
ASSERT(iparamindex < N);
iparamdata[iparamindex] = i;
iparamindex++;
return &iparamdata[iparamindex - 1];
}
void* Float(float f) {
ASSERT(fparamindex < N);
fparamdata[fparamindex] = f;
fparamindex++;
return &fparamdata[fparamindex - 1];
}
void* Vec(float x, float y, float z) {
Float(x);
Float(y);
Float(z);
return &fparamdata[fparamindex - 3];
}
void* Str(const char* str) {
ASSERT(sparamindex < N);
sparamdata[sparamindex] = ustring(str);
sparamindex++;
return &sparamdata[sparamindex - 1];
}
private:
// storage for shader parameters
float fparamdata[N];
int iparamdata[N];
ustring sparamdata[N];
int fparamindex;
int iparamindex;
int sparamindex;
};
void parse_scene() {
// setup default camera (now that resolution is finalized)
camera = Camera(Vec3(0,0,0), Vec3(0,0,-1), Vec3(0,1,0), 90.0f, xres, yres);
// load entire text file into a buffer
std::ifstream file(scenefile.c_str(), std::ios::binary);
std::vector<char> text((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
if (text.empty()) {
std::cerr << "Error reading " << scenefile << "\n"
<< "File is either missing or empty\n";
exit (EXIT_FAILURE);
}
text.push_back(0); // make sure text ends with trailing 0
#ifdef USING_OIIO_PUGI
namespace pugi = OIIO::pugi;
#endif
// build DOM tree
pugi::xml_document doc;
pugi::xml_parse_result parse_result = doc.load_file(scenefile.c_str());
if (!parse_result) {
std::cerr << "XML parsed with errors: " << parse_result.description() << ", at offset " << parse_result.offset << "\n";
exit (EXIT_FAILURE);
}
pugi::xml_node root = doc.child("World");
if (!root) {
std::cerr << "Error reading " << scenefile << "\n"
<< "Root element <World> is missing\n";
exit (EXIT_FAILURE);
}
// loop over all children of world
for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling()) {
if (strcmp(node.name(), "Option") == 0) {
for (pugi::xml_attribute attr = node.first_attribute(); attr; attr = attr.next_attribute()) {
int i = 0;
if (sscanf(attr.value(), " int %d ", &i) == 1) {
if (strcmp(attr.name(), "max_bounces") == 0)
max_bounces = i;
else if (strcmp(attr.name(), "rr_depth") == 0)
rr_depth = i;
}
// TODO: pass any extra options to shading system (or texture system?)
}
} else if (strcmp(node.name(), "Camera") == 0) {
// defaults
Vec3 eye(0,0,0);
Vec3 dir(0,0,-1);
Vec3 up(0,1,0);
float fov = 90.f;
// load camera (only first attribute counts if duplicates)
pugi::xml_attribute eye_attr = node.attribute("eye");
pugi::xml_attribute dir_attr = node.attribute("dir");
pugi::xml_attribute at_attr = node.attribute("look_at");
pugi::xml_attribute up_attr = node.attribute("up");
pugi::xml_attribute fov_attr = node.attribute("fov");
if (eye_attr) eye = strtovec(eye_attr.value());
if (dir_attr) dir = strtovec(dir_attr.value()); else
if ( at_attr) dir = strtovec( at_attr.value()) - eye;
if ( up_attr) up = strtovec( up_attr.value());
if (fov_attr) fov = strtoflt(fov_attr.value());
// create actual camera
camera = Camera(eye, dir, up, fov, xres, yres);
} else if (strcmp(node.name(), "Sphere") == 0) {
// load sphere
pugi::xml_attribute center_attr = node.attribute("center");
pugi::xml_attribute radius_attr = node.attribute("radius");
if (center_attr && radius_attr) {
Vec3 center = strtovec(center_attr.value());
float radius = strtoflt(radius_attr.value());
if (radius > 0) {
pugi::xml_attribute light_attr = node.attribute("is_light");
bool is_light = light_attr ? strtobool(light_attr.value()) : false;
scene.add_sphere(Sphere(center, radius, int(shaders.size()) - 1, is_light));
}
}
} else if (strcmp(node.name(), "Quad") == 0) {
// load quad
pugi::xml_attribute corner_attr = node.attribute("corner");
pugi::xml_attribute edge_x_attr = node.attribute("edge_x");
pugi::xml_attribute edge_y_attr = node.attribute("edge_y");
if (corner_attr && edge_x_attr && edge_y_attr) {
pugi::xml_attribute light_attr = node.attribute("is_light");
bool is_light = light_attr ? strtobool(light_attr.value()) : false;
Vec3 co = strtovec(corner_attr.value());
Vec3 ex = strtovec(edge_x_attr.value());
Vec3 ey = strtovec(edge_y_attr.value());
scene.add_quad(Quad(co, ex, ey, int(shaders.size()) - 1, is_light));
}
} else if (strcmp(node.name(), "Background") == 0) {
pugi::xml_attribute res_attr = node.attribute("resolution");
if (res_attr)
backgroundResolution = strtoint(res_attr.value());
backgroundShaderID = int(shaders.size()) - 1;
} else if (strcmp(node.name(), "ShaderGroup") == 0) {
ShaderGroupRef group;
pugi::xml_attribute name_attr = node.attribute("name");
std::string name = name_attr? name_attr.value() : "";
pugi::xml_attribute type_attr = node.attribute("type");
std::string shadertype = type_attr ? type_attr.value() : "surface";
pugi::xml_attribute commands_attr = node.attribute("commands");
std::string commands = commands_attr ? commands_attr.value() : node.text().get();
if (commands.size())
group = shadingsys->ShaderGroupBegin (name, shadertype, commands);
else
group = shadingsys->ShaderGroupBegin (name);
ParamStorage<1024> store; // scratch space to hold parameters until they are read by Shader()
for (pugi::xml_node gnode = node.first_child(); gnode; gnode = gnode.next_sibling()) {
if (strcmp(gnode.name(), "Parameter") == 0) {
// handle parameters
for (pugi::xml_attribute attr = gnode.first_attribute(); attr; attr = attr.next_attribute()) {
int i = 0; float x = 0, y = 0, z = 0;
if (sscanf(attr.value(), " int %d ", &i) == 1)
shadingsys->Parameter(attr.name(), TypeDesc::TypeInt, store.Int(i));
else if (sscanf(attr.value(), " float %f ", &x) == 1)
shadingsys->Parameter(attr.name(), TypeDesc::TypeFloat, store.Float(x));
else if (sscanf(attr.value(), " vector %f %f %f", &x, &y, &z) == 3)
shadingsys->Parameter(attr.name(), TypeDesc::TypeVector, store.Vec(x, y, z));
else if (sscanf(attr.value(), " point %f %f %f", &x, &y, &z) == 3)
shadingsys->Parameter(attr.name(), TypeDesc::TypePoint, store.Vec(x, y, z));
else if (sscanf(attr.value(), " color %f %f %f", &x, &y, &z) == 3)
shadingsys->Parameter(attr.name(), TypeDesc::TypeColor, store.Vec(x, y, z));
else
shadingsys->Parameter(attr.name(), TypeDesc::TypeString, store.Str(attr.value()));
}
} else if (strcmp(gnode.name(), "Shader") == 0) {
pugi::xml_attribute type_attr = gnode.attribute("type");
pugi::xml_attribute name_attr = gnode.attribute("name");
pugi::xml_attribute layer_attr = gnode.attribute("layer");
const char* type = type_attr ? type_attr.value() : "surface";
if (name_attr && layer_attr)
shadingsys->Shader(type, name_attr.value(), layer_attr.value());
} else if (strcmp(gnode.name(), "ConnectShaders") == 0) {
// FIXME: find a more elegant way to encode this
pugi::xml_attribute sl = gnode.attribute("srclayer");
pugi::xml_attribute sp = gnode.attribute("srcparam");
pugi::xml_attribute dl = gnode.attribute("dstlayer");
pugi::xml_attribute dp = gnode.attribute("dstparam");
if (sl && sp && dl && dp)
shadingsys->ConnectShaders(sl.value(), sp.value(),
dl.value(), dp.value());
} else {
// unknow element?
}
}
shadingsys->ShaderGroupEnd();
shaders.push_back (group);
} else {
// unknown element?
}
}
if (root.next_sibling()) {
std::cerr << "Error reading " << scenefile << "\n"
<< "Found multiple top-level elements\n";
exit (EXIT_FAILURE);
}
}
void globals_from_hit(ShaderGlobals& sg, const Ray& r, const Dual2<float>& t, int id, bool flip) {
memset(&sg, 0, sizeof(ShaderGlobals));
Dual2<Vec3> P = r.point(t);
sg.P = P.val(); sg.dPdx = P.dx(); sg.dPdy = P.dy();
Dual2<Vec3> N = scene.normal(P, id);
sg.Ng = sg.N = N.val();
Dual2<Vec2> uv = scene.uv(P, N, sg.dPdu, sg.dPdv, id);
sg.u = uv.val().x; sg.dudx = uv.dx().x; sg.dudy = uv.dy().x;
sg.v = uv.val().y; sg.dvdx = uv.dx().y; sg.dvdy = uv.dy().y;
sg.surfacearea = scene.surfacearea(id);
sg.I = r.d.val();
sg.dIdx = r.d.dx();
sg.dIdy = r.d.dy();
sg.backfacing = sg.N.dot(sg.I) > 0;
if (sg.backfacing) {
sg.N = -sg.N;
sg.Ng = -sg.Ng;
}
sg.flipHandedness = flip;
// In our SimpleRenderer, the "renderstate" itself just a pointer to
// the ShaderGlobals.
sg.renderstate = &sg;
}
Vec3 eval_background(const Dual2<Vec3>& dir, ShadingContext* ctx) {
ShaderGlobals sg;
memset(&sg, 0, sizeof(ShaderGlobals));
sg.I = dir.val();
sg.dIdx = dir.dx();
sg.dIdy = dir.dy();
shadingsys->execute(ctx, *shaders[backgroundShaderID], sg);
return process_background_closure(sg.Ci);
}
Color3 subpixel_radiance(float x, float y, Sampler& sampler, ShadingContext* ctx) {
Ray r = camera.get(x, y);
Color3 path_weight(1, 1, 1);
Color3 path_radiance(0, 0, 0);
int prev_id = -1;
float bsdf_pdf = std::numeric_limits<float>::infinity(); // camera ray has only one possible direction
bool flip = false;
for (int b = 0; b <= max_bounces; b++) {
// trace the ray against the scene
Dual2<float> t; int id = prev_id;
if (!scene.intersect(r, t, id)) {
// we hit nothing? check background shader
if (backgroundShaderID >= 0) {
if (backgroundResolution > 0) {
float bg_pdf = 0;
Vec3 bg = background.eval(r.d.val(), bg_pdf);
path_radiance += path_weight * bg * MIS::power_heuristic<MIS::WEIGHT_WEIGHT>(bsdf_pdf, bg_pdf);
} else {
// we aren't importance sampling the background - so just run it directly
path_radiance += path_weight * eval_background(r.d, ctx);
}
}
break;
}
// construct a shader globals for the hit point
ShaderGlobals sg;
globals_from_hit(sg, r, t, id, flip);
int shaderID = scene.shaderid(id);
if (shaderID < 0 || !shaders[shaderID]) break; // no shader attached? done
// execute shader and process the resulting list of closures
shadingsys->execute (ctx, *shaders[shaderID], sg);
ShadingResult result;
bool last_bounce = b == max_bounces;
process_closure(result, sg.Ci, last_bounce);
// add self-emission
float k = 1;
if (scene.islight(id)) {
// figure out the probability of reaching this point
float light_pdf = scene.shapepdf(id, r.o.val(), sg.P);
k = MIS::power_heuristic<MIS::WEIGHT_EVAL>(bsdf_pdf, light_pdf);
}
path_radiance += path_weight * k * result.Le;
// last bounce? nothing left to do
if (last_bounce) break;
// build internal pdf for sampling between bsdf closures
result.bsdf.prepare(sg, path_weight, b >= rr_depth);
// get two random numbers
Vec3 s = sampler.get();
float xi = s.x;
float yi = s.y;
float zi = s.z;
// trace one ray to the background
if (backgroundResolution > 0) {
Dual2<Vec3> bg_dir;
float bg_pdf = 0, bsdf_pdf = 0;
Vec3 bg = background.sample(xi, yi, bg_dir, bg_pdf);
Color3 bsdf_weight = result.bsdf.eval(sg, bg_dir.val(), bsdf_pdf);
Color3 contrib = path_weight * bsdf_weight * bg * MIS::power_heuristic<MIS::WEIGHT_WEIGHT>(bg_pdf, bsdf_pdf);
if ((contrib.x + contrib.y + contrib.z) > 0) {
int shadow_id = id;
Ray shadow_ray = Ray(sg.P, bg_dir);
Dual2<float> shadow_dist;
if (!scene.intersect(shadow_ray, shadow_dist, shadow_id)) // ray reached the background?
path_radiance += contrib;
}
}
// trace one ray to each light
for (int lid = 0; lid < scene.num_prims(); lid++) {
if (lid == id) continue; // skip self
if (!scene.islight(lid)) continue; // doesn't want to be sampled as a light
int shaderID = scene.shaderid(lid);
if (shaderID < 0 || !shaders[shaderID]) continue; // no shader attached to this light
// sample a random direction towards the object
float light_pdf;
Vec3 ldir = scene.sample(lid, sg.P, xi, yi, light_pdf);
float bsdf_pdf = 0;
Color3 contrib = path_weight * result.bsdf.eval(sg, ldir, bsdf_pdf) * MIS::power_heuristic<MIS::EVAL_WEIGHT>(light_pdf, bsdf_pdf);
if ((contrib.x + contrib.y + contrib.z) > 0) {
Ray shadow_ray = Ray(sg.P, ldir);
// trace a shadow ray and see if we actually hit the target
// in this tiny renderer, tracing a ray is probably cheaper than evaluating the light shader
int shadow_id = id; // ignore self hit
Dual2<float> shadow_dist;
if (scene.intersect(shadow_ray, shadow_dist, shadow_id) && shadow_id == lid) {
// setup a shader global for the point on the light
ShaderGlobals light_sg;
globals_from_hit(light_sg, shadow_ray, shadow_dist, lid, false);
// execute the light shader (for emissive closures only)
shadingsys->execute (ctx, *shaders[shaderID], light_sg);
ShadingResult light_result;
process_closure(light_result, light_sg.Ci, true);
// accumulate contribution
path_radiance += contrib * light_result.Le;
}
}
}
// trace indirect ray and continue
path_weight *= result.bsdf.sample(sg, xi, yi, zi, r.d, bsdf_pdf);
if (!(path_weight.x > 0) && !(path_weight.y > 0) && !(path_weight.z > 0))
break; // filter out all 0's or NaNs
prev_id = id;
r.o = Dual2<Vec3>(sg.P, sg.dPdx, sg.dPdy);
flip ^= sg.Ng.dot(r.d.val()) > 0;
}
return path_radiance;
}
Color3 antialias_pixel(int x, int y, ShadingContext* ctx) {
Color3 result(0, 0, 0);
for (int ay = 0, si = 0; ay < aa; ay++) {
for (int ax = 0; ax < aa; ax++, si++) {
Sampler sampler(x, y, si, aa);
// jitter pixel coordinate [0,1)^2
Vec3 j = sampler.get();
// warp distribution to approximate a tent filter [-1,+1)^2
j.x *= 2; j.x = j.x < 1 ? sqrtf(j.x) - 1 : 1 - sqrtf(2 - j.x);
j.y *= 2; j.y = j.y < 1 ? sqrtf(j.y) - 1 : 1 - sqrtf(2 - j.y);
// trace eye ray (apply jitter from center of the pixel)
result += subpixel_radiance(x + 0.5f + j.x, y + 0.5f + j.y, sampler, ctx);
}
}
return result / float(aa * aa);
}
void scanline_worker(Counter& counter, std::vector<Color3>& pixels) {
// Optional: high-performance apps may request this thread-specific
// pointer in order to save a bit of time on each shade. Just like
// the name implies, a multithreaded renderer would need to do this
// separately for each thread, and be careful to always use the same
// thread_info each time for that thread.
//
// There's nothing wrong with a simpler app just passing NULL for
// the thread_info; in such a case, the ShadingSystem will do the
// necessary calls to find the thread-specific pointer itself, but
// this will degrade performance just a bit.
OSL::PerThreadInfo *thread_info = shadingsys->create_thread_info();
// Request a shading context so that we can execute the shader.
// We could get_context/release_constext for each shading point,
// but to save overhead, it's more efficient to reuse a context
// within a thread.
ShadingContext *ctx = shadingsys->get_context (thread_info);
int y;
while (counter.getnext(y)) {
for (int x = 0, i = xres * y; x < xres; ++x, ++i)
pixels[i] = antialias_pixel(x, y, ctx);
}
// We're done shading with this context.
shadingsys->release_context (ctx);
// Now that we're done rendering, release the thread=specific
// pointer we saved. A simple app could skip this; but if the app
// asks for it (as we have in this example), then it should also
// destroy it when done with it.
shadingsys->destroy_thread_info(thread_info);
}
} // anonymous namespace
int main (int argc, const char *argv[]) {
using namespace OIIO;
Timer timer;
// Create a new shading system. We pass it the RendererServices
// object that services callbacks from the shading system, NULL for
// the TextureSystem (which will create a default OIIO one), and
// an error handler.
shadingsys = new ShadingSystem (&rend, NULL, &errhandler);
// Register the layout of all closures known to this renderer
// Any closure used by the shader which is not registered, or
// registered with a different number of arguments will lead
// to a runtime error.
register_closures(shadingsys);
// Remember that each shader parameter may optionally have a
// metadata hint [[int lockgeom=...]], where 0 indicates that the
// parameter may be overridden by the geometry itself, for example
// with data interpolated from the mesh vertices, and a value of 1
// means that it is "locked" with respect to the geometry (i.e. it
// will not be overridden with interpolated or
// per-geometric-primitive data).
//
// In order to most fully optimize shader, we typically want any
// shader parameter not explicitly specified to default to being
// locked (i.e. no per-geometry override):
shadingsys->attribute("lockgeom", 1);
// Read command line arguments
getargs (argc, argv);
// Setup common attributes
shadingsys->attribute ("debug", debug2 ? 2 : (debug1 ? 1 : 0));
shadingsys->attribute ("compile_report", debug1|debug2);
int opt = O2 ? 2 : (O1 ? 1 : 0);
if (const char *opt_env = getenv ("TESTSHADE_OPT")) // overrides opt
opt = atoi(opt_env);
shadingsys->attribute ("optimize", opt);
shadingsys->attribute ("debugnan", debugnan);
if (! shaderpath.empty())
shadingsys->attribute ("searchpath:shader", shaderpath);
if (extraoptions.size())
shadingsys->attribute ("options", extraoptions);
// Loads a scene, creating camera, geometry and assigning shaders
parse_scene();
// validate options
if (aa < 1) aa = 1;
if (num_threads < 1)
num_threads = std::thread::hardware_concurrency();
// prepare background importance table (if requested)
if (backgroundResolution > 0 && backgroundShaderID >= 0) {
// get a context so we can make several background shader calls
OSL::PerThreadInfo *thread_info = shadingsys->create_thread_info();
ShadingContext *ctx = shadingsys->get_context (thread_info);
// build importance table to optimize background sampling
background.prepare(backgroundResolution, eval_background, ctx);
// release context
shadingsys->release_context (ctx);
shadingsys->destroy_thread_info(thread_info);
} else {
// we aren't directly evaluating the background
backgroundResolution = 0;
}
double setuptime = timer.lap ();
// Local memory for the pixels
std::vector<Color3> pixels(xres * yres, Color3(0,0,0));
// Make an ImageBuf that wraps it ('pixels' still owns the memory)
ImageBuf pixelbuf (ImageSpec(xres, yres, 3, TypeDesc::FLOAT), pixels.data());
// Create shared counter to iterate over one scanline at a time
Counter scanline_counter(errhandler, yres, "Rendering");
// launch a scanline worker for each thread
OIIO::thread_group workers;
for (int i = 0; i < num_threads; i++)
workers.add_thread(new std::thread (scanline_worker, std::ref(scanline_counter), std::ref(pixels)));
workers.join_all();
double runtime = timer.lap();
// Write image to disk
if (Strutil::iends_with (imagefile, ".jpg") ||
Strutil::iends_with (imagefile, ".jpeg") ||
Strutil::iends_with (imagefile, ".gif") ||
Strutil::iends_with (imagefile, ".png")) {
// JPEG, GIF, and PNG images should be automatically saved as sRGB
// because they are almost certainly supposed to be displayed on web
// pages.
ImageBufAlgo::colorconvert (pixelbuf, pixelbuf,
"linear", "sRGB", false, "", "");
}
pixelbuf.set_write_format (TypeDesc::HALF);
if (! pixelbuf.write (imagefile))
errhandler.error ("Unable to write output image: %s",
pixelbuf.geterror().c_str());
// Print some debugging info
if (debug1 || runstats || profile) {
double writetime = timer.lap();
std::cout << "\n";
std::cout << "Setup: " << OIIO::Strutil::timeintervalformat (setuptime,2) << "\n";
std::cout << "Run : " << OIIO::Strutil::timeintervalformat (runtime,2) << "\n";
std::cout << "Write: " << OIIO::Strutil::timeintervalformat (writetime,2) << "\n";
std::cout << "\n";
std::cout << shadingsys->getstats (5) << "\n";
OIIO::TextureSystem *texturesys = shadingsys->texturesys();
if (texturesys)
std::cout << texturesys->getstats (5) << "\n";
std::cout << ustring::getstats() << "\n";
}
// We're done with the shading system now, destroy it
shaders.clear (); // Must release the group refs first
delete shadingsys;
return EXIT_SUCCESS;
}
| 41.362869 | 142 | 0.586385 | [
"mesh",
"geometry",
"render",
"object",
"vector"
] |
33f33c176eac069e311fc916bc9be3e315ea8c1b | 587 | cpp | C++ | openjudge/04/01/1999.cpp | TheBadZhang/OJ | b5407f2483aa630068343b412ecaf3a9e3303f7e | [
"Apache-2.0"
] | 1 | 2020-07-22T16:54:07.000Z | 2020-07-22T16:54:07.000Z | openjudge/04/01/1999.cpp | TheBadZhang/OJ | b5407f2483aa630068343b412ecaf3a9e3303f7e | [
"Apache-2.0"
] | 1 | 2018-05-12T12:53:06.000Z | 2018-05-12T12:53:06.000Z | openjudge/04/01/1999.cpp | TheBadZhang/OJ | b5407f2483aa630068343b412ecaf3a9e3303f7e | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
int main () {
struct LOG {
std::string s[4];
} t;
std::string f;
std::vector <LOG> log;
int d = 0;
while (std::cin >> f) {
t.s [d++] = f;
if (d % 4 == 0) log.push_back (t);
}
std::sort (log.begin (), log.end (), [](LOG a, LOG b){
if (a.s [3] > b.s [3] || a.s [2] < b.s[2]) {
return true;
} else return false;
});
for (auto s : log) {
std::cout << s.s [0] << s.s [1] << s.s [2] << s.s [3] << std::endl;
}
return 0;
} | 20.241379 | 75 | 0.422487 | [
"vector"
] |
33f605d893dfd1921852a7eb1572c1febc6beb64 | 2,610 | cpp | C++ | tests/cpp/test_runtime_thread_safety.cpp | p1x31/TRTorch | f99a6ca763eb08982e8b7172eb948a090bcbf11c | [
"BSD-3-Clause"
] | 944 | 2020-03-13T22:50:32.000Z | 2021-11-09T05:39:28.000Z | tests/cpp/test_runtime_thread_safety.cpp | p1x31/TRTorch | f99a6ca763eb08982e8b7172eb948a090bcbf11c | [
"BSD-3-Clause"
] | 434 | 2020-03-18T03:00:29.000Z | 2021-11-09T00:26:36.000Z | tests/cpp/test_runtime_thread_safety.cpp | p1x31/TRTorch | f99a6ca763eb08982e8b7172eb948a090bcbf11c | [
"BSD-3-Clause"
] | 106 | 2020-03-18T02:20:21.000Z | 2021-11-08T18:58:58.000Z | #include <string>
#include <thread>
#include "gtest/gtest.h"
#include "tests/util/util.h"
#include "torch/script.h"
#include "trtorch/trtorch.h"
void run_infer(
int thread_id,
torch::jit::Module& mod,
torch::jit::Module& trt_mod,
const std::vector<torch::jit::IValue> inputs,
const std::vector<torch::jit::IValue> inputs_trt,
std::vector<torch::jit::IValue>& out_vec,
std::vector<torch::jit::IValue>& trt_out_vec) {
int count = 10;
while (count-- > 0) {
out_vec[thread_id] = mod.forward(inputs);
trt_out_vec[thread_id] = trt_mod.forward(inputs_trt);
}
}
TEST(CppAPITests, RuntimeThreadSafety) {
std::string path = "tests/modules/resnet50_traced.jit.pt";
torch::jit::Module mod;
try {
// Deserialize the ScriptModule from a file using torch::jit::load().
mod = torch::jit::load(path);
} catch (const c10::Error& e) {
std::cerr << "error loading the model\n";
}
mod.eval();
mod.to(torch::kCUDA);
torch::Tensor in_jit = at::randint(5, {1, 3, 224, 224}, torch::kCUDA).to(torch::kFloat);
torch::Tensor in_trt = in_jit.clone().to(torch::kFloat);
std::vector<torch::jit::IValue> inputs_jit;
std::vector<torch::jit::IValue> inputs_trt;
inputs_jit.push_back(in_jit.clone());
inputs_trt.push_back(in_trt.clone());
std::vector<trtorch::CompileSpec::Input> input_ranges;
for (auto in : inputs_trt) {
input_ranges.push_back({std::vector<int64_t>{1, 3, 224, 224},
std::vector<int64_t>{1, 3, 224, 224},
std::vector<int64_t>{16, 3, 224, 224},
torch::kFloat});
}
auto compile_settings = trtorch::CompileSpec(input_ranges);
// FP32 execution
compile_settings.enabled_precisions = {torch::kFloat};
compile_settings.strict_types = true;
auto trt_mod = trtorch::CompileGraph(mod, compile_settings);
std::cout << "trtorch::CompileGraph" << std::endl;
int num_threads = 10;
std::vector<torch::jit::IValue> out_vec(num_threads), trt_out_vec(num_threads);
std::vector<std::thread> threads;
for (int i = 0; i < num_threads; i++) {
threads.push_back(std::thread(
run_infer,
i,
std::ref(mod),
std::ref(trt_mod),
inputs_jit,
inputs_trt,
std::ref(out_vec),
std::ref(trt_out_vec)));
}
for (int i = 0; i < num_threads; i++) {
threads[i].join();
}
bool flag = true;
for (int i = 0; i < num_threads; i++) {
bool f = trtorch::tests::util::almostEqual(out_vec[i].toTensor(), trt_out_vec[i].toTensor(), 1e-2);
flag = flag && f;
}
ASSERT_TRUE(flag);
} | 31.445783 | 103 | 0.631801 | [
"vector",
"model"
] |
33fb88ab231db08fdecb760ed2b9b1cb23125072 | 1,540 | hxx | C++ | Modules/Core/Common/include/otbCommandProgressUpdate.hxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/Core/Common/include/otbCommandProgressUpdate.hxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/Core/Common/include/otbCommandProgressUpdate.hxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 otbCommandProgressUpdate_hxx
#define otbCommandProgressUpdate_hxx
#include "otbCommandProgressUpdate.h"
namespace otb
{
template <class TFilter>
void CommandProgressUpdate<TFilter>::Execute(itk::Object* caller, const itk::EventObject& event)
{
Execute((const itk::Object*)caller, event);
}
template <class TFilter>
void CommandProgressUpdate<TFilter>::Execute(const itk::Object* object, const itk::EventObject& event)
{
FilterPointer filter = dynamic_cast<FilterPointer>(object);
if (typeid(event) != typeid(itk::ProgressEvent))
{
return;
}
int factor = 160;
int val = int(filter->GetProgress() * factor);
if ((val % 2) == 0)
{
std::cout << "|";
std::cout.flush();
}
if (val == factor)
{
std::cout << ">";
std::cout.flush();
}
}
} // end namespace otb
#endif
| 24.0625 | 102 | 0.698052 | [
"object"
] |
33ffcd3f035112e20f7090750c1f26db925b1133 | 2,448 | cpp | C++ | examples/ble_nus/main.cpp | amoghaddassi/SimpleDBus | 4b6aca45ae4948b54337a386f3b5d57c51699684 | [
"MIT"
] | 5 | 2020-07-16T02:53:50.000Z | 2021-09-08T22:25:15.000Z | examples/ble_nus/main.cpp | amoghaddassi/SimpleDBus | 4b6aca45ae4948b54337a386f3b5d57c51699684 | [
"MIT"
] | 5 | 2021-01-03T18:07:47.000Z | 2021-02-04T06:37:42.000Z | examples/ble_nus/main.cpp | amoghaddassi/SimpleDBus | 4b6aca45ae4948b54337a386f3b5d57c51699684 | [
"MIT"
] | 3 | 2021-02-03T15:59:19.000Z | 2021-08-31T01:52:05.000Z | #include "bluezdbus/BluezService.h"
#include <stdlib.h>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <thread>
BluezService bluez_service;
volatile bool async_thread_active = true;
void async_thread_function() {
while (async_thread_active) {
bluez_service.run_async();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void millisecond_delay(int ms) {
for (int i = 0; i < ms; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
/**
* This is a minimal example in which we exchange some data
* with a device exposing the Nordic UART service.
*/
int main(int argc, char* argv[]) {
std::string mac_address = argv[1];
bluez_service.init();
std::thread* async_thread = new std::thread(async_thread_function);
auto adapter = bluez_service.get_first_adapter();
if (adapter == nullptr) {
std::cout << "No adapter found!" << std::endl;
return -1;
}
adapter->discovery_filter_transport_set("le");
adapter->StartDiscovery();
millisecond_delay(5000);
adapter->StopDiscovery();
auto device = adapter->get_device(mac_address);
if (device != nullptr) {
device->Connect();
// In theory, we should wait for the OnConnect event.
millisecond_delay(1000);
auto characteristic_tx = device->get_characteristic("6e400001-b5a3-f393-e0a9-e50e24dcca9e",
"6e400003-b5a3-f393-e0a9-e50e24dcca9e");
auto characteristic_rx = device->get_characteristic("6e400001-b5a3-f393-e0a9-e50e24dcca9e",
"6e400002-b5a3-f393-e0a9-e50e24dcca9e");
if (characteristic_tx != nullptr) {
characteristic_tx->ValueChanged = [&](std::vector<uint8_t> new_value) { /* Data! */ };
characteristic_tx->StartNotify();
}
if (characteristic_rx != nullptr) {
std::string message = "Hello World";
characteristic_rx->write_command((uint8_t*)message.c_str(), message.length());
}
millisecond_delay(2000);
characteristic_tx->StopNotify();
device->Disconnect();
millisecond_delay(1000);
}
async_thread_active = false;
while (!async_thread->joinable()) {
millisecond_delay(10);
}
async_thread->join();
delete async_thread;
return 0;
} | 30.222222 | 100 | 0.620507 | [
"vector"
] |
33ffd4d47186dab8658a8661f1917fa2c5ce657d | 1,114 | cxx | C++ | src/GeomObject.cxx | fermi-lat/geometry | 71a08bdb0caf952566fed8d8aeb62bd264a4bab7 | [
"BSD-3-Clause"
] | null | null | null | src/GeomObject.cxx | fermi-lat/geometry | 71a08bdb0caf952566fed8d8aeb62bd264a4bab7 | [
"BSD-3-Clause"
] | null | null | null | src/GeomObject.cxx | fermi-lat/geometry | 71a08bdb0caf952566fed8d8aeb62bd264a4bab7 | [
"BSD-3-Clause"
] | null | null | null | // $Id: GeomObject.cxx,v 1.3 2002/10/24 16:50:11 kuss Exp $
//
//
#include "geometry/GeomObject.h"
#include "geometry/CoordTransform.h"
#include <typeinfo>
const char* GeomObject::nameOf()const
{
const std::type_info& t1 = typeid(*this);
return t1.name();
}
GeomObject&
GeomObject::move(const Vector& v)
{
return transform(CoordTransform(v));
}
GeomObject& GeomObject::moveX(double s){ return move(Vector(s,0,0));}
GeomObject& GeomObject::moveY(double s){ return move(Vector(0,s,0));}
GeomObject& GeomObject::moveZ(double s){ return move(Vector(0,0,s));}
GeomObject&
GeomObject::rotateX(double theta)
{
CLHEP::HepRotation R;
return transform(R.rotateX(theta));
}
GeomObject &
GeomObject::rotateY(double theta)
{
CLHEP::HepRotation R;
return transform(R.rotateY(theta));
}
GeomObject &
GeomObject::rotateZ(double theta)
{
CLHEP::HepRotation R;
return transform(R.rotateZ(theta));
}
GeomObject &
GeomObject::rotate(double angle, const Vector & axis)
{
CLHEP::HepRotation R;
return transform(R.rotate(angle, axis));
}
void GeomObject::printOn(std::ostream& )const{};
| 18.881356 | 69 | 0.704668 | [
"geometry",
"vector",
"transform"
] |
d500273c56f928be0f6cb11a1bac8c79512bdfc9 | 4,679 | hpp | C++ | unimodularity-library-1.2c/src/gen_network.hpp | vios-fish/CompetitiveProgramming | 6953f024e4769791225c57ed852cb5efc03eb94b | [
"MIT"
] | 2 | 2016-07-05T21:14:40.000Z | 2020-03-08T01:33:12.000Z | src/gen_network.hpp | vbraun/unimodularity-library | d329571908a84ed98713721a2fe873ad534901c8 | [
"BSL-1.0"
] | null | null | null | src/gen_network.hpp | vbraun/unimodularity-library | d329571908a84ed98713721a2fe873ad534901c8 | [
"BSL-1.0"
] | null | null | null | /**
* Copyright Matthias Walter 2010.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
**/
#ifndef GEN_NETWORK_HPP_
#define GEN_NETWORK_HPP_
#include "gen_generic.hpp"
#include "matrix.hpp"
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/two_bit_color_map.hpp>
template <typename OutputIterator, typename Graph, typename IndexMap, typename Vertex>
OutputIterator find_path(Graph graph, IndexMap index_map, Vertex s, Vertex t, OutputIterator result)
{
if (s == t)
{
*result++ = s;
return result;
}
typedef boost::graph_traits <Graph> graph_traits_t;
typedef typename graph_traits_t::vertex_descriptor vertex_t;
/// Define a color map for DFS
typedef boost::two_bit_color_map <> color_map_t;
color_map_t color_map(boost::num_vertices(graph));
/// Declare predecessor map
typedef std::vector <vertex_t> predecessors_t;
typedef boost::iterator_property_map <typename predecessors_t::iterator, IndexMap> predecessor_map_t;
predecessors_t predecessors(boost::num_vertices(graph), graph_traits_t::null_vertex());
predecessor_map_t predecessor_map(predecessors.begin(), index_map);
boost::depth_first_visit(graph, s, boost::make_dfs_visitor(record_predecessors(predecessor_map, boost::on_tree_edge())), color_map);
vertex_t current_vertex = t;
while (current_vertex != s)
{
vertex_t next_vertex = boost::get(predecessor_map, current_vertex);
if (next_vertex == graph_traits_t::null_vertex())
return result;
*result++ = current_vertex;
current_vertex = next_vertex;
}
*result++ = s;
return result;
}
class network_matrix_generator: public matrix_generator
{
public:
network_matrix_generator(size_t height, size_t width, unimod::log_level level) :
matrix_generator("network", height, width, level)
{
}
virtual ~network_matrix_generator()
{
}
template <typename MatrixType>
void generate(MatrixType& matrix)
{
size_t nodes = matrix.size1() + 1;
if (_level != unimod::LOG_QUIET)
std::cerr << "Creating a spanning tree with " << nodes << " nodes..." << std::flush;
/// Create a spanning tree
typedef boost::adjacency_list <boost::vecS, boost::vecS, boost::undirectedS> tree_graph_t;
typedef boost::graph_traits <tree_graph_t> tree_traits_t;
tree_graph_t tree_graph(nodes);
std::vector <tree_traits_t::vertex_descriptor> used_vertices;
tree_traits_t::vertex_iterator vertex_iter, vertex_beyond;
for (boost::tie(vertex_iter, vertex_beyond) = boost::vertices(tree_graph); vertex_iter != vertex_beyond; ++vertex_iter)
{
if (!used_vertices.empty())
{
boost::uniform_int <int> dist(0, used_vertices.size() - 1);
tree_traits_t::vertex_descriptor other = used_vertices[dist(_rng)];
boost::add_edge(*vertex_iter, other, tree_graph);
}
used_vertices.push_back(*vertex_iter);
}
if (_level != unimod::LOG_QUIET)
std::cerr << " done.\nAdding edges and filling matrix..." << std::flush;
for (size_t column = 0; column < _matrix.size2(); ++column)
{
/// Choose an edge not in the tree
boost::uniform_int <int> dist(0, nodes - 1);
tree_traits_t::vertex_descriptor u, v;
do
{
u = boost::vertex(dist(_rng), tree_graph);
v = boost::vertex(dist(_rng), tree_graph);
}
while (u == v || boost::edge(u, v, tree_graph).second);
std::set <tree_traits_t::vertex_descriptor> path_vertices;
find_path(tree_graph, boost::get(boost::vertex_index, tree_graph), u, v, std::inserter(path_vertices, path_vertices.end()));
size_t row = 0;
tree_traits_t::edge_iterator edge_iter, edge_beyond;
for (boost::tie(edge_iter, edge_beyond) = boost::edges(tree_graph); edge_iter != edge_beyond; ++edge_iter)
{
u = boost::source(*edge_iter, tree_graph);
v = boost::target(*edge_iter, tree_graph);
_matrix(row, column) = (path_vertices.find(u) != path_vertices.end() && path_vertices.find(v) != path_vertices.end()) ? 1 : 0;
++row;
}
}
if (_level != unimod::LOG_QUIET)
std::cerr << " done.\nCorrecting the signs..." << std::flush;
sign();
if (_level != unimod::LOG_QUIET)
std::cerr << " done." << std::endl;
}
virtual void generate()
{
if (_height <= _width)
{
generate(_matrix);
}
else
{
unimod::matrix_transposed <unimod::integer_matrix> transposed(_matrix);
generate(transposed);
}
}
};
#endif
| 30.383117 | 134 | 0.679419 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.