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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c09099fd177d51559c83295140b92428345add6f | 1,504 | cc | C++ | pthread/mutex/mutex.cc | uslsteen/parallel_prog | 893d73869e851b59c5503d3bbd9a668230c56ada | [
"MIT"
] | null | null | null | pthread/mutex/mutex.cc | uslsteen/parallel_prog | 893d73869e851b59c5503d3bbd9a668230c56ada | [
"MIT"
] | null | null | null | pthread/mutex/mutex.cc | uslsteen/parallel_prog | 893d73869e851b59c5503d3bbd9a668230c56ada | [
"MIT"
] | null | null | null | #include <algorithm>
#include <iostream>
#include <string>
#include <pthread.h>
#include <vector>
void *thr_mut(void *arg);
inline void usage(char* exec_path) {
std::cout << "USAGE: " << exec_path << " <nthreads>" << std::endl;
}
inline void check_err(int err_code) {
if (!err_code)
return;
std::cerr << "Error was occured: " << err_code;
std::abort();
}
inline uint32_t incr() {
static int32_t id;
return ++id;
}
/* shared data between threads */
double shared_data = 0;
pthread_mutex_t lock_x = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, char** argv) {
if (argc == 2) {
uint32_t nthreads = std::stoi(argv[1]);
std::vector<pthread_t> threads(nthreads);
std::vector<int32_t> thr_id(nthreads);
std::generate(thr_id.begin(), thr_id.end(), incr);
for (auto& id : thr_id)
std::cout << id << " ";
std::cout << std::endl;
for (uint32_t i = 0; i < nthreads; ++i)
check_err(pthread_create(&threads[i], nullptr, thr_mut, (int32_t*)&(thr_id[i])));
for (auto& thr : threads)
check_err(pthread_join(thr, nullptr));
}
else usage(argv[0]);
}
void *thr_mut(void *arg) {
int32_t *data = (int32_t *)arg;
/* get mutex before modifying and printing shared_x */
pthread_mutex_lock(&lock_x);
shared_data += *data;
std::cout << "shared_data = " << shared_data << std::endl;
pthread_mutex_unlock(&lock_x);
pthread_exit(NULL);
} | 25.066667 | 93 | 0.599734 | [
"vector"
] |
6a4fa8706d25f25816d69c2a0b7f1afe60848ef8 | 4,603 | cpp | C++ | automated-tests/src/dali-adaptor/utc-Dali-GifLoading.cpp | vcebollada/dali-adaptor | 5f12750f484173a344eb23a569d398e4532ffcad | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | automated-tests/src/dali-adaptor/utc-Dali-GifLoading.cpp | vcebollada/dali-adaptor | 5f12750f484173a344eb23a569d398e4532ffcad | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | automated-tests/src/dali-adaptor/utc-Dali-GifLoading.cpp | vcebollada/dali-adaptor | 5f12750f484173a344eb23a569d398e4532ffcad | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2017 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <stdlib.h>
#include <dali/dali.h>
#include <dali-test-suite-utils.h>
#include <dali/devel-api/adaptor-framework/gif-loading.h>
using namespace Dali;
namespace
{
// test gif image, resolution: 100*100, 5 frames, delay: 1 second, disposal method: none
static const char* gGif_100_None = TEST_RESOURCE_DIR "/canvas-none.gif";
// test gif image, resolution: 100*100, 5 frames, delay: 1 second, disposal method: none for first frame and previous for the rest
static const char* gGif_100_Prev = TEST_RESOURCE_DIR "/canvas-prev.gif";
// test gif image, resolution: 100*100, 5 frames, delay: 1 second, disposal method: background
static const char* gGif_100_Bgnd = TEST_RESOURCE_DIR "/canvas-bgnd.gif";
// this image if not exist, for negative test
static const char* gGifNonExist = "non-exist.gif";
void VerifyLoad( std::vector<Dali::PixelData>& pixelDataList, Dali::Vector<uint32_t>& frameDelayList,
uint32_t frameCount, uint32_t width, uint32_t height, uint32_t delay )
{
DALI_TEST_EQUALS( pixelDataList.size(), frameCount, TEST_LOCATION );
DALI_TEST_EQUALS( frameDelayList.Size(), frameCount, TEST_LOCATION );
for( uint32_t idx = 0; idx<frameCount; idx++ )
{
// Check the image size and delay of each frame
DALI_TEST_EQUALS( pixelDataList[idx].GetWidth(), width, TEST_LOCATION );
DALI_TEST_EQUALS( pixelDataList[idx].GetHeight(), height, TEST_LOCATION );
DALI_TEST_EQUALS( frameDelayList[idx], delay, TEST_LOCATION );
}
}
}
void utc_dali_gif_loader_startup(void)
{
test_return_value = TET_UNDEF;
}
void utc_dali_gif_loader_cleanup(void)
{
test_return_value = TET_PASS;
}
int UtcDaliGifLoadingP(void)
{
std::vector<Dali::PixelData> pixelDataList;
Dali::Vector<uint32_t> frameDelayList;
std::unique_ptr<Dali::GifLoading> gifLoading = GifLoading::New( gGif_100_None, true );
bool succeed = gifLoading->LoadAllFrames( pixelDataList, frameDelayList );
// Check that the loading succeed
DALI_TEST_CHECK( succeed );
VerifyLoad( pixelDataList, frameDelayList, 5u, 100u, 100u, 1000u );
pixelDataList.clear();
gifLoading = GifLoading::New( gGif_100_Prev, true );
succeed = gifLoading->LoadAllFrames( pixelDataList, frameDelayList );
// Check that the loading succeed
DALI_TEST_CHECK( succeed );
VerifyLoad( pixelDataList, frameDelayList, 5u, 100u, 100u, 1000u );
pixelDataList.clear();
gifLoading = GifLoading::New( gGif_100_Bgnd, true );
succeed = gifLoading->LoadAllFrames( pixelDataList, frameDelayList );
// Check that the loading succeed
DALI_TEST_CHECK( succeed );
VerifyLoad( pixelDataList, frameDelayList, 5u, 100u, 100u, 1000u );
END_TEST;
}
int UtcDaliGifLoadingN(void)
{
std::vector<Dali::PixelData> pixelDataList;
Dali::Vector<uint32_t> frameDelayList;
std::unique_ptr<Dali::GifLoading> gifLoading = GifLoading::New( gGifNonExist, true );
bool succeed = gifLoading->LoadAllFrames( pixelDataList, frameDelayList );
// Check that the loading failed
DALI_TEST_CHECK( !succeed );
// Check that both pixelDataList and frameDelayList are empty
DALI_TEST_EQUALS( pixelDataList.size(), 0u, TEST_LOCATION );
DALI_TEST_EQUALS( frameDelayList.Size(), 0u, TEST_LOCATION );
END_TEST;
}
int UtcDaliGifLoadingGetImageSizeP(void)
{
std::unique_ptr<Dali::GifLoading> gifLoading = GifLoading::New( gGif_100_None, true );
ImageDimensions imageSize = gifLoading->GetImageSize();
// Check that the image size is [100, 100]
DALI_TEST_EQUALS( imageSize.GetWidth(), 100u, TEST_LOCATION );
DALI_TEST_EQUALS( imageSize.GetHeight(), 100u, TEST_LOCATION );
END_TEST;
}
int UtcDaliGifLoadingGetImageSizeN(void)
{
std::unique_ptr<Dali::GifLoading> gifLoading = GifLoading::New( gGifNonExist, true );
ImageDimensions imageSize = gifLoading->GetImageSize();
// Check that it returns zero size when the gif is not valid
DALI_TEST_EQUALS( imageSize.GetWidth(), 0u, TEST_LOCATION );
DALI_TEST_EQUALS( imageSize.GetHeight(), 0u, TEST_LOCATION );
END_TEST;
}
| 34.350746 | 130 | 0.747339 | [
"vector"
] |
6a51639f21059189431acc2983d4d18df008eea7 | 10,025 | cpp | C++ | ANode/test/TestRepeatWithTimeDependencies.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | ANode/test/TestRepeatWithTimeDependencies.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | ANode/test/TestRepeatWithTimeDependencies.cpp | mpartio/ecflow | ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6 | [
"Apache-2.0"
] | null | null | null | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name :
// Author : Avi
// Revision : $Revision: #14 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
#include <iostream>
#include <boost/test/unit_test.hpp>
#include "Task.hpp"
#include "Family.hpp"
#include "Suite.hpp"
#include "Defs.hpp"
#include "Jobs.hpp"
#include "JobsParam.hpp"
#include "CalendarUpdateParams.hpp"
//#include "PrintStyle.hpp"
using namespace std;
using namespace ecf;
using namespace boost::posix_time;
using namespace boost::gregorian;
BOOST_AUTO_TEST_SUITE( NodeTestSuite )
BOOST_AUTO_TEST_CASE( test_repeat_day_time_combination_in_hierarchy )
{
cout << "ANode:: ...test_repeat_day_time_combination_in_hierarchy \n";
// Create the suite, starting on a sunday
// suite s1
// family f
// repeat integer rep 0 1
// family f1
// day monday
// task t1
// time 10:00 # should run, monday at 10:00 twice, due to repeat
// time 11:00 # should run, monday at 11:00 twice, due to repeat
Defs defs;
suite_ptr suite = defs.add_suite("s1");
boost::posix_time::ptime the_time = boost::posix_time::ptime(date(2019,8,4),time_duration(0,0,0)); //sunday
suite->addClock( ClockAttr(the_time) );
family_ptr f = suite->add_family("f");
family_ptr f1 = f->add_family("f1");
f1->addRepeat(RepeatInteger("rep",0,1,1));
f1->addDay( DayAttr(DayAttr::MONDAY) );
task_ptr t1 = f1->add_task("t1");
t1->addTime( ecf::TimeAttr(ecf::TimeSlot(10,0)) );
t1->addTime( ecf::TimeAttr(ecf::TimeSlot(11,0)) );
defs.beginAll();
CalendarUpdateParams calUpdateParams( hours(1) );
boost::posix_time::ptime expected_time1 = boost::posix_time::ptime(date(2019,8,5),time_duration(10,0,0)); // Monday & 10
boost::posix_time::ptime expected_time2 = boost::posix_time::ptime(date(2019,8,5),time_duration(11,0,0)); // Monday & 11
boost::posix_time::ptime expected_time3 = boost::posix_time::ptime(date(2019,8,12),time_duration(10,0,0)); // Monday & 10
boost::posix_time::ptime expected_time4 = boost::posix_time::ptime(date(2019,8,12),time_duration(11,0,0)); // Monday & 11
//cout << defs << "\n";
int submitted = 0;
for(int m=1; m < 212; m++) { // run for 9 days
//const std::vector<DayAttr>& days = f1->days();
//const std::vector<ecf::TimeAttr>& times = t1->timeVec();
//cout << "Suite time " << suite->calendar().suiteTime() << " dayChanged:" << suite->calendar().dayChanged() << " " << days[0].dump() << " " << times[0].dump() << " rep: " << f1->repeat().value() << "\n";
Jobs jobs(&defs);
JobsParam jobsParam;
jobs.generate(jobsParam);
if (jobsParam.submitted().size() ) {
submitted++;
//cout << " submitted at " << suite->calendar().suiteTime() << " " << days[0].dump() << " " << times[0].dump() << "\n";
// 1st Run: Monday at 10:00 am
if ( submitted == 1)
BOOST_CHECK_MESSAGE( suite->calendar().suiteTime() == expected_time1,"\nExpected to submit at " << expected_time1 << " only, but also found " << suite->calendar().suiteTime());
// 2nd Run: Monday at 11:00 am
if ( submitted == 2)
BOOST_CHECK_MESSAGE( suite->calendar().suiteTime() == expected_time2,"\nExpected to submit at " << expected_time2 << " only, but also found " << suite->calendar().suiteTime());
// 3rd Run: Monday at 10:00 am
if ( submitted == 3)
BOOST_CHECK_MESSAGE( suite->calendar().suiteTime() == expected_time3,"\nExpected to submit at " << expected_time3 << " only, but also found " << suite->calendar().suiteTime());
// 4th Run: Monday at 11:00 am
if ( submitted == 4)
BOOST_CHECK_MESSAGE( suite->calendar().suiteTime() == expected_time4,"\nExpected to submit at " << expected_time4 << " only, but also found " << suite->calendar().suiteTime());
t1->set_state(NState::COMPLETE); // cause repeat to loop
//cout << " set_complete t1 at " << suite->calendar().suiteTime() << " " << days[0].dump() << " " << times[0].dump() << "\n";
}
defs.updateCalendar(calUpdateParams);
}
BOOST_CHECK_MESSAGE( submitted == 4,"Expected four submission but found " << submitted);
}
BOOST_AUTO_TEST_CASE( test_repeat_time_day_combination_in_hierarchy )
{
cout << "ANode:: ...test_repeat_time_day_combination_in_hierarchy \n";
// Create the suite, starting on a sunday
// suite s1
// family f
// repeat integer rep 0 1
// family f1
// time 10:00 # should run, 2 on monday at midnight, the time has NO effect
// task t1
// day monday
Defs defs;
suite_ptr suite = defs.add_suite("s1");
boost::posix_time::ptime the_time = boost::posix_time::ptime(date(2019,8,4),time_duration(0,0,0)); //sunday
suite->addClock( ClockAttr(the_time) );
family_ptr f = suite->add_family("f");
family_ptr f1 = f->add_family("f1");
f1->addRepeat(RepeatInteger("rep",0,3,1)); // four iteration
f1->addTime( ecf::TimeAttr(ecf::TimeSlot(10,0)) );
task_ptr t1 = f1->add_task("t1");
t1->addDay( DayAttr(DayAttr::MONDAY) );
defs.beginAll();
CalendarUpdateParams calUpdateParams( hours(1) );
boost::posix_time::ptime expected_time1 = boost::posix_time::ptime(date(2019,8,5),time_duration(0,0,0)); // Monday & 00:00
boost::posix_time::ptime expected_time3 = boost::posix_time::ptime(date(2019,8,12),time_duration(0,0,0)); // Monday & 00:00
//cout << defs << "\n";
int submitted = 0;
for(int m=1; m < 212; m++) { // run for 9 days
//const std::vector<DayAttr>& days = t1->days();
//const std::vector<ecf::TimeAttr>& times = f1->timeVec();
//cout << "Suite time " << suite->calendar().suiteTime() << " dayChanged:" << suite->calendar().dayChanged() << " " << days[0].dump() << " " << times[0].dump() << " rep: " << f1->repeat().value() << "\n";
Jobs jobs(&defs);
JobsParam jobsParam;
jobs.generate(jobsParam);
if (jobsParam.submitted().size() ) {
submitted++;
//cout << " submitted at " << suite->calendar().suiteTime() << " " << days[0].dump() << " " << times[0].dump() << "\n";
// 1st Run: Monday at 00:00 am
if ( submitted == 1)
BOOST_CHECK_MESSAGE( suite->calendar().suiteTime() == expected_time1,"\nExpected to submit at " << expected_time1 << " only, but also found " << suite->calendar().suiteTime());
// 1st Run: Monday at 00:00 am
if ( submitted == 2)
BOOST_CHECK_MESSAGE( suite->calendar().suiteTime() == expected_time3,"\nExpected to submit at " << expected_time3 << " only, but also found " << suite->calendar().suiteTime());
t1->set_state(NState::COMPLETE); // cause repeat to loop
//cout << " set_complete t1 at " << suite->calendar().suiteTime() << " " << days[0].dump() << " " << times[0].dump() << "\n";
//PrintStyle style(PrintStyle::MIGRATE);
//cout << defs << "\n";
}
defs.updateCalendar(calUpdateParams);
}
BOOST_CHECK_MESSAGE( submitted == 2,"Expected two submission but found " << submitted);
}
BOOST_AUTO_TEST_CASE( test_repeat_with_impossible_day_combination_in_hierarchy )
{
cout << "ANode:: ...test_repeat_with_impossible_day_combination_in_hierarchy\n";
// Create the suite, starting on a sunday
// suite s1
// clock real 04.08.2019 # Sunday
// family f
// repeat integer rep 0 1
// family f1
// day monday
// task t1
// day tuesday # cant be free on Monday and Tuesday,
// time 10:00
// verify complete:1
Defs defs;
suite_ptr suite = defs.add_suite("s1");
suite->addClock( ClockAttr( boost::posix_time::ptime(date(2019,8,4),time_duration(0,0,0)) ) );//sunday
family_ptr f = suite->add_family("f");
family_ptr f1 = f->add_family("f1");
f1->addRepeat(RepeatInteger("rep",0,1,1)); // 2 iteration
f1->addDay( DayAttr(DayAttr::MONDAY) );
task_ptr t1 = f1->add_task("t1");
t1->addDay( DayAttr(DayAttr::TUESDAY) );
t1->addTime( ecf::TimeAttr(ecf::TimeSlot(10,0)) );
defs.beginAll();
CalendarUpdateParams calUpdateParams( hours(1) );
//cout << defs << "\n";
int submitted = 0;
for(int m=1; m < 212; m++) { // run for 9 days
//const std::vector<DayAttr>& fdays = f1->days();
//const std::vector<DayAttr>& days = t1->days();
//const std::vector<ecf::TimeAttr>& times = t1->timeVec();
//cout << "Suite time " << suite->calendar().suiteTime() << " dayChanged:" << suite->calendar().dayChanged() << "\n "
// << fdays[0].dump() << " " << days[0].dump() << " " << times[0].dump() << " rep: " << f1->repeat().value() << "\n";
Jobs jobs(&defs);
JobsParam jobsParam;
jobs.generate(jobsParam);
if (jobsParam.submitted().size() ) {
submitted++;
//cout << " submitted at " << suite->calendar().suiteTime() << " dayChanged:" << suite->calendar().dayChanged() << "\n "
// << fdays[0].dump() << " " << days[0].dump() << " " << times[0].dump() << " rep: " << f1->repeat().value() << "\n";
t1->set_state(NState::COMPLETE); // cause repeat to loop
//PrintStyle style(PrintStyle::MIGRATE);
//cout << defs << "\n";
}
defs.updateCalendar(calUpdateParams);
}
BOOST_CHECK_MESSAGE( submitted == 0 ,"Expected 0 submission but found " << submitted);
}
BOOST_AUTO_TEST_SUITE_END()
| 43.969298 | 210 | 0.599002 | [
"vector"
] |
6a51692448f86c080c8d5dd4564c8b9bc0378de7 | 9,669 | hpp | C++ | libraries/wallet/include/bts/wallet/wallet_impl.hpp | larkx/LarkX | 8e803d16f31431e8389e772d0e6aab0d474bc9ca | [
"Zlib",
"Unlicense",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause-Clear",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libraries/wallet/include/bts/wallet/wallet_impl.hpp | larkx/LarkX | 8e803d16f31431e8389e772d0e6aab0d474bc9ca | [
"Zlib",
"Unlicense",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause-Clear",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libraries/wallet/include/bts/wallet/wallet_impl.hpp | larkx/LarkX | 8e803d16f31431e8389e772d0e6aab0d474bc9ca | [
"Zlib",
"Unlicense",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause-Clear",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <bts/wallet/wallet_db.hpp>
#include <bts/blockchain/account_operations.hpp>
#include <bts/blockchain/asset_operations.hpp>
#include <bts/blockchain/balance_operations.hpp>
#include <bts/blockchain/market_operations.hpp>
namespace bts { namespace wallet { namespace detail {
class wallet_impl : public chain_observer
{
public:
wallet* self = nullptr;
bool _is_enabled = true;
wallet_db _wallet_db;
chain_database_ptr _blockchain;
path _data_directory;
path _current_wallet_path;
fc::sha512 _wallet_password;
fc::optional<fc::time_point> _scheduled_lock_time;
fc::future<void> _relocker_done;
fc::future<void> _scan_in_progress;
unsigned _num_scanner_threads = 1;
vector<std::unique_ptr<fc::thread>> _scanner_threads;
float _scan_progress = 0;
struct login_record
{
private_key_type key;
fc::time_point_sec insertion_time;
};
std::map<public_key_type, login_record> _login_map;
fc::future<void> _login_map_cleaner_done;
const static short _login_cleaner_interval_seconds = 60;
const static short _login_lifetime_seconds = 300;
vector<function<void( void )>> _unlocked_upgrade_tasks;
wallet_impl();
~wallet_impl();
void create_file( const path& wallet_file_name,
const string& password,
const string& brainkey = string() );
void open_file( const path& wallet_filename );
void reschedule_relocker();
void relocker();
private_key_type create_one_time_key();
/**
* This method is called anytime the blockchain state changes including
* undo operations.
*/
virtual void state_changed( const pending_chain_state_ptr& state )override;
/**
* This method is called anytime a block is applied to the chain.
*/
virtual void block_applied( const block_summary& summary )override;
void scan_market_transaction(
const market_transaction& mtrx,
uint32_t block_num,
const time_point_sec& block_time,
const time_point_sec& received_time
);
secret_hash_type get_secret( uint32_t block_num,
const private_key_type& delegate_key )const;
void scan_state();
void scan_block( uint32_t block_num, const vector<private_key_type>& keys, const time_point_sec& received_time );
wallet_transaction_record scan_transaction(
const signed_transaction& transaction,
uint32_t block_num,
const time_point_sec& block_timestamp,
const vector<private_key_type>& keys,
const time_point_sec& received_time,
bool overwrite_existing = false
);
void scan_genesis_experimental( const account_balance_record_summary_type& account_balances );
void scan_block_experimental( uint32_t block_num,
const map<private_key_type, string>& account_keys,
const map<address, string>& account_balances,
const set<string>& account_names );
transaction_ledger_entry scan_transaction_experimental( const transaction_evaluation_state& eval_state,
uint32_t block_num,
const time_point_sec& timestamp,
bool overwrite_existing );
transaction_ledger_entry scan_transaction_experimental( const transaction_evaluation_state& eval_state,
uint32_t block_num,
const time_point_sec& timestamp,
const map<private_key_type, string>& account_keys,
const map<address, string>& account_balances,
const set<string>& account_names,
bool overwrite_existing );
void scan_transaction_experimental( const transaction_evaluation_state& eval_state,
const map<private_key_type, string>& account_keys,
const map<address, string>& account_balances,
const set<string>& account_names,
transaction_ledger_entry& record,
bool store_record );
void scan_claim( const claim_operation& op, asset& total_fee )const;
bool scan_withdraw( const withdraw_operation& op, wallet_transaction_record& trx_rec, asset& total_fee, public_key_type& from_pub_key );
bool scan_withdraw_pay( const withdraw_pay_operation& op, wallet_transaction_record& trx_rec, asset& total_fee );
bool scan_deposit( const deposit_operation& op, const vector<private_key_type>& keys, wallet_transaction_record& trx_rec, asset& total_fee );
bool scan_register_account( const register_account_operation& op, wallet_transaction_record& trx_rec );
bool scan_update_account( const update_account_operation& op, wallet_transaction_record& trx_rec );
#ifndef PTS_SUPPRESS_ASSETS
bool scan_create_asset( const create_asset_operation& op, wallet_transaction_record& trx_rec );
bool scan_issue_asset( const issue_asset_operation& op, wallet_transaction_record& trx_rec );
#endif
bool scan_update_feed(const update_feed_operation& op, wallet_transaction_record& trx_rec );
bool scan_bid( const bid_operation& op, wallet_transaction_record& trx_rec, asset& total_fee );
bool scan_ask( const ask_operation& op, wallet_transaction_record& trx_rec, asset& total_fee );
bool scan_short( const short_operation& op, wallet_transaction_record& trx_rec, asset& total_fee );
bool scan_burn( const burn_operation& op, wallet_transaction_record& trx_rec, asset& total_fee );
void sync_balance_with_blockchain( const balance_id_type& balance_id, const obalance_record& record, const bool sync = true );
void sync_balance_with_blockchain( const balance_id_type& balance_id );
vector<wallet_transaction_record> get_pending_transactions()const;
void scan_balances();
void scan_registered_accounts();
void withdraw_to_transaction( const asset& amount_to_withdraw,
const string& from_account_name,
signed_transaction& trx,
unordered_set<address>& required_signatures );
const asset claim_to_transaction( const bts::blockchain::account_record& recipient,
const pts_address &source,
const fc::ecc::compact_signature signature,
signed_transaction& trx,
unordered_set<address>& required_signatures );
void authorize_update( unordered_set<address>& required_signatures, oaccount_record account, bool need_owner_key = false );
void scan_chain_task( uint32_t start, uint32_t end, bool fast_scan );
void login_map_cleaner_task();
void upgrade_version();
void upgrade_version_unlocked();
delegate_slate select_delegate_vote( vote_selection_method selection = vote_random );
slate_id_type select_slate( signed_transaction& transaction, const asset_id_type& deposit_asset_id = asset_id_type( 0 ), vote_selection_method = vote_random );
bool is_receive_account( const string& account_name )const;
bool is_valid_account( const string& account_name )const;
bool is_unique_account( const string& account_name )const;
address get_new_address( const string& account_name );
public_key_type get_new_public_key( const string& account_name );
void sign_transaction( signed_transaction& transaction, const unordered_set<address>& required_signatures )const;
void cache_transaction( const signed_transaction& transaction, wallet_transaction_record& record, bool apply_transaction = true );
transaction_ledger_entry apply_transaction_experimental( const signed_transaction& transaction );
void apply_order_to_builder(order_type_enum order_type,
transaction_builder_ptr builder,
const string& account_name,
const string& balance,
const string& order_price,
const string& base_symbol,
const string& quote_symbol,
const string& short_price_limit = string()
);
};
} } } // bts::wallet::detail
| 50.623037 | 165 | 0.596959 | [
"vector"
] |
6a55958efa0884513e6803e93d26aaf03d8ca9fd | 507 | cpp | C++ | topics/graphs/graph/graph.cpp | formatkaka/dsalgo | a7c7386c5c161e23bc94456f93cadd0f91f102fa | [
"Unlicense"
] | null | null | null | topics/graphs/graph/graph.cpp | formatkaka/dsalgo | a7c7386c5c161e23bc94456f93cadd0f91f102fa | [
"Unlicense"
] | null | null | null | topics/graphs/graph/graph.cpp | formatkaka/dsalgo | a7c7386c5c161e23bc94456f93cadd0f91f102fa | [
"Unlicense"
] | null | null | null | //
// Created by Siddhant on 2019-11-22.
//
#include "graph.h"
#include "iostream"
#include "vector"
#include "string"
#include "list"
using namespace std;
int main() {
graph<int> g(2, 1);
g.addEdge(0, 1);
// g.addEdge(0,1);
// g.addEdge(2,2);
// g.addEdge(4,0);
// g.addEdge(0,1);
// g.isdag();
vector<int> k = g.gettopsort();
cout << "topsort : " << endl;
for (int i = 0; i < k.size(); ++i) {
cout << k[i] << ", ";
}
// g.bfs(1);
return 0;
} | 14.485714 | 40 | 0.497041 | [
"vector"
] |
6a55ebd5c550de9c8bb08cb0d0914f7d3e531cf9 | 2,039 | cpp | C++ | src/core/Utils.cpp | k3a/glfk | 4646be393248092522619bc5ab98eb7f28616ac5 | [
"BSD-3-Clause"
] | null | null | null | src/core/Utils.cpp | k3a/glfk | 4646be393248092522619bc5ab98eb7f28616ac5 | [
"BSD-3-Clause"
] | null | null | null | src/core/Utils.cpp | k3a/glfk | 4646be393248092522619bc5ab98eb7f28616ac5 | [
"BSD-3-Clause"
] | null | null | null | /*-
Minimalistic and Modular OpenGL C++ Framework
GLFK LICENSE (BSD-based) - please see LICENSE.md
-*/
#include "Utils.h"
#include "Renderer.h"
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
std::string ReadFile(const char* path)
{
struct stat st;
FILE* fp;
char* buf;
std::string outBuff;
if ((fp = fopen(path, "rb")) == NULL) {
return "";
}
stat(path, &st);
buf = (char*) malloc(st.st_size);
fread(buf, 1, st.st_size, fp);
fclose(fp);
buf[st.st_size] = '\0';
outBuff = std::string(buf, st.st_size+1);
return outBuff;
}
const char* GLErrorToString(unsigned error)
{
if(error == GL_NO_ERROR) {
return "GL_NO_ERROR: No error has been recorded.";
} else if(error == GL_INVALID_ENUM) {
return "GL_INVALID_ENUM: An unacceptable value is specified for an enumerated argument.";
} else if(error == GL_INVALID_VALUE) {
return "GL_INVALID_VALUE: A numeric argument is out of range.\n";
} else if(error == GL_INVALID_OPERATION) {
return "GL_INVALID_OPERATION: The specified operation is not allowed in the current state.";
} else if(error == GL_OUT_OF_MEMORY) {
return "GL_OUT_OF_MEMORY: There is not enough memory left to execute the command.";
} else if(error == GL_INVALID_FRAMEBUFFER_OPERATION) {
return "GL_INVALID_FRAMEBUFFER_OPERATION: The framebuffer object is not complete.";
} else {
static char buff[32];
sprintf(buff, "0x%X", error);
return buff;
}
}
void PrintGLErrorImpl(const char* where)
{
#ifndef DEBUG
return;
#endif
static GLenum prevError = 0;
static const char* prevErrorWhere = NULL;
GLenum error = glGetError();
if (!error) {
return;
} else if (error == prevError && where == prevErrorWhere) {
return; // don't display the same error more times
}
prevError = error;
prevErrorWhere = where;
printf("GL error during %s: %s\n", where, GLErrorToString(error));
}
| 26.141026 | 100 | 0.635115 | [
"object"
] |
6a59c263d5e3f12260f9e74b7ea6f08d8bfb15a0 | 24,121 | cpp | C++ | nvcommon/nvModel/src/nvModel.cpp | soundsilence/Tracer | 3a71b2afcbd3debc34d601962a80967d8aa1cae0 | [
"MIT"
] | null | null | null | nvcommon/nvModel/src/nvModel.cpp | soundsilence/Tracer | 3a71b2afcbd3debc34d601962a80967d8aa1cae0 | [
"MIT"
] | null | null | null | nvcommon/nvModel/src/nvModel.cpp | soundsilence/Tracer | 3a71b2afcbd3debc34d601962a80967d8aa1cae0 | [
"MIT"
] | null | null | null | //
// nvModel.cpp - Model support class
//
// The nvModel class implements an interface for a multipurpose model
// object. This class is useful for loading and formatting meshes
// for use by OpenGL. It can compute face normals, tangents, and
// adjacency information. The class supports the obj file format.
//
// This file implements the fomat independent part of the code.
//
// Author: Evan Hart
// Email: sdkfeedback@nvidia.com
//
// Copyright (c) NVIDIA Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <set>
#include <map>
#include <algorithm>
#include <string.h>
#include "nvModel.h"
#include <nvMath.h>
//fix for non-standard naming
#ifdef WIN32
#define strcasecmp _stricmp
#endif
using std::vector;
using std::set;
using std::map;
using std::min;
using std::max;
namespace nv {
//////////////////////////////////////////////////////////////////////
//
// Local data structures
//
//////////////////////////////////////////////////////////////////////
//
// Index gathering and ordering structure
////////////////////////////////////////////////////////////
struct IdxSet {
GLuint pIndex;
GLuint nIndex;
GLuint tIndex;
GLuint tanIndex;
GLuint cIndex;
bool operator< ( const IdxSet &rhs) const {
if (pIndex < rhs.pIndex)
return true;
else if (pIndex == rhs.pIndex) {
if (nIndex < rhs.nIndex)
return true;
else if (nIndex == rhs.nIndex) {
if ( tIndex < rhs.tIndex)
return true;
else if ( tIndex == rhs.tIndex) {
if (tanIndex < rhs.tanIndex)
return true;
else if (tanIndex == rhs.tanIndex)
return (cIndex < rhs.cIndex);
}
}
}
return false;
}
};
//
// Edge connectivity structure
////////////////////////////////////////////////////////////
struct Edge {
GLuint pIndex[2]; //position indices
bool operator< (const Edge &rhs) const {
return ( pIndex[0] == rhs.pIndex[0]) ? ( pIndex[1] < rhs.pIndex[1]) : pIndex[0] < rhs.pIndex[0];
}
Edge( GLuint v0, GLuint v1) {
pIndex[0] = std::min( v0, v1);
pIndex[1] = std::max( v0, v1);
}
private:
Edge() {} // disallow the default constructor
};
//////////////////////////////////////////////////////////////////////
//
// Static data
//
//////////////////////////////////////////////////////////////////////
Model::FormatInfo Model::formatTable[] = {
{ "obj", Model::loadObjFromFile }
};
Model* Model::CreateModel() {
return new Model;
}
//
//
////////////////////////////////////////////////////////////
Model::Model() : _posSize(0), _tcSize(0), _cSize(0), _pOffset(-1), _nOffset(-1), _tcOffset(-1), _sTanOffset(-1), _cOffset(-1), _vtxSize(0), _openEdges(0) {
//nv::vec2<float> val;
}
//
//
//////////////////////////////////////////////////////////////////////
Model::~Model() {
//dynamic allocations presently all handled via stl
}
//
//initialize a model from a file
//////////////////////////////////////////////////////////////////////
bool Model::loadModelFromFile( const char* file) {
const char* extension;
extension = strrchr( file, '.');
if (extension)
extension++; //start looking after the .
else
return false; //don't try to place guess the file type
int formatCount = sizeof(Model::formatTable) / sizeof(Model::FormatInfo);
//try to match by format first
for ( int ii = 0; ii < formatCount; ii++) {
if ( ! strcasecmp( formatTable[ii].extension, extension)) {
//extension matches, load it
return formatTable[ii].reader( file, *this);
}
}
return false;
}
//
// compile the model to an acceptable format
//////////////////////////////////////////////////////////////////////
void Model::compileModel( Model::PrimType prim) {
bool needsTriangles = false;
bool needsTrianglesWithAdj = false;
bool needsEdges = false;
bool needsPoints = false;
if ( (prim & Model::eptPoints) == Model::eptPoints)
needsPoints = true;
if ( (prim & Model::eptTriangles) == Model::eptTriangles)
needsTriangles = true;
if ( (prim & Model::eptTrianglesWithAdjacency) == Model::eptTrianglesWithAdjacency) {
needsTriangles = true;
needsTrianglesWithAdj = true;
}
if ( (prim & Model::eptEdges) == Model::eptEdges) {
needsTriangles = true;
needsEdges = true;
}
//merge the points
map<IdxSet, GLuint> pts;
//find whether a position is unique
set<GLuint> ptSet;
{
vector<GLuint>::iterator pit = _pIndex.begin();
vector<GLuint>::iterator nit = _nIndex.begin();
vector<GLuint>::iterator tit = _tIndex.begin();
vector<GLuint>::iterator tanit = _tanIndex.begin();
vector<GLuint>::iterator cit = _cIndex.begin();
while ( pit < _pIndex.end()) {
IdxSet idx;
idx.pIndex = *pit;
if ( _normals.size() > 0)
idx.nIndex = *nit;
else
idx.nIndex = 0;
if ( _tIndex.size() > 0)
idx.tIndex = *tit;
else
idx.tIndex = 0;
if ( _tanIndex.size() > 0)
idx.tanIndex = *tanit;
else
idx.tanIndex = 0;
if ( _cIndex.size() > 0)
idx.cIndex = *cit;
else
idx.cIndex = 0;
map<IdxSet,GLuint>::iterator mit = pts.find(idx);
if (mit == pts.end()) {
if (needsTriangles)
_indices[2].push_back( (GLuint)pts.size());
//since this one is a new vertex, check to see if this position is already referenced
if (needsPoints && ptSet.find(idx.pIndex) != ptSet.end()) {
ptSet.insert( idx.pIndex);
}
pts.insert( map<IdxSet,GLuint>::value_type(idx, (GLuint)pts.size()));
//position
_vertices.push_back( _positions[idx.pIndex*_posSize]);
_vertices.push_back( _positions[idx.pIndex*_posSize + 1]);
_vertices.push_back( _positions[idx.pIndex*_posSize + 2]);
if (_posSize == 4)
_vertices.push_back( _positions[idx.pIndex*_posSize + 3]);
//normal
if (_normals.size() > 0) {
_vertices.push_back( _normals[idx.nIndex*3]);
_vertices.push_back( _normals[idx.nIndex*3 + 1]);
_vertices.push_back( _normals[idx.nIndex*3 + 2]);
}
//texture coordinate
if (_texCoords.size() > 0) {
_vertices.push_back( _texCoords[idx.tIndex*_tcSize]);
_vertices.push_back( _texCoords[idx.tIndex*_tcSize + 1]);
if (_tcSize == 3)
_vertices.push_back( _texCoords[idx.tIndex*_tcSize + 2]);
}
//tangents
if (_sTangents.size() > 0) {
_vertices.push_back( _sTangents[idx.tanIndex*3]);
_vertices.push_back( _sTangents[idx.tanIndex*3 + 1]);
_vertices.push_back( _sTangents[idx.tanIndex*3 + 2]);
}
//colors
if (_colors.size() > 0) {
_vertices.push_back( _colors[idx.cIndex*_cSize]);
_vertices.push_back( _colors[idx.cIndex*_cSize + 1]);
_vertices.push_back( _colors[idx.cIndex*_cSize + 2]);
if (_cSize == 4)
_vertices.push_back( _colors[idx.cIndex*_cSize + 3]);
}
}
else {
if (needsTriangles)
_indices[2].push_back( mit->second);
}
//advance the iterators if the components are present
pit++;
if (hasNormals())
nit++;
if (hasTexCoords())
tit++;
if (hasTangents())
tanit++;
if (hasColors())
cit++;
}
}
//create an edge list, if necessary
if (needsEdges || needsTrianglesWithAdj) {
std::multimap<Edge, GLuint> edges;
//edges are only based on positions only
for (int ii = 0; ii < (int)_pIndex.size(); ii += 3) {
for (int jj = 0; jj < 3; jj++) {
Edge w( _pIndex[ii + jj], _pIndex[ii + (jj +1) % 3]);
std::multimap<Edge, GLuint>::iterator it = edges.find(w);
//if we are storing edges, make sure we store only one copy
if (needsEdges && it == edges.end()) {
_indices[1].push_back( _indices[2][ii+jj]);
_indices[1].push_back( _indices[2][ii + (jj +1) % 3]);
}
edges.insert( std::multimap<Edge, GLuint>::value_type( w, ii / 3));
}
}
//now handle triangles with adjacency
if (needsTrianglesWithAdj) {
for (unsigned int ii = 0; ii < _pIndex.size(); ii += 3) {
for (int jj = 0; jj < 3; jj++) {
Edge w( _pIndex[ii + jj], _pIndex[ii + (jj + 1) % 3]);
std::multimap<Edge, GLuint>::iterator it = edges.lower_bound(w);
std::multimap<Edge, GLuint>::iterator limit = edges.upper_bound(w);
GLuint adjVertex = 0;
while ( it != edges.end() && it->second == ii /3 && it != limit)
it++;
if ( it == edges.end() || it == limit || it->first.pIndex[0] != w.pIndex[0] || it->first.pIndex[1] != w.pIndex[1] ) {
//no adjacent triangle found, duplicate the vertex
adjVertex = _indices[2][ii + jj];
_openEdges++;
}
else {
GLuint triOffset = it->second * 3; //compute the starting index of the triangle
adjVertex = _indices[2][triOffset]; //set the vertex to a default, in case the adjacent triangle it a degenerate
//find the unshared vertex
for ( int kk=0; kk<3; kk++) {
if ( _pIndex[triOffset + kk] != w.pIndex[0] && _pIndex[triOffset + kk] != w.pIndex[1] ) {
adjVertex = _indices[2][triOffset + kk];
break;
}
}
}
//store the vertices for this edge
_indices[3].push_back( _indices[2][ii + jj]);
_indices[3].push_back( adjVertex);
}
}
}
}
//create selected prim
//set the offsets and vertex size
_pOffset = 0; //always first
_vtxSize = _posSize;
if ( hasNormals()) {
_nOffset = _vtxSize;
_vtxSize += 3;
}
else {
_nOffset = -1;
}
if ( hasTexCoords()) {
_tcOffset = _vtxSize;
_vtxSize += _tcSize;
}
else {
_tcOffset = -1;
}
if ( hasTangents()) {
_sTanOffset = _vtxSize;
_vtxSize += 3;
}
else {
_sTanOffset = -1;
}
if ( hasColors()) {
_cOffset = _vtxSize;
_vtxSize += _cSize;
}
else {
_cOffset = -1;
}
}
//
// compute tangents in the S direction
//
//////////////////////////////////////////////////////////////////////
void Model::computeTangents() {
//make sure tangents don't already exist
if ( hasTangents())
return;
//make sure that the model has texcoords
if ( !hasTexCoords())
return;
//alloc memory and initialize to 0
_tanIndex.reserve( _pIndex.size());
_sTangents.resize( (_texCoords.size() / _tcSize) * 3, 0.0f);
// the collision map records any alternate locations for the tangents
std::multimap< GLuint, GLuint> collisionMap;
//process each face, compute the tangent and try to add it
for (int ii = 0; ii < (int)_pIndex.size(); ii += 3) {
vec3f p0(&_positions[_pIndex[ii]*_posSize]);
vec3f p1(&_positions[_pIndex[ii+1]*_posSize]);
vec3f p2(&_positions[_pIndex[ii+2]*_posSize]);
vec2f st0(&_texCoords[_tIndex[ii]*_tcSize]);
vec2f st1(&_texCoords[_tIndex[ii+1]*_tcSize]);
vec2f st2(&_texCoords[_tIndex[ii+2]*_tcSize]);
//compute the edge and tc differentials
vec3f dp0 = p1 - p0;
vec3f dp1 = p2 - p0;
vec2f dst0 = st1 - st0;
vec2f dst1 = st2 - st0;
float factor = 1.0f / (dst0[0] * dst1[1] - dst1[0] * dst0[1]);
//compute sTangent
vec3f sTan;
sTan[0] = dp0[0] * dst1[1] - dp1[0] * dst0[1];
sTan[1] = dp0[1] * dst1[1] - dp1[1] * dst0[1];
sTan[2] = dp0[2] * dst1[1] - dp1[2] * dst0[1];
sTan *= factor;
//should this really renormalize?
sTan =normalize( sTan);
//loop over the vertices, to update the tangents
for (int jj = 0; jj < 3; jj++) {
//get the present accumulated tangnet
vec3f curTan(&_sTangents[_tIndex[ii + jj]*3]);
//check to see if it is uninitialized, if so, insert it
if (curTan[0] == 0.0f && curTan[1] == 0.0f && curTan[2] == 0.0f) {
_sTangents[_tIndex[ii + jj]*3] = sTan[0];
_sTangents[_tIndex[ii + jj]*3+1] = sTan[1];
_sTangents[_tIndex[ii + jj]*3+2] = sTan[2];
_tanIndex.push_back(_tIndex[ii + jj]);
}
else {
//check for agreement
curTan = normalize( curTan);
if ( dot( curTan, sTan) >= cosf( 3.1415926f * 0.333333f)) {
//tangents are in agreement
_sTangents[_tIndex[ii + jj]*3] += sTan[0];
_sTangents[_tIndex[ii + jj]*3+1] += sTan[1];
_sTangents[_tIndex[ii + jj]*3+2] += sTan[2];
_tanIndex.push_back(_tIndex[ii + jj]);
}
else {
//tangents disagree, this vertex must be split in tangent space
std::multimap< GLuint, GLuint>::iterator it = collisionMap.find( _tIndex[ii + jj]);
//loop through all hits on this index, until one agrees
while ( it != collisionMap.end() && it->first == _tIndex[ii + jj]) {
curTan = vec3f( &_sTangents[it->second*3]);
curTan = normalize(curTan);
if ( dot( curTan, sTan) >= cosf( 3.1415926f * 0.333333f))
break;
it++;
}
//check for agreement with an earlier collision
if ( it != collisionMap.end() && it->first == _tIndex[ii + jj]) {
//found agreement with an earlier collision, use that one
_sTangents[it->second*3] += sTan[0];
_sTangents[it->second*3+1] += sTan[1];
_sTangents[it->second*3+2] += sTan[2];
_tanIndex.push_back(it->second);
}
else {
//we have a new collision, create a new tangent
GLuint target = (GLuint)_sTangents.size() / 3;
_sTangents.push_back( sTan[0]);
_sTangents.push_back( sTan[1]);
_sTangents.push_back( sTan[2]);
_tanIndex.push_back( target);
collisionMap.insert( std::multimap< GLuint, GLuint>::value_type( _tIndex[ii + jj], target));
}
} // else ( if tangent agrees)
} // else ( if tangent is uninitialized )
} // for jj = 0 to 2 ( iteration of triangle verts)
} // for ii = 0 to numFaces *3 ( iterations over triangle faces
//normalize all the tangents
for (int ii = 0; ii < (int)_sTangents.size(); ii += 3) {
vec3f tan(&_sTangents[ii]);
tan = normalize(tan);
_sTangents[ii] = tan[0];
_sTangents[ii+1] = tan[1];
_sTangents[ii+2] = tan[2];
}
}
//
//compute vertex normals
//////////////////////////////////////////////////////////////////////
void Model::computeNormals() {
// don't recompute normals
if (hasNormals())
return;
//allocate and initialize the normal values
_normals.resize( (_positions.size() / _posSize) * 3, 0.0f);
_nIndex.reserve( _pIndex.size());
// the collision map records any alternate locations for the normals
std::multimap< GLuint, GLuint> collisionMap;
//iterate over the faces, computing the face normal and summing it them
for ( int ii = 0; ii < (int)_pIndex.size(); ii += 3) {
vec3f p0(&_positions[_pIndex[ii]*_posSize]);
vec3f p1(&_positions[_pIndex[ii+1]*_posSize]);
vec3f p2(&_positions[_pIndex[ii+2]*_posSize]);
//compute the edge vectors
vec3f dp0 = p1 - p0;
vec3f dp1 = p2 - p0;
vec3f fNormal = cross( dp0, dp1); // compute the face normal
vec3f nNormal = normalize(fNormal); // compute a normalized normal
//iterate over the vertices, adding the face normal influence to each
for ( int jj = 0; jj < 3; jj++) {
// get the current normal from the default location (index shared with position)
vec3f cNormal( &_normals[_pIndex[ii + jj]*3]);
// check to see if this normal has not yet been touched
if ( cNormal[0] == 0.0f && cNormal[1] == 0.0f && cNormal[2] == 0.0f) {
// first instance of this index, just store it as is
_normals[_pIndex[ii + jj]*3] = fNormal[0];
_normals[_pIndex[ii + jj]*3 + 1] = fNormal[1];
_normals[_pIndex[ii + jj]*3 + 2] = fNormal[2];
_nIndex.push_back( _pIndex[ii + jj]);
}
else {
// check for agreement
cNormal = normalize( cNormal);
if ( dot( cNormal, nNormal) >= cosf( 3.1415926f * 0.333333f)) {
//normal agrees, so add it
_normals[_pIndex[ii + jj]*3] += fNormal[0];
_normals[_pIndex[ii + jj]*3 + 1] += fNormal[1];
_normals[_pIndex[ii + jj]*3 + 2] += fNormal[2];
_nIndex.push_back( _pIndex[ii + jj]);
}
else {
//normals disagree, this vertex must be along a facet edge
std::multimap< GLuint, GLuint>::iterator it = collisionMap.find( _pIndex[ii + jj]);
//loop through all hits on this index, until one agrees
while ( it != collisionMap.end() && it->first == _pIndex[ii + jj]) {
cNormal = normalize(vec3f( &_normals[it->second*3]));
if ( dot( cNormal, nNormal) >= cosf( 3.1415926f * 0.333333f))
break;
it++;
}
//check for agreement with an earlier collision
if ( it != collisionMap.end() && it->first == _pIndex[ii + jj]) {
//found agreement with an earlier collision, use that one
_normals[it->second*3] += fNormal[0];
_normals[it->second*3+1] += fNormal[1];
_normals[it->second*3+2] += fNormal[2];
_nIndex.push_back(it->second);
}
else {
//we have a new collision, create a new normal
GLuint target = (GLuint)_normals.size() / 3;
_normals.push_back( fNormal[0]);
_normals.push_back( fNormal[1]);
_normals.push_back( fNormal[2]);
_nIndex.push_back( target);
collisionMap.insert( std::multimap< GLuint, GLuint>::value_type( _pIndex[ii + jj], target));
}
} // else ( if normal agrees)
} // else (if normal is uninitialized)
} // for each vertex in triangle
} // for each face
//now normalize all the normals
for ( int ii = 0; ii < (int)_normals.size(); ii += 3) {
vec3f norm(&_normals[ii]);
norm =normalize(norm);
_normals[ii] = norm[0];
_normals[ii+1] = norm[1];
_normals[ii+2] = norm[2];
}
}
//
//
//////////////////////////////////////////////////////////////////////
void Model::computeBoundingBox( vec3f &minVal, vec3f &maxVal) {
if ( _positions.empty())
return;
minVal = vec3f( 1e10f, 1e10f, 1e10f);
maxVal = -minVal;
for ( vector<float>::iterator pit = _positions.begin() + _posSize; pit < _positions.end(); pit += _posSize) {
minVal = min( minVal, vec3f( &pit[0]));
maxVal = max( maxVal, vec3f( &pit[0]));
}
}
//
//
//////////////////////////////////////////////////////////////////////
void Model::rescale( float radius) {
if ( _positions.empty())
return;
vec3f minVal, maxVal;
computeBoundingBox(minVal, maxVal);
vec3f r = 0.5f*(maxVal - minVal);
vec3f center = minVal + r;
// float oldRadius = length(r);
float oldRadius = std::max(r.x, std::max(r.y, r.z));
float scale = radius / oldRadius;
for ( vector<float>::iterator pit = _positions.begin(); pit < _positions.end(); pit += _posSize) {
vec3f np = scale*(vec3f(&pit[0]) - center);
pit[0] = np.x;
pit[1] = np.y;
pit[2] = np.z;
}
}
//
//
//////////////////////////////////////////////////////////////////////
void Model::clearNormals(){
_normals.clear();
_nIndex.clear();
}
//
//
//////////////////////////////////////////////////////////////////////
void Model::clearTexCoords(){
_texCoords.clear();
_tIndex.clear();
}
//
//
//////////////////////////////////////////////////////////////////////
void Model::clearTangents(){
_sTangents.clear();
_tanIndex.clear();
}
//
//
//////////////////////////////////////////////////////////////////////
void Model::clearColors(){
_colors.clear();
_cIndex.clear();
}
//
//
//////////////////////////////////////////////////////////////////////
void Model::removeDegeneratePrims() {
GLuint *pSrc = 0, *pDst = 0, *tSrc = 0, *tDst = 0, *nSrc = 0, *nDst = 0, *cSrc = 0, *cDst = 0;
int degen = 0;
pSrc = &_pIndex[0];
pDst = pSrc;
if (hasTexCoords()) {
tSrc = &_tIndex[0];
tDst = tSrc;
}
if (hasNormals()) {
nSrc = &_nIndex[0];
nDst = nSrc;
}
if (hasColors()) {
cSrc =&_cIndex[0];
cDst = cSrc;
}
for (int ii = 0; ii < (int)_pIndex.size(); ii += 3, pSrc += 3, tSrc += 3, nSrc += 3, cSrc += 3) {
if ( pSrc[0] == pSrc[1] || pSrc[0] == pSrc[2] || pSrc[1] == pSrc[2]) {
degen++;
continue; //skip updating the dest
}
for (int jj = 0; jj < 3; jj++) {
*pDst++ = pSrc[jj];
if (hasTexCoords())
*tDst++ = tSrc[jj];
if (hasNormals())
*nDst++ = nSrc[jj];
if (hasColors())
*cDst++ = cSrc[jj];
}
}
_pIndex.resize( _pIndex.size() - degen * 3);
if (hasTexCoords())
_tIndex.resize( _tIndex.size() - degen * 3);
if (hasNormals())
_nIndex.resize( _nIndex.size() - degen * 3);
if (hasColors())
_cIndex.resize( _cIndex.size() - degen * 3);
}
};
| 32.640054 | 155 | 0.475105 | [
"object",
"vector",
"model"
] |
6a5a957c09260e6c64a1aaaa483aa15e1a3f29c1 | 2,721 | cpp | C++ | src/scenes/ScenePoseEstimation.cpp | tes2840/DepthProjectionMapping | 79288535c975a3f33544d9f444ebd9d8038dec04 | [
"Apache-2.0"
] | 2 | 2022-01-08T19:17:32.000Z | 2022-03-19T12:38:51.000Z | src/scenes/ScenePoseEstimation.cpp | tes2840/DepthProjectionMapping | 79288535c975a3f33544d9f444ebd9d8038dec04 | [
"Apache-2.0"
] | null | null | null | src/scenes/ScenePoseEstimation.cpp | tes2840/DepthProjectionMapping | 79288535c975a3f33544d9f444ebd9d8038dec04 | [
"Apache-2.0"
] | null | null | null | #include "ScenePoseEstimation.h"
/**
* @brief initialize variables
* @return void
*/
void ScenePoseEstimation::setup() {
m_pDepth = getSharedData().pDepth;
m_marker.setCameraParams(getSharedData().camMatrix, getSharedData().distCoeffs);
}
/**
* @brief update scene's parameters
* @detail estimate pose of the marker in camera image
* @return void
*/
void ScenePoseEstimation::update() {
if (ofGetFrameNum() % 5 != 0) {
// only update every 5 frames.
return;
}
cv::Mat image;
cv::Vec3d rvec, tvec;
m_pDepth->getColorImage(&image);
// estimate pose matrix
bool validPose = m_marker.getPoseEstimation(&image, &rvec, &tvec);
if (validPose == true) {
std::vector< cv::Point2f > imagePoints;
std::vector< cv::Point2f > dstPoints;
m_marker.getImageCorners(rvec, tvec, &imagePoints);
m_marker.drawImageFrame(&image, imagePoints);
// Get perspective transform matrix
dstPoints.push_back(cv::Point2f(0 , m_pDepth->getDepthImageHeight() ));
dstPoints.push_back(cv::Point2f(m_pDepth->getDepthImageWidth() , m_pDepth->getDepthImageHeight() ));
dstPoints.push_back(cv::Point2f(0 , 0 ));
dstPoints.push_back(cv::Point2f(m_pDepth->getDepthImageWidth() , 0 ));
m_perspectiveMatrix = cv::getPerspectiveTransform(imagePoints, dstPoints);
}
// draw pose estimation result
putText(image, "Press 'd or q' to confirm perspective transform matrix.",
cv::Point(10, 20), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 0, 0), 2);
putText(image, "'d' : Start projection mapping of the depth image.",
cv::Point(10, 40), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 0, 0), 2);
putText(image, "'q' : Start projection mapping of the capture image.",
cv::Point(10, 60), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(255, 0, 0), 2);
cv::imshow("PoseEstimation", image);
}
/**
* @brief draw marker image
* @return void
*/
void ScenePoseEstimation::draw() {
// draw marker image
cv::Mat marker = m_marker.getMarkerImage();
convertMatToOfImage(marker, &m_markerImage);
m_markerImage.draw(0, 0);
}
/**
* @brief gets called when a key is pressed
* @param[in] key - the key of pressed
* @return void
*/
void ScenePoseEstimation::keyPressed(int key) {
if (key == 'q') {
m_perspectiveMatrix.copyTo( getSharedData().perspectiveMatrix );
cv::destroyWindow("PoseEstimation");
changeState("ProjectionAreaDetection");
}
else if (key == 'd') {
m_perspectiveMatrix.copyTo(getSharedData().perspectiveMatrix);
cv::destroyWindow("PoseEstimation");
changeState("DepthProjection");
}
}
/**
* @brief gets called when scene transition
* @return this scene's name
*/
string ScenePoseEstimation::getName() {
return "PoseEstimation";
}
| 28.642105 | 102 | 0.6957 | [
"vector",
"transform"
] |
6a5f91fbfb808137b339fefda1e0a5203a89e6b2 | 10,659 | cpp | C++ | src/AstProgram.cpp | dwuid/souffle | 44413880c8928bb714aaba62792934b10eb20719 | [
"UPL-1.0"
] | 2 | 2021-04-29T16:34:06.000Z | 2021-12-04T08:31:30.000Z | src/AstProgram.cpp | dwuid/souffle | 44413880c8928bb714aaba62792934b10eb20719 | [
"UPL-1.0"
] | 1 | 2019-11-20T22:48:09.000Z | 2019-11-20T22:48:09.000Z | src/AstProgram.cpp | dwuid/souffle | 44413880c8928bb714aaba62792934b10eb20719 | [
"UPL-1.0"
] | 1 | 2021-07-27T07:49:45.000Z | 2021-07-27T07:49:45.000Z | /*
* Souffle - A Datalog Compiler
* Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file AstProgram.cpp
*
* Implement methods for class Program that represents a Datalog
* program consisting of types, relations, and clauses.
*
***********************************************************************/
#include "AstProgram.h"
#include "AstClause.h"
#include "AstComponent.h"
#include "AstFunctorDeclaration.h"
#include "AstLiteral.h"
#include "AstRelation.h"
#include "ErrorReport.h"
#include "Util.h"
#include <sstream>
namespace souffle {
/*
* Program
*/
AstProgram::AstProgram(AstProgram&& other) noexcept {
types.swap(other.types);
relations.swap(other.relations);
clauses.swap(other.clauses);
loads.swap(other.loads);
stores.swap(other.stores);
components.swap(other.components);
instantiations.swap(other.instantiations);
}
/* Add a new type to the program */
void AstProgram::addType(std::unique_ptr<AstType> type) {
auto& cur = types[type->getName()];
assert(!cur && "Redefinition of type!");
cur = std::move(type);
}
const AstType* AstProgram::getType(const AstTypeIdentifier& name) const {
auto pos = types.find(name);
return (pos == types.end()) ? nullptr : pos->second.get();
}
std::vector<const AstType*> AstProgram::getTypes() const {
std::vector<const AstType*> res;
for (const auto& cur : types) {
res.push_back(cur.second.get());
}
return res;
}
/* Add a relation to the program */
void AstProgram::addRelation(std::unique_ptr<AstRelation> r) {
const auto& name = r->getName();
assert(relations.find(name) == relations.end() && "Redefinition of relation!");
relations[name] = std::move(r);
}
void AstProgram::appendRelation(std::unique_ptr<AstRelation> r) {
// get relation
std::unique_ptr<AstRelation>& rel = relations[r->getName()];
assert(!rel && "Adding pre-existing relation!");
// add relation
rel = std::move(r);
}
/* Add a functor declaration to the program */
void AstProgram::addFunctorDeclaration(std::unique_ptr<AstFunctorDeclaration> f) {
const auto& name = f->getName();
assert(functors.find(name) == functors.end() && "Redefinition of relation!");
functors[name] = std::move(f);
}
/* Remove a relation from the program */
void AstProgram::removeRelation(const AstRelationIdentifier& name) {
/* Remove relation from map */
relations.erase(relations.find(name));
}
void AstProgram::appendClause(std::unique_ptr<AstClause> clause) {
// get relation
std::unique_ptr<AstRelation>& r = relations[clause->getHead()->getName()];
assert(r && "Trying to append to unknown relation!");
// delegate call
r->addClause(std::move(clause));
}
void AstProgram::removeClause(const AstClause* clause) {
// get relation
auto pos = relations.find(clause->getHead()->getName());
if (pos == relations.end()) {
return;
}
// delegate call
pos->second->removeClause(clause);
}
AstRelation* AstProgram::getRelation(const AstRelationIdentifier& name) const {
auto pos = relations.find(name);
return (pos == relations.end()) ? nullptr : pos->second.get();
}
AstFunctorDeclaration* AstProgram::getFunctorDeclaration(const std::string& name) const {
auto pos = functors.find(name);
return (pos == functors.end()) ? nullptr : pos->second.get();
}
/* Add a clause to the program */
void AstProgram::addClause(std::unique_ptr<AstClause> clause) {
assert(clause && "NULL clause");
clauses.push_back(std::move(clause));
}
void AstProgram::addLoad(std::unique_ptr<AstLoad> directive) {
assert(directive && "NULL IO directive");
loads.push_back(std::move(directive));
}
void AstProgram::addStore(std::unique_ptr<AstStore> directive) {
assert(directive && "NULL IO directive");
stores.push_back(std::move(directive));
}
/* Add a pragma to the program */
void AstProgram::addPragma(std::unique_ptr<AstPragma> pragma) {
assert(pragma && "NULL IO directive");
pragmaDirectives.push_back(std::move(pragma));
}
/* Put all pragma directives of the program into a list */
const std::vector<std::unique_ptr<AstPragma>>& AstProgram::getPragmaDirectives() const {
return pragmaDirectives;
}
/* Put all relations of the program into a list */
std::vector<AstRelation*> AstProgram::getRelations() const {
std::vector<AstRelation*> res;
for (const auto& rel : relations) {
res.push_back(rel.second.get());
}
return res;
}
/* Put all loads of the program into a list */
const std::vector<std::unique_ptr<AstLoad>>& AstProgram::getLoads() const {
return loads;
}
/* Put all stores of the program into a list */
const std::vector<std::unique_ptr<AstStore>>& AstProgram::getStores() const {
return stores;
}
/* Print program in textual format */
void AstProgram::print(std::ostream& os) const {
/* Print types */
os << "// ----- Types -----\n";
for (const auto& cur : types) {
os << *cur.second << "\n";
}
/* Print components */
if (!components.empty()) {
os << "\n// ----- Components -----\n";
for (const auto& cur : components) {
os << *cur << "\n";
}
}
/* Print instantiations */
if (!instantiations.empty()) {
os << "\n";
for (const auto& cur : instantiations) {
os << *cur << "\n";
}
}
/* Print functors */
os << "\n// ----- Functors -----\n";
for (const auto& cur : functors) {
const std::unique_ptr<AstFunctorDeclaration>& f = cur.second;
os << "\n\n// -- " << f->getName() << " --\n";
f->print(os);
os << "\n";
}
/* Print relations */
os << "\n// ----- Relations -----\n";
for (const auto& cur : relations) {
const std::unique_ptr<AstRelation>& rel = cur.second;
os << "\n\n// -- " << rel->getName() << " --\n";
os << *rel << "\n\n";
for (const auto clause : rel->getClauses()) {
os << *clause << "\n\n";
}
for (const auto ioDirective : rel->getLoads()) {
os << *ioDirective << "\n\n";
}
for (const auto ioDirective : rel->getStores()) {
os << *ioDirective << "\n\n";
}
}
if (!clauses.empty()) {
os << "\n// ----- Orphan Clauses -----\n";
os << join(clauses, "\n\n", print_deref<std::unique_ptr<AstClause>>()) << "\n";
}
if (!loads.empty()) {
os << "\n// ----- Orphan Load directives -----\n";
os << join(loads, "\n\n", print_deref<std::unique_ptr<AstLoad>>()) << "\n";
}
if (!stores.empty()) {
os << "\n// ----- Orphan Store directives -----\n";
os << join(stores, "\n\n", print_deref<std::unique_ptr<AstStore>>()) << "\n";
}
if (!pragmaDirectives.empty()) {
os << "\n// ----- Pragma -----\n";
for (const auto& cur : pragmaDirectives) {
os << *cur << "\n";
}
}
}
AstProgram* AstProgram::clone() const {
auto res = new AstProgram();
// move types
for (const auto& cur : types) {
res->types.insert(std::make_pair(cur.first, std::unique_ptr<AstType>(cur.second->clone())));
}
for (const auto& cur : relations) {
res->relations.insert(std::make_pair(cur.first, std::unique_ptr<AstRelation>(cur.second->clone())));
}
for (const auto& cur : functors) {
res->functors.insert(
std::make_pair(cur.first, std::unique_ptr<AstFunctorDeclaration>(cur.second->clone())));
}
for (const auto& cur : clauses) {
res->clauses.emplace_back(cur->clone());
}
for (const auto& cur : loads) {
res->loads.emplace_back(cur->clone());
}
for (const auto& cur : printSizes) {
res->printSizes.emplace_back(cur->clone());
}
for (const auto& cur : stores) {
res->stores.emplace_back(cur->clone());
}
for (const auto& cur : components) {
res->components.emplace_back(cur->clone());
}
for (const auto& cur : instantiations) {
res->instantiations.emplace_back(cur->clone());
}
for (const auto& cur : pragmaDirectives) {
res->pragmaDirectives.emplace_back(cur->clone());
}
ErrorReport errors;
res->finishParsing();
// done
return res;
}
/** Mutates this node */
void AstProgram::apply(const AstNodeMapper& map) {
for (auto& cur : types) {
cur.second = map(std::move(cur.second));
}
for (auto& cur : relations) {
cur.second = map(std::move(cur.second));
}
for (auto& cur : components) {
cur = map(std::move(cur));
}
for (auto& cur : instantiations) {
cur = map(std::move(cur));
}
for (auto& cur : pragmaDirectives) {
cur = map(std::move(cur));
}
for (auto& cur : loads) {
cur = map(std::move(cur));
}
for (auto& cur : stores) {
cur = map(std::move(cur));
}
}
void AstProgram::finishParsing() {
// unbound clauses with no relation defined
std::vector<std::unique_ptr<AstClause>> unbound;
// add clauses
for (auto& cur : clauses) {
auto pos = relations.find(cur->getHead()->getName());
if (pos != relations.end()) {
pos->second->addClause(std::move(cur));
} else {
unbound.push_back(std::move(cur));
}
}
// remember the remaining orphan clauses
clauses.clear();
clauses.swap(unbound);
// unbound directives with no relation defined
std::vector<std::unique_ptr<AstLoad>> unboundLoads;
std::vector<std::unique_ptr<AstStore>> unboundStores;
// add IO directives
for (auto& cur : loads) {
auto pos = relations.find(cur->getName());
if (pos != relations.end()) {
pos->second->addLoad(std::move(cur));
} else {
unboundLoads.push_back(std::move(cur));
}
}
// remember the remaining orphan directives
loads.clear();
loads.swap(unboundLoads);
for (auto& cur : stores) {
auto pos = relations.find(cur->getName());
if (pos != relations.end()) {
pos->second->addStore(std::move(cur));
} else {
unboundStores.push_back(std::move(cur));
}
}
// remember the remaining orphan directives
stores.clear();
stores.swap(unboundStores);
}
} // end of namespace souffle
| 29.282967 | 108 | 0.591237 | [
"vector"
] |
6a5fd68967546f8d52007146a0db7b63cfa61e1c | 965 | cc | C++ | SimG4Core/PhysicsLists/src/EmParticleList.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | SimG4Core/PhysicsLists/src/EmParticleList.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | SimG4Core/PhysicsLists/src/EmParticleList.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-03-19T13:44:54.000Z | 2019-03-19T13:44:54.000Z | #include "SimG4Core/PhysicsLists/interface/EmParticleList.h"
EmParticleList::EmParticleList()
{
pNames =
{
"gamma", "e-", "e+", "mu+", "mu-",
"pi+", "pi-", "kaon+", "kaon-", "proton",
"anti_proton", "alpha", "He3", "GenericIon", "B+",
"B-", "D+", "D-", "Ds+", "Ds-",
"anti_He3", "anti_alpha","anti_deuteron","anti_lambda_c+","anti_omega-",
"anti_sigma_c+","anti_sigma_c++", "anti_sigma+", "anti_sigma-","anti_triton",
"anti_xi_c+", "anti_xi-", "deuteron", "lambda_c+", "omega-",
"sigma_c+", "sigma_c++", "sigma+", "sigma-", "tau+",
"tau-", "triton", "xi_c+", "xi-"
};
}
EmParticleList::~EmParticleList()
{}
const std::vector<G4String>& EmParticleList::PartNames() const
{
return pNames;
}
| 35.740741 | 80 | 0.445596 | [
"vector"
] |
6a60c016c6082076b06fc326e1b6b0c3b30c29b9 | 47,410 | cpp | C++ | RPNcalc.cpp | frymonkey237/RPNcalc | cf1c50d87e3cc3331fc4de9aa310679ed0c1cb54 | [
"MIT"
] | 1 | 2018-12-22T07:47:46.000Z | 2018-12-22T07:47:46.000Z | RPNcalc.cpp | frymonkey237/RPNcalc | cf1c50d87e3cc3331fc4de9aa310679ed0c1cb54 | [
"MIT"
] | null | null | null | RPNcalc.cpp | frymonkey237/RPNcalc | cf1c50d87e3cc3331fc4de9aa310679ed0c1cb54 | [
"MIT"
] | null | null | null | /* TO DO
* > TO DO:
* > remove the extra indent on the to do list.
* > switch over to the "> Subject:" format which seems like it would more
* easily translate into program documentation. In addition, try to write
* notes in such a way that they will easily translate into
* documentation. That way, instead of deleting this stuff once it's
* complete, it can be repurposed into documentation, killing two birds
* with one stone.
*
* > FileHandler:
* > Create a file handler class and move file related functions to it.
* > Create methods for saving/loading program variables (profiles), user
* defined content, and unit conversion ratios.
*
* > Named:
* > Create a "named" command that always follows a save or load command
* pair and precedes a filename to save to or load from.
* > If no "named" command follows a save or load command pair, then
* whatever is being saved or loaded will use the associated default
* file which is called default.<ext> where ext is the associated
* extension.
* > Saving/loading with the name "default" will have the same
* effect. For example, "save stack" is equivalent to
* "save stack named default".
* > Things that can be saved or loaded:
* Note: command is what would follow "save" or "load"
* > the stack
* > extension: ".stack"
* > command: "stack"
* > default file: "default.stack"
* > user defined variables, functions, and conversion ratios
* > extension: ".def"
* > command: "defined"
* > default file: "default.def"
* > program variables/settings
* > extension: ".profile"
* > command: "profile"
* > default: "default.profile"
* > all three of the above
* > command: "all"
* > If saving and file with given name already exists, then overwrite the
* file. If file with name does not exist, create it.
* > Examples:
* > To save the stack to default file:
* "save stack" or "save stack default"
* > To save user defined variables with name "myVar":
* "save defined named myVar"
* > Load a profile with the name "fullscreen":
* "load profile named fullscreen"
*
* > Rationals:
* > look into ratio library for fractions
* > identify fractions using either regex or cstring methods
* > maybe make the RationalNumber class polymorphically inherit from
* both SingletonElement and ratio
*
* > Command Naming:
* > Add more abbreviated forms of commands which consist of a dash, '-',
* followed by a single letter. Also, add more full names for
* trigonometric operations, like "arcsecant" or "hyperbolictangent".
*
* > Help:
* > list all the commands in the help file.
* > Create help command and help file reader. Look into how man pages are
* normally handled on linux and in ncurses programs.
* > Can get help for specific commands with: "help <cmd>"
* > help is an infix command, requiring look-ahead, like set, store,
* save, etc.
* > if help isn't followed by a command, then display main help page
* > help info stored in RPNcalc.help
* > How will the user scroll through help page?
* > help files also should be accessible from the command line using
* the man command.
*
* > Undo:
* > undo returns the stack to it's state prior to the last input, or
* prior to the last undo if undo is called multiple times.
* > undo mode can be disabled by the user with "unset undo" in order
* to improve performance.
* > Create flag in ProgramVariables for undo.
* > number of past stacks to save is user definable with
* "<num> set undosteps"
* > will have to add undoSteps variable to ProgramVariables.
* > If undo flag is set, a file is kept open and stack is appended to
* the file during each iteration, after the input is entered, but
* before it is processed.
* >
*
* > Set:
* > For numeric program variables the existing syntax for set is:
* "<value> set <variable>"
* > Need a system for using set with boolean program variables.
* > The syntax for boolean variables is:
* "set <variable>" or "unset <variable>"
* > "set" sets the proceeding variable to true, and "unset" sets
* the proceeding variable to false, regardless of the variable's
* previous value.
* > both "set" and "unset" call the setProgramVariable function.
* > After look ahead is performed to get the variable to set,
* the setProgramVariable function branches depending on if
* the variable is a bool or an int.
* > If variable is an int, the top of the stack is popped
* and stored to the variable
* > If variable is a bool, the first letter of the current
* term, which would have to be either "set" or "unset",
* is checked.
* > ProgramVariables method setVar is called using
* ternary conditional operator:
* progVar.setVar(<variable>, tolowercase(
* progVar.inputTerms[index].front()) == 's'?
* true : false);
* > Note: Boolean variables that represent a "this or
* that" relationship rather than a "yes or no"
* relationship, may have variable names which aren't
* really a variable, but rather an alias for a
* for inverse of another variable, eg. "set degrees"
* is really an alias for "unset radians".
*
*
* > Radian mode:
* > move radian mode back to ProgramVariables, and then add a bool
* parameter to unary operations for the radian variable.
*
* > ProgramVariables:
* > make ProgramVariables a class so that it can have member
* functions.
* > create an overloaded method called something like "setVar" with
* two variations.
* > One sets integer variables and takes a string containing the
* name of the intended variable along with the new integer value
* for the variable.
* > The other sets boolean variables and takes the variable name
* along with a boolean value.
*
* > Save/Load:
* > could even create profiles
* > user would specify profile names which would be appended on to the
* filename for the profile data.
* ".RPNstack.someProfileName.profile"
* > profiles would be useful for running the calculator on different
* terminals.
*
* > Units:
* > units a specified with a unit initials preceded by an underscore
* > examples: kelvin - "_k" , millimeter - "_mm"
* > units are stored in stack element data structure
* > user can basically enter anything they want to as a unit as long as its made
* up of alphanumeric characters and preceded by an underscore.
* > multiplying mixed units creates a new unit that is the product of the two
* units, eg. "_mm*Hg".
* > Dividing mixed units creates a new unit that is the ratio of the two units,
* eg. "_m/hr"
* > each stack element contains an array for numerator units, an array for
* denominator units and a flag for has units.
* > If has units is raised, command functions will search an abridged array
* of only operations where units are defined, and will then call overloaded
* versions of the associated functions that also take the unit arrays as
* parameters.
* > for binary commands some operations will only be defined when units of
* operands match, ie addition and subtraction, while others work
* regardless of units
* > to complicate things further, units with known conversions should
* be converted if possible to facilitate things like addition and
* subtraction.
* > think about algebraic variables
* > Another way to handle multiple data types on the stack is to create a stack
* element structure which would hold a stack element, its datatype, units, and any
* other relevant information.
* > This would require somehow defining how to perform binary operations on
* mixed data types, and when operations can't be performed on mixed data
* types.
* > Look into using the gnu scientific library , atlas, and or boost
* > <boost/numeric/interval.hpp> for arithmetic on intervals.
* > Could be useful for computing the result of integration over a range.
* > will need to link the boost library when compiling.
* > Gnu mpfr library for arbitrary precision floating point
* calculations.
* > For mixed type oprations, look into overloading the math functions and using
* try-catch statements to catch when a operation is undefined for given types.
* > save command that is like set and store in that what is to be saved follows the
* command.
* > valid forms are "save variables", "save profile", "save stack", and
* "save all"
* > Use regex to determine input types
* > Possible types:
* > real number
* > 0 or more + or - followed by 0 or more digits or commas
* followed by zero to one decimal points followed by one
* or more digits followed by 0 to one scientific notation
* stuff.
* > (+|-)*(\\d|,)*.*\\d+(e(
* > complex number
* > vector
* > rational
* > unit
* > command
* > interval
* > using boost interval package
* > change realStack back to a stack rather than a list
* > Or maybe a dynamically allocated array with my own implementation
* of container functions, like push_back(num) and size().
* > add "set scientific" command to put in scientific notation
* > "set standard" to change back to standard notation
* > look into using a package for arbitrary floating point calculations
* > Gnu mpfr
* > allow user to set precision of calculations and significant
* figures to display.
* > for set command map try and create a struct that has a pointer to a
* member of program variables of type T.
* > Create a new ncurses mode that is accessed with the command line
* argument "-n". That way the currently functioning mode will continue
* to be operational while the ncurses interface is implemented.
* > Once ncurses is fully operational, make ncurses mode the default
* and the original mode accessed with a command line argument.
* > Make each of the 3 modes into separate functions so that the main
* function is basically just a decision tree between the three
* modes.
* > Create an empty class "StackElement" that classes "RealNumber",
* "RealVector", "ComplexNumber", and "RationalNumber" inherit from
* > The stack will be an array of "StackElement"s, which will allow
* holding real numbers, complex numbers, rationals, and vectors on
* the same stack.
* > A "RealVector" will hold an array of real numbers, complex
* numbers or rationals.
* > Create class "SingletonElement" that inherits from
* "StackElement" and is inherited by "RealNumber",
* "ComplexNumber", and "RationalNumber". This is so the
* vector class can hold an array of SingletonElements.
* > Rational class holds two integer values: "numerator" and
* "denominator".
* > StackElement
* / \
* SingletonElement SetElement
* / | \ | \
* Unit RationalNumber RealNumber ComplexNumber RealVector RealMatrix
* +---------+-------------+-----------+
* | | |
* RationalUnit RealUnit ComplexUnit
*
*
* > Units are a class that contains an array of unit numerators and
* unit denominators. An empty numerator or denominator array is
* assumed to be equivalent to 1.
* > RationalUnit, RealUnit, and ComplexUnit are polymorphic
* classes that inherit from both the unit class and their
* respective SingletonElement class. These are empty classes
* which inherit the their respective element variable and the
* unit variables.
* > Allowed Mixed unit operations are limited to multiplication
* and division and some derived operations derived from them
* like raising to exponent. For example, the unit km+s is not
* allowed, but km*s or km/s is.
* > Units are demarcated with an underscore, so 50 miles per hour
* would be entered as "50 _mi/hr".
* > No spaces in units.
* > Multiplication and division must be explicit.
* > Units do not have to be predefined, a unit is just two arrays
* of cstrings. The cstrings themselves can be anything, but the
* naming must be consistent, ie. "miles" and "mi" would not be
* considered equivalent.
* > Units "_d" is a way of specifying degree mode for a specific
* operand as well as a way to prevent invalid mixed unit
* operations on a degree. Radians don't need a unit so there
* isn't a analogous "_r" for radians.
* > Conversions do have to be predefined
* > There are two types of conversions: linear and non-linear.
* > Linear conversions are something like miles to
* kilometers, which can be expressed by conversion ratio,
* while non-linear conversions are something like
* Fahrenheit to Celsius, that requires adding some
* constant.
* > Linear and non-linear are separated because of the
* difference in how dimensional analysis is executed and
* how the conversions are represented by the program.
* > Linear conversions are represented by a
* "ConversionRatio" data structure which contains two
* equivalent RealUnit types with different units which
* ideally should only contain a single unit numerator.
* > For example, the ConversionRatio data structure
* for converting between miles and kilometers might
* contain one RealUnit with a value of 1 and a unit
* of "mi", and another RealUnit with a value of
* 1.60932 and a unit of "km" since 1 mile == 1.60932
* kilometers.
* > Compound linear conversions are handled with
* dimensional analysis.
* > For dimensional analysis, a path must be found
* between the input numerator and denominator
* and the desired numerator and denominator.
* > Maybe solving from either end and working
* towards the middle would be more efficient
* than the brute force method
* > Alternatively, instead of finding a path at
* conversion time, all possible linear
* conversions of between two units could be
* created every time a new conversion ratio is
* added. Essentially, this would still be the
* brute force strategy except most of the work
* has been done ahead of time. At conversion
* time, all that is left is to seach for the
* appropriate conversion, or conversions, if
* performing dimensional analysis.
* > This is probably the better option of the
* two.
* > Because new conversion ratios will need to
* created whether the conversion ratio was
* added by the programmer or the user, all
* conversion ratios should be stored in a
* file loaded at
* > "to" operator handles conversions. It is an infix operator
* where the left operand is the value with units that you
* wish to convert, while the right operand is the unit you
* wish to convert to. For example, number of kilometers in
* 50 miles would be written as "50 _mi to _km
* > Once function definitions are implemented, user defined
* non-linear unit conversions can be implemented as a
* special case of a function definition where the only
* parameter is a unit and the result is a unit (which
* includes classes inheriting from unit).
*
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cmath>
#include <stdexcept>
#include <list>
#include <fstream>
#include <stack>
#include <vector>
#include <map>
//for timing program execution (debugging)
#include <ctime>
#include <ratio>
#include <chrono>
//RPNcalc header files
#include "MathStack.h"
#include "mathFunctions.h"
//No longer using
//#include <array>
//#include <algorithm>
//#include <regex>
using namespace std;
// +---------------------------------+
// | Class and Struct Declarations |
//----+---------------------------------+---------------------------------------
//Data structure for holding user modifiable program variables. Passed by reference to
// program command function. Stack is not included and is passed separately.
struct ProgramVariables {
bool exit, //program exits when true
error; //Terminate current input process if error
vector<string> inputTerms; //The list of user input terms
int index; //The index of the current input term
//needed for infix commands (set,store)
//and repeat commands (repeat,sum,etc)
list<string> userMessages; //Messages to display on next output
//Format:
//Execution Time,
//last input,
//Error messages, if any
map<int,int> repeatCount; //Map of remaining repeats to repeat indices
//Could also use 2D array
map<string,double> userVariables; //Used with store command
//User-modifiable program variables
string prompt; //prompt preceding user input
int displayWidth, //Width of display window
outputLength, //Number of stack elements to display
maxStackLength; //Maximum length of stack
//For timing main thread (debugging)
chrono::steady_clock::time_point time1;
chrono::steady_clock::time_point time2;
chrono::duration<double> timeSpan;
}; //end programVariables
//Data structures for mapping user command to functions or variables
struct UnCommandMap {
string inputCommand;
void (*functionPtr)(MathStack &);
bool convertTrigInput,
convertTrigOutput;
}; //end UnCommandMap
struct BinCommandMap {
string inputCommand;
void (*functionPtr)(MathStack &, double);
}; //end BinCommandMap
struct ConstantMap {
string inputCommand;
double constantValue;
}; //end ConstantMap
struct ProgCmdMap {
string inputCommand;
void (*functionPtr)(MathStack &, ProgramVariables &);
}; //end ProgCmdMap
//*****************************************************************************************
//**| Constant Definitions |*************************************************************
//*****************************************************************************************
//Command counts need for commandMap array sizing
const int CONST_CMD_COUNT = 2;
const int UN_CMD_COUNT = 25;
const int BIN_CMD_COUNT = 19;
const int PROG_CMD_COUNT = 19;
const int TOTAL_CMD_COUNT = CONST_CMD_COUNT + UN_CMD_COUNT + BIN_CMD_COUNT
+ PROG_CMD_COUNT;
const string GREETING = "+-RPNcalc----------------------------+\n"
"| ___ ___ __ __ _ __ _ __ | \n"
"| / O ) / O ) \\ / /__\\/ \\| |/__\\ |\n"
"| / . \\ / / / /\\ v / |__ () \\ | |__ |\n"
"|/_/ \\_\\_/ /_/ \\_/ \\__/\\__/\\_\\|\\__/ |\n"
"+------------------------------------+\n"
" type 'help' for help ";
/*
+-RPNcalc----------------------------+
| ___ ___ __ __ _ __ _ __ |
| / O ) / O ) \ / /__\/ \| |/__\ |
| / . \ / / / /\ v / |__ () \ | |__ |
|/_/ \_\_/ /_/ \_/ \__/\__/\_\|\__/ |
+------------------------------------+
type 'help' for for help
*/
const char CLEAR_TERMINAL[] = { 0x1b, '[', '2', 'J', 0}; //ANSI clear screen escape seq.
//Mathematical Constants
const double PI = acos(-1);
const double EULERS_NUM = 2.7182818284590452353602874713526624977;
const string RESERVED_WORDS[TOTAL_CMD_COUNT] = { "pi", "e", "-*", "neg", "e^x",
"exp", "10^-", "sin", "cos", "tan", "sec", "csc", "cot", "asin", "acos",
"atan", "sinh", "cosh", "tanh", "asinh", "acosh", "ln", "log", "sqrt",
"cbrt", "sq", "cb", "+", "add", "-", "sub", "subtract", "*", "multiply",
"/", "divide", "//", "div", "mod","%", "^", "swap", "mag2", "pyth",
"take", "root", "quit", "set", "width", "length", "stackLength",
"clear", "save", "sum", "load", "repeat", "sequence", "sum", "product",
"radians", "degrees", "store", "sto", "-l", "-s"
}; //end RESERVED_WORDS
//*****************************************************************************************
//**| Function Prototypes |**************************************************************
//*****************************************************************************************
//input processing
vector<string> extractInputTerms();
void processInput(MathStack &, ProgramVariables &);
bool performUnaryOperation(string, MathStack &);
bool performBinaryOperation(string, MathStack &);
bool addConstant(string, MathStack &);
bool executeProgCmd(string, MathStack &, ProgramVariables &);
bool addNumber(string, MathStack &, ProgramVariables &);
bool recallVariable(string, MathStack &, ProgramVariables &);
string toLowercase(string);
//Display functions
void displayOutput(MathStack &, ProgramVariables &);
void drawLine(int);
//other
void startupProcedure(MathStack &);
void exitProcedure(MathStack &);
bool writeStackToFile(MathStack); //A copy is desired rather than a reference here
bool loadStackFromFile(MathStack &);
void initializeRepeatCount(string,ProgramVariables &);
//program functions
void quitProgram(MathStack &, ProgramVariables &);
void widthCmd(MathStack &, ProgramVariables &);
void displayLengthCmd(MathStack &, ProgramVariables &);
void stackLengthCmd(MathStack &, ProgramVariables &);
void setPrompt(MathStack &, ProgramVariables &); //(incomplete)
void clearStack(MathStack &, ProgramVariables &);
void saveStack(MathStack &, ProgramVariables &);
void loadStack(MathStack &, ProgramVariables &);
void repeatInput(MathStack &, ProgramVariables &);
void setProgVariable(MathStack &, ProgramVariables &);
void trigMode(MathStack &, ProgramVariables &);
void storeVar(MathStack &, ProgramVariables &);
// +----------------+
// | Command Maps |
//----+----------------+--------------------------------------------------------
//Remember, when adding new commands, command count constant must be adjusted
//and new command should be added to RESERVED_WORDS.
const ConstantMap CONSTANT_MAP[CONST_CMD_COUNT] = {{"pi", PI}, {"e", EULERS_NUM}};
const UnCommandMap UNARY_OP_MAP[UN_CMD_COUNT] = {
{"-*", negative, 0, 0}, {"neg", negative, 0, 0},
{"e^x", exponential, 0, 0}, {"exp", exponential, 0, 0},
{"10^-", tenToPower, 0, 0}, {"sin", sine, 1, 0}, {"cos", cosine, 1, 0},
{"tan", tangent, 1, 0}, {"sec", secant, 1, 0}, {"csc", cosecant, 1, 0},
{"cot", cotangent, 1, 0}, {"asin", arcsine, 0, 1},
{"acos", arccosine, 0, 1}, {"atan", arctangent, 0, 1},
{"sinh", hyperSin, 0, 0}, {"cosh", hyperCos, 0, 0},
{"tanh", hyperTan, 0, 0}, {"asinh", arcHyperSin, 0, 0},
{"acosh", arcHyperCos, 0, 0}, {"ln", naturalLog, 0, 0},
{"log", logBase10, 0, 0}, {"sqrt", squareRoot, 0, 0},
{"cbrt", cubeRoot, 0, 0}, {"sq", square, 0, 0},{"cb", cube, 0, 0}
}; //end UNARY_OP_MAP
const BinCommandMap BINARY_OP_MAP[BIN_CMD_COUNT] = {
{"+", add}, {"add", add}, {"-", subtract}, {"sub", subtract},
{"subtract", subtract}, {"*", multiply}, {"multiply", multiply}, {"/", divide},
{"divide",divide}, {"//", integerDivide}, {"div", integerDivide},
{"mod", modFunction}, {"%", modFunction}, {"^", raise2power}, {"swap", swapXY},
{"mag2", magnitude2D}, {"pyth", magnitude2D}, {"take", moveNtoTop},
{"root", root}
}; //end BINARY_OP_MAP
const ProgCmdMap PROGRAM_CMD_MAP[PROG_CMD_COUNT] = {
{"quit", quitProgram}, {"set", setProgVariable}, {"width", widthCmd},
{"length", displayLengthCmd}, {"stackLength", stackLengthCmd},
{"clear", clearStack}, {"save", saveStack}, {"sum", repeatInput},
{"load", loadStack}, {"repeat", repeatInput}, {"sequence", repeatInput},
{"sum", repeatInput}, {"product", repeatInput}, {"radians", trigMode},
{"degrees", trigMode}, {"store", storeVar}, {"sto", storeVar},
{"-l", loadStack}, {"-s", saveStack}
}; //end PROGRAM_CMD_MAP
// +-----------------+
// | Main function |
//-----+-----------------+------------------------------------------------------
int main(int argc, char *argv[]) {
//Variables used in both argument mode and interface mode
MathStack mainStack; //primary stack
ProgramVariables progVar; //contains user modifiable variables
//Variables used in interface mode only
progVar.exit = false; //exit program when true
progVar.prompt = " >>> "; //User may modify
progVar.displayWidth = 36; //Width of terminal display
progVar.outputLength = 10; //Number of stack elements to display
progVar.maxStackLength = 100; //Maximum length of stack
//Variables used in argument mode only
string term; //Used for parsing arguments
//argument mode - performs single RPN calculation and outputs the stack top
if (argc > 1) {
for (int i = 1; i < argc; i++) { //skip over program name at i = 0
term = argv[i];
progVar.inputTerms.push_back(term);
} //end for
progVar.error = false; //assume no errors
processInput(mainStack, progVar);
if (!progVar.error) //display result if no errors
cout << mainStack.top() << endl;
else //if error, display error msg
cout << progVar.userMessages.back() << endl;
} //end if
//Interface mode - terminal calculator interface for multiple calculations
else {
//Ask user if they'd like to load a previously saved stack
startupProcedure(mainStack);
//Initial time (debugging)
progVar.time1 = chrono::steady_clock::now();
do {
//Display
displayOutput(mainStack, progVar); //display program output
cout << progVar.prompt; //display input prompt
//flush program variables
progVar.userMessages.clear(); //flush user messages
progVar.error = false; //error assumed false
progVar.repeatCount.clear(); //flush repeat counts
//Extract user input
progVar.inputTerms = extractInputTerms();
//start timer (debugging)
progVar.time1 = chrono::steady_clock::now();
//process input terms
processInput(mainStack, progVar);
} while(!progVar.exit);
exitProcedure(mainStack);
} //end else
return 0;
} //end main
//*****************************************************************************************
//**| Function Definitions |*************************************************************
//*****************************************************************************************
void startupProcedure(MathStack &stack) {
char loadChoice;
bool loadSuccessful;
cout << "\nWould you like to load a previously saved stack? [Y/n]: ";
cin >> loadChoice;
if (loadChoice == 'y' || loadChoice == 'Y') {
cout << "Loading stack..." << endl;
loadSuccessful = loadStackFromFile(stack);
cout << (loadSuccessful ? "Stack loaded" : "Error loading stack") << endl << endl;
} //end if
} //end startupProcedure
void exitProcedure(MathStack &stack) {
char saveChoice;
bool saveSuccessful;
cout << CLEAR_TERMINAL << endl << "Would you like to save the current stack? [Y/n]: ";
cin >> saveChoice;
if (saveChoice == 'y' || saveChoice == 'Y') {
cout << "Saving stack..." << endl;
stack.reverseStack();
saveSuccessful = writeStackToFile(stack);
cout << (saveSuccessful? "stack saved" : "Error opening stack file") << endl;
} //end if
} //end exitProcedure
bool loadStackFromFile(MathStack &stack) {
ifstream stackFile;
double currentNum;
stackFile.open("RPNcalc.stack");
if (stackFile) {
while (stackFile >> currentNum)
stack.addNum(currentNum);
stackFile.close();
return true;
} //end if
else
return false;
} //end loadStackFromFile
bool writeStackToFile(MathStack stack) {
ofstream stackFile;
stackFile.open("RPNcalc.stack", ofstream::out | ofstream::trunc);
if (stackFile) {
while (!stack.empty())
stackFile << stack.popTop() << endl;
stackFile.close();
} //end if
else
return false;
} //end writeStackToFile
//*****************************
//***| Input Processing |***
//*****************************
vector<string> extractInputTerms() {
string term;
vector<string> inputTerms;
char currentChar,
lastChar = ' '; //set initially to space to capture first term
//Extract input terms
do { //terminate loop at end of line
cin.get(currentChar); //extract next char
//if character isn't whitespace, add it to back of term as lowerspace character.
if (!isspace(currentChar))
term.push_back(currentChar);
//Terms end when current char is space and last char is not.
//After terms end, they're added to the term list, and term is flushed.
if (isspace(currentChar) && !isspace(lastChar)) {
inputTerms.push_back(term);
term.clear();
} //end if
lastChar = currentChar;
} while (currentChar != '\n');
return inputTerms;
} //end extractInputTerms
void processInput(MathStack &stack, ProgramVariables &progVar) {
bool opSuccess; //indicates that attempted operation was successful
string term;
if (progVar.inputTerms.empty())
stack.addNum(stack.top());
else {
progVar.index = 0; //flush index
while (progVar.index < progVar.inputTerms.size() && !progVar.error) {
term = progVar.inputTerms[progVar.index];
opSuccess = addNumber(term, stack, progVar);
if (!opSuccess)
opSuccess = performBinaryOperation(toLowercase(term), stack);
if (!opSuccess)
opSuccess = performUnaryOperation(toLowercase(term), stack);
if (!opSuccess)
opSuccess = addConstant(term, stack); //case sensitive
if (!opSuccess)
opSuccess = executeProgCmd(toLowercase(term), stack, progVar);
if (!opSuccess)
opSuccess = recallVariable(toLowercase(term), stack, progVar);
if (!opSuccess) {
progVar.userMessages.push_front("Error! Invalid input: " + term);
progVar.error = true;
} //end if (!opSuccess)
else
progVar.index++;
} //end while
} //end else
} //end process input
bool addNumber(string input, MathStack &stack, ProgramVariables &progVar) {
bool operationSuccess;
try {
stack.addNum(stod(input));
operationSuccess = true;
if (stack.size() > progVar.maxStackLength)
stack.trimStack(progVar.maxStackLength);
} //end try
catch (out_of_range& e) { //In case number is out of range
progVar.userMessages.push_front("Error! Out of range: " + input);
progVar.error = true;
operationSuccess = true;
} //end catch
catch (invalid_argument& r) {
operationSuccess = false;
} //Go on if number conversion unsuccessful
return operationSuccess;
} //end addNumber
bool executeProgCmd(string input, MathStack &stack, ProgramVariables &progVar) {
bool operationSuccess = false; //assume operation is unsuccessful until it is
int i = 0; //for array iteration
while (!operationSuccess && i < PROG_CMD_COUNT) {
if (input == PROGRAM_CMD_MAP[i].inputCommand) {
PROGRAM_CMD_MAP[i].functionPtr(stack, progVar);
operationSuccess = true;
} //end if
i++;
} //end while
return operationSuccess;
} //end executeProgCmd
bool addConstant(string input, MathStack &stack) {
bool operationSuccess = false; //assume operation is unsuccessful until it is
int i = 0; //for array iteration
while (!operationSuccess && i < CONST_CMD_COUNT) {
if (input == CONSTANT_MAP[i].inputCommand) {
stack.addNum(CONSTANT_MAP[i].constantValue);
operationSuccess = true;
} //end if
i++;
} //end while
return operationSuccess;
} //end addConstant
bool performUnaryOperation(string input, MathStack &stack) {
bool operationSuccess = false; //assume operation is unsuccessful until it is
int i = 0; //for array iteration
while (!operationSuccess && i < UN_CMD_COUNT) {
if (input == UNARY_OP_MAP[i].inputCommand) {
if (UNARY_OP_MAP[i].convertTrigInput && !stack.radianMode) {
degToRad(stack);
UNARY_OP_MAP[i].functionPtr(stack);
} //end if
else if (UNARY_OP_MAP[i].convertTrigOutput
&& !stack.radianMode) {
UNARY_OP_MAP[i].functionPtr(stack);
radToDeg(stack);
} //end else if
else
UNARY_OP_MAP[i].functionPtr(stack);
operationSuccess = true;
} //end if
i++;
} //end while
return operationSuccess;
} //end performUnaryOperation
bool performBinaryOperation(string input, MathStack &stack) {
bool operationSuccess = false; //assume operation is unsuccessful until it is
int i = 0; //for array iteration
double lastIn;
while (!operationSuccess && i < BIN_CMD_COUNT) {
if (input == BINARY_OP_MAP[i].inputCommand) {
lastIn = stack.popTop();
BINARY_OP_MAP[i].functionPtr(stack, lastIn);
operationSuccess = true;
} //end if
i++;
} //end while
return operationSuccess;
} //end performBinaryOperation
bool recallVariable(string input, MathStack &stack, ProgramVariables &progVar) {
bool operationSuccess;
try {
stack.addNum(progVar.userVariables.at(input));
operationSuccess = true;
}
catch (out_of_range& e) {
operationSuccess = false;
} //end catch
return operationSuccess;
} //end recallVariable
string toLowercase(string str) {
for (int i = 0; i < str.size(); i++)
str[i] += (str[i] > 64 && str[i] < 91) * 32;
return str;
} //end toLowercase
// +----------------------+
// | Output Generating |
//-------+----------------------+----------------------------------------------
void displayOutput(MathStack &stack, ProgramVariables &progVar) {
list<double> outputList = stack.topNreversed(progVar.outputLength);
string lastInput;
//stop timer, record difference, and add execution time to user messages
progVar.time2 = chrono::steady_clock::now();
progVar.timeSpan = chrono::duration_cast<chrono::duration<double>>
(progVar.time2 - progVar.time1);
//Add user messages
lastInput = "Last Input:";
for (string term : progVar.inputTerms)
lastInput += " " + term;
progVar.userMessages.push_front(lastInput);
progVar.userMessages.push_front("Execution time: "
+ to_string(progVar.timeSpan.count()) + 's');
//display output
cout << CLEAR_TERMINAL << endl << GREETING << endl;
drawLine(progVar.displayWidth);
cout << setprecision(16); //some operations seem to break down past 16 digits
for (int i = progVar.outputLength; i > 0; i--) {
cout << " |" << setw(2) << right << i << ": "
<< left << setw(progVar.displayWidth - 6)
<< outputList.front() << "| ";
if (!progVar.userMessages.empty()) {
cout << (i != 1? "-> " + progVar.userMessages.front() : "...");
progVar.userMessages.pop_front();
} //end if
cout << endl;
outputList.pop_front();
} //end for
drawLine(progVar.displayWidth);
} //end displayOutput
void drawLine(int lineWidth) {
string line (lineWidth - 2, '-');
cout << " +" << line << '+' << endl;
} //end drawLine
//*************************************
//***| Program Command Functions |***
//*************************************
void quitProgram(MathStack &stack, ProgramVariables &progVar)
{ progVar.exit = true; }
void clearStack(MathStack &stack, ProgramVariables &progVar)
{ stack.clearStack(); }
void saveStack(MathStack &stack, ProgramVariables &progVar)
{ writeStackToFile(stack); }
void loadStack(MathStack &stack, ProgramVariables &progVar)
{ loadStackFromFile(stack); }
void widthCmd(MathStack &stack, ProgramVariables &progVar) {
progVar.userMessages.push_front("Display width: "
+ to_string(progVar.displayWidth)
+" characters");
} //end showWidth
void displayLengthCmd(MathStack &stack, ProgramVariables &progVar) {
progVar.userMessages.push_front("Display Length: "
+ to_string(progVar.outputLength)
+ " stack elements");
} //end showDisplayLength
void stackLengthCmd(MathStack &stack, ProgramVariables &progVar) {
progVar.userMessages.push_front("Max stack length: "
+ to_string(progVar.maxStackLength)
+ " stack elements");
} //end showStackLength
void trigMode(MathStack &stack, ProgramVariables &progVar) {
string mode = stack.radianMode? "radians" : "degrees";
progVar.userMessages.push_front("Trig Mode: " + mode);
} //end trigMode
void setProgVariable(MathStack &stack, ProgramVariables &progVar) {
string nextTerm = progVar.inputTerms[progVar.index + 1];
//look ahead to next term to see what to set
if (nextTerm == "length")
progVar.outputLength = stack.popTop();
else if (nextTerm == "width")
progVar.displayWidth = stack.popTop();
else if (nextTerm == "stackLength")
progVar.maxStackLength = stack.popTop();
else if (nextTerm == "radians") {
stack.radianMode = true;
} //end else if
else if (nextTerm == "degrees") {
stack.radianMode = false;
} //end else if
else {
progVar.error = true;
progVar.userMessages.push_front("Error! Invalid set: " + nextTerm);
} //end else
} //end setProgVariable
void repeatInput(MathStack &stack, ProgramVariables &progVar) {
int index = progVar.index;
string term = progVar.inputTerms[index];
//remove the last repeat number from the stack every time repeat is called
stack.pop();
//initialize progVar.repeatCount if not already.
if (progVar.repeatCount.empty()) {
initializeRepeatCount(term, progVar);
} //end if
//Behavior for specific repeat commands
//Switch to command -> function pointer map if list grows larger
if (term == "sum")
add(stack, stack.popTop());
else if (term == "product")
multiply(stack, stack.popTop());
else if (term == "sequence" && progVar.repeatCount[index] > 1)
stack.addNum(stack.top());
//If more repeats needed
if (progVar.repeatCount[index] > 1) {
progVar.repeatCount[index]--;
progVar.index = -1; //will be incremented up to 0 in processInput
} //end if
//if on last repeat, reset count and move on with line
else if (progVar.repeatCount[index] == 1
&& progVar.repeatCount.upper_bound(index)
!= progVar.repeatCount.end()) {
progVar.repeatCount[index] = abs(stoi(progVar.inputTerms[index-1]));
} //end else if
} //end repeatInput
void initializeRepeatCount(string term, ProgramVariables &progVar) {
for (int i = 0; i < progVar.inputTerms.size(); i++) {
term = progVar.inputTerms[i];
if (term == "repeat" || term == "sequence" || term == "sum"
|| term == "product") {
try {
progVar.repeatCount.insert(pair<int,int>(i,
abs(stoi(progVar.inputTerms[i-1]))));
} //end try
catch (invalid_argument& r) {
progVar.error = true;
progVar.userMessages.push_front("Error! Invalid repeat times: "
+ progVar.inputTerms[i-1]);
} //end catch
//If count initially set to 0, infinite loop will result
if (progVar.repeatCount[i] == 0) {
progVar.error = true;
progVar.userMessages.push_front("Error! Cannot repeat 0 times");
} //end if (progVar.repeatCount[i] == 0)
} //end if
}//end for
} //end initializeRepeatCount
void storeVar(MathStack &stack, ProgramVariables &progVar) {
string varName = progVar.inputTerms[progVar.index + 1];
for (int i = 0; i < TOTAL_CMD_COUNT; i++) {
if (varName == RESERVED_WORDS[i]) {
progVar.error = true;
progVar.userMessages.push_front("Error! Invalid Variable Name: "
+ varName);
} //end if
} //end for
if (!progVar.error) {
double value = stack.top();
//if variable already exists, update it, else create new variable
try {
progVar.userVariables.at(varName) = value;
} //end try
catch (out_of_range &e) {
progVar.userVariables.insert(pair<string,double>(varName, value));
} //end catch
progVar.index++;
} //end if
} //end storeVar
//THE GRAVEYARD_______________________________________________________________
/*
void setProgVariable(MathStack &stack, ProgramVariables &progVar) {
int i = 0;
bool found = false;
progVar.set = true;
string nextTerm = progVar.inputTerms[progVar.index + 1]; //look-ahead at next term
while (!found && i < SET_CMD_COUNT) {
if (nextTerm == SET_CMD_MAP[i].inputCommand) {
SET_CMD_MAP[i].functionPtr(stack, progVar);
found = true;
} //end if
i++;
} //end while
if (!found) {
progVar.error = true;
progVar.userMessages.push_front("Error! Invalid set: " + nextTerm);
} //end if
} //end setProgVariable
*/
| 44.810964 | 91 | 0.548492 | [
"vector"
] |
6a698321820d4e8a72477dd919282799175f08e6 | 32,493 | cpp | C++ | src/wallet/rpcdump.cpp | ComputerCraftr/devault | 546b54df85e3392f85e7ea5fcd4ea9b395ba8f4c | [
"MIT"
] | null | null | null | src/wallet/rpcdump.cpp | ComputerCraftr/devault | 546b54df85e3392f85e7ea5fcd4ea9b395ba8f4c | [
"MIT"
] | null | null | null | src/wallet/rpcdump.cpp | ComputerCraftr/devault | 546b54df85e3392f85e7ea5fcd4ea9b395ba8f4c | [
"MIT"
] | null | null | null | // Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2019 DeVault developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <cashaddrenc.h>
#include <chain.h>
#include <chainparams.h>
#include <config.h>
#include <core_io.h>
#include <dstencode.h>
#include <merkleblock.h>
#include <rpc/server.h>
#include <wallet/rpcwallet.h>
#include <script/script.h>
#include <script/standard.h>
#include <sync.h>
#include <util/fs_util.h>
#include <util/time.h>
#include <validation.h>
#include <wallet/wallet.h>
#include <wallet/mnemonic.h>
#include <util/splitstring.h>
#include <devault/coinreward.h>
#include <devault/rewards.h>
#include <string.h> // for memcpy
#include <univalue.h>
#include <cmath>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <iomanip> // for get_time
static std::string EncodeDumpString(const std::string &str) {
std::stringstream ret;
for (uint8_t c : str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
uint8_t c = str[pos];
if (c == '%' && pos + 2 < str.length()) {
c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) |
((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15));
pos += 2;
}
ret << c;
}
return ret.str();
}
UniValue abortrescan(const Config &config, const JSONRPCRequest &request) {
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 0) {
throw std::runtime_error("abortrescan\n"
"\nStops current wallet rescan triggered by "
"an RPC call, e.g. by an importprivkey call.\n"
"\nExamples:\n"
"\nImport a private key\n" +
HelpExampleCli("importprivkey", "\"mykey\"") +
"\nAbort the running wallet rescan\n" +
HelpExampleCli("abortrescan", "") +
"\nAs a JSON-RPC call\n" +
HelpExampleRpc("abortrescan", ""));
}
if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) {
return false;
}
pwallet->AbortRescan();
return true;
}
void ImportAddress(CWallet *, const CTxDestination &dest,
const std::string &strLabel);
void ImportScript(CWallet *const pwallet, const CScript &script,
const std::string &strLabel, bool isRedeemScript)
EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the "
"private key for this address or "
"script");
}
pwallet->MarkDirty();
if (!pwallet->HaveWatchOnly(script) &&
!pwallet->AddWatchOnly(script, 0 /* nCreateTime */)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (isRedeemScript) {
if (!pwallet->HaveCScript(script) && !pwallet->AddCScript(script)) {
throw JSONRPCError(RPC_WALLET_ERROR,
"Error adding p2sh redeemScript to wallet");
}
ImportAddress(pwallet, CScriptID(script), strLabel);
} else {
CTxDestination destination;
if (ExtractDestination(script, destination)) {
pwallet->SetAddressBook(destination, strLabel, "receive");
}
}
}
void ImportAddress(CWallet *const pwallet, const CTxDestination &dest,
const std::string &strLabel)
EXCLUSIVE_LOCKS_REQUIRED(pwallet->cs_wallet) {
CScript script = GetScriptForDestination(dest);
ImportScript(pwallet, script, strLabel, false);
// add to address book or update label
if (IsValidDestination(dest)) {
pwallet->SetAddressBook(dest, strLabel, "receive");
}
}
UniValue importaddress(const Config &config, const JSONRPCRequest &request) {
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 ||
request.params.size() > 4) {
throw std::runtime_error(
"importaddress \"address\" ( \"label\" rescan p2sh )\n"
"\nAdds a script (in hex) or address that can be watched as if it "
"were in your wallet but cannot be used to spend. Requires a new "
"wallet backup.\n"
"\nArguments:\n"
"1. \"script\" (string, required) The hex-encoded script "
"(or address)\n"
"2. \"label\" (string, optional, default=\"\") An "
"optional label\n"
"3. rescan (boolean, optional, default=true) Rescan "
"the wallet for transactions\n"
"4. p2sh (boolean, optional, default=false) Add "
"the P2SH version of the script as well\n"
"\nNote: This call can take minutes to complete if rescan is true, "
"during that time, other rpc calls\n"
"may report that the imported address exists but related "
"transactions are still missing, leading to temporarily "
"incorrect/bogus balances and unspent outputs until rescan "
"completes.\n"
"If you have the full public key, you should call importpubkey "
"instead of this.\n"
"\nNote: If you import a non-standard raw script in hex form, "
"outputs sending to it will be treated\n"
"as change, and not show up in many RPCs.\n"
"\nExamples:\n"
"\nImport a script with rescan\n" +
HelpExampleCli("importaddress", "\"myscript\"") +
"\nImport using a label without rescan\n" +
HelpExampleCli("importaddress", R"("myscript" "testing" false)") +
"\nAs a JSON-RPC call\n" +
HelpExampleRpc("importaddress",
R"("myscript", "testing", false)"));
}
std::string strLabel;
if (!request.params[1].isNull()) {
strLabel = request.params[1].get_str();
}
// Whether to perform rescan after import
bool fRescan = true;
if (!request.params[2].isNull()) {
fRescan = request.params[2].get_bool();
}
if (fRescan && fPruneMode) {
throw JSONRPCError(RPC_WALLET_ERROR,
"Rescan is disabled in pruned mode");
}
WalletRescanReserver reserver(pwallet);
if (fRescan && !reserver.reserve()) {
throw JSONRPCError(
RPC_WALLET_ERROR,
"Wallet is currently rescanning. Abort existing rescan or wait.");
}
// Whether to import a p2sh version, too
bool fP2SH = false;
if (!request.params[3].isNull()) {
fP2SH = request.params[3].get_bool();
}
{
LOCK2(cs_main, pwallet->cs_wallet);
CTxDestination dest = DecodeDestination(request.params[0].get_str(),
config.GetChainParams());
if (IsValidDestination(dest)) {
if (fP2SH) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Cannot use the p2sh flag with an address - "
"use a script instead");
}
ImportAddress(pwallet, dest, strLabel);
} else if (IsHex(request.params[0].get_str())) {
std::vector<uint8_t> data(ParseHex(request.params[0].get_str()));
ImportScript(pwallet, CScript(data.begin(), data.end()), strLabel,
fP2SH);
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Invalid DeVault address or script");
}
}
if (fRescan) {
pwallet->RescanFromTime(TIMESTAMP_MIN, reserver, true /* update */);
pwallet->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importprunedfunds(const Config &config,
const JSONRPCRequest &request) {
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 2) {
throw std::runtime_error(
"importprunedfunds\n"
"\nImports funds without rescan. Corresponding address or script "
"must previously be included in wallet. Aimed towards pruned "
"wallets. The end-user is responsible to import additional "
"transactions that subsequently spend the imported outputs or "
"rescan after the point in the blockchain the transaction is "
"included.\n"
"\nArguments:\n"
"1. \"rawtransaction\" (string, required) A raw transaction in hex "
"funding an already-existing address in wallet\n"
"2. \"txoutproof\" (string, required) The hex output from "
"gettxoutproof that contains the transaction\n");
}
CMutableTransaction tx;
if (!DecodeHexTx(tx, request.params[0].get_str())) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 txid = tx.GetId();
CWalletTx wtx(pwallet, MakeTransactionRef(std::move(tx)));
CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK,
PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
// Search partial merkle tree in proof for our transaction and index in
// valid block
std::vector<uint256> vMatch;
std::vector<size_t> vIndex;
size_t txnIndex = 0;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) ==
merkleBlock.header.hashMerkleRoot) {
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) ||
!chainActive.Contains(
mapBlockIndex[merkleBlock.header.GetHash()])) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Block not found in chain");
}
std::vector<uint256>::const_iterator it;
if ((it = std::find(vMatch.begin(), vMatch.end(), txid)) ==
vMatch.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Transaction given doesn't exist in proof");
}
txnIndex = vIndex[it - vMatch.begin()];
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Something wrong with merkleblock");
}
wtx.nIndex = txnIndex;
wtx.hashBlock = merkleBlock.header.GetHash();
LOCK2(cs_main, pwallet->cs_wallet);
if (pwallet->IsMine(*wtx.tx)) {
pwallet->AddToWallet(wtx, false);
return NullUniValue;
}
throw JSONRPCError(
RPC_INVALID_ADDRESS_OR_KEY,
"No addresses in wallet correspond to included transaction");
}
UniValue removeprunedfunds(const Config &config,
const JSONRPCRequest &request) {
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
"removeprunedfunds \"txid\"\n"
"\nDeletes the specified transaction from the wallet. Meant for "
"use with pruned wallets and as a companion to importprunedfunds. "
"This will effect wallet balances.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The hex-encoded id of "
"the transaction you are deleting\n"
"\nExamples:\n" +
HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1"
"ce581bebf46446a512166eae762873"
"4ea0a5\"") +
"\nAs a JSON-RPC call\n" +
HelpExampleRpc("removeprunedfunds",
"\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166"
"eae7628734ea0a5\""));
}
LOCK2(cs_main, pwallet->cs_wallet);
TxId txid;
txid.SetHex(request.params[0].get_str());
std::vector<TxId> txIds;
txIds.push_back(txid);
std::vector<TxId> txIdsOut;
if (pwallet->ZapSelectTx(txIds, txIdsOut) != DBErrors::LOAD_OK) {
throw JSONRPCError(RPC_WALLET_ERROR,
"Could not properly delete the transaction.");
}
if (txIdsOut.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER,
"Transaction does not exist in wallet.");
}
return NullUniValue;
}
UniValue importpubkey(const Config &config, const JSONRPCRequest &request) {
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 ||
request.params.size() > 4) {
throw std::runtime_error(
"importpubkey \"pubkey\" ( \"label\" rescan )\n"
"\nAdds a public key (in hex) that can be watched as if it were in "
"your wallet but cannot be used to spend. Requires a new wallet "
"backup.\n"
"\nArguments:\n"
"1. \"pubkey\" (string, required) The hex-encoded public "
"key\n"
"2. \"label\" (string, optional, default=\"\") An "
"optional label\n"
"3. rescan (boolean, optional, default=true) Rescan "
"the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true, "
"during that time, other rpc calls\n"
"may report that the imported pubkey exists but related "
"transactions are still missing, leading to temporarily "
"incorrect/bogus balances and unspent outputs until rescan "
"completes.\n"
"\nExamples:\n"
"\nImport a public key with rescan\n" +
HelpExampleCli("importpubkey", "\"mypubkey\"") +
"\nImport using a label without rescan\n" +
HelpExampleCli("importpubkey", R"("mypubkey" "testing" false)") +
"\nAs a JSON-RPC call\n" +
HelpExampleRpc("importpubkey", R"("mypubkey", "testing", false)"));
}
std::string strLabel;
if (!request.params[1].isNull()) {
strLabel = request.params[1].get_str();
}
// Whether to perform rescan after import
bool fRescan = true;
if (!request.params[2].isNull()) {
fRescan = request.params[2].get_bool();
}
if (fRescan && fPruneMode) {
throw JSONRPCError(RPC_WALLET_ERROR,
"Rescan is disabled in pruned mode");
}
WalletRescanReserver reserver(pwallet);
if (fRescan && !reserver.reserve()) {
throw JSONRPCError(
RPC_WALLET_ERROR,
"Wallet is currently rescanning. Abort existing rescan or wait.");
}
if (!IsHex(request.params[0].get_str())) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Pubkey must be a hex string");
}
std::vector<uint8_t> data(ParseHex(request.params[0].get_str()));
CPubKey pubKey(data.begin(), data.end());
if (!pubKey.IsFullyValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Pubkey is not a valid public key");
}
{
LOCK2(cs_main, pwallet->cs_wallet);
ImportAddress(pwallet, pubKey.GetID(), strLabel);
ImportScript(pwallet, GetScriptForRawPubKey(pubKey), strLabel, false);
}
if (fRescan) {
pwallet->RescanFromTime(TIMESTAMP_MIN, reserver, true /* update */);
pwallet->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue dumpprivkey(const Config &config, const JSONRPCRequest &request) {
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1) {
throw std::runtime_error(
"dumpprivkey \"address\"\n"
"\nReveals the private key corresponding to 'address'.\n"
"Then the importprivkey can be used with this output\n"
"\nArguments:\n"
"1. \"address\" (string, required) The DeVault address for the "
"private key\n"
"\nResult:\n"
"\"key\" (string) The private key\n"
"\nExamples:\n" +
HelpExampleCli("dumpprivkey", "\"myaddress\"") +
HelpExampleCli("importprivkey", "\"mykey\"") +
HelpExampleRpc("dumpprivkey", "\"myaddress\""));
}
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::string strAddress = request.params[0].get_str();
CTxDestination dest =
DecodeDestination(strAddress, config.GetChainParams());
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,
"Invalid DeVault address");
}
#ifdef HAVE_VARIANT
const CKeyID *keyID = &std::get<CKeyID>(dest);
#else
const CKeyID *keyID = boost::get<CKeyID>(&dest);
#endif
if (!keyID) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
}
CKey vchSecret;
if (!pwallet->GetKey(*keyID, vchSecret)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " +
strAddress + " is not known");
}
std::string bech32string = EncodeSecret(vchSecret);
UniValue keys(UniValue::VOBJ);
keys.pushKV("bech32",bech32string);
return keys;
}
UniValue dumpwallet(const Config &config, const JSONRPCRequest &request) {
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpwallet \"filename\"\n"
"\nDumps all wallet keys in a human-readable format to a "
"server-side file. This does not allow overwriting existing "
"files.\n"
"Imported scripts are included in the dumpsfile\n"
"Note that if your wallet contains keys which are not derived from "
"your HD seed (e.g. imported keys), these are not covered by\n"
"only backing up the seed itself, and must be backed up too (e.g. "
"ensure you back up the whole dumpfile).\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename with path "
"(either absolute or relative to devaultd)\n"
"\nResult:\n"
"{ (json object)\n"
" \"filename\" : { (string) The filename with full "
"absolute path\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("dumpwallet", "\"test\"") +
HelpExampleRpc("dumpwallet", "\"test\""));
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
fs::path filepath = request.params[0].get_str();
filepath = fs::absolute(filepath);
/**
* Prevent arbitrary files from being overwritten. There have been reports
* that users have overwritten wallet files this way:
* https://github.com/bitcoin/bitcoin/issues/9934
* It may also avoid other security issues.
*/
if (fs::exists(filepath)) {
throw JSONRPCError(RPC_INVALID_PARAMETER,
filepath.string() + " already exists. If you are "
"sure this is what you want, "
"move it out of the way first");
}
std::ofstream file;
file.open(filepath.string().c_str());
if (!file.is_open()) {
throw JSONRPCError(RPC_INVALID_PARAMETER,
"Cannot open wallet dump file");
}
std::map<CTxDestination, int64_t> mapKeyBirth;
const std::map<CKeyID, int64_t> &mapKeyPool = pwallet->GetAllReserveKeys();
pwallet->GetKeyBirthTimes(mapKeyBirth);
std::set<CScriptID> scripts = pwallet->GetCScripts();
// TODO: include scripts in GetKeyBirthTimes() output instead of separate
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID>> vKeyBirth;
for (const auto &entry : mapKeyBirth) {
#ifdef HAVE_VARIANT
if (const CKeyID *keyID = &std::get<CKeyID>(entry.first)) {
#else
if (const CKeyID *keyID = boost::get<CKeyID>(&entry.first)) {
#endif
// set and test
vKeyBirth.emplace_back(entry.second, *keyID);
}
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by DeVault %s\n", CLIENT_BUILD);
file << strprintf("# * Created on %s\n", FormatISO8601DateTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n",
chainActive.Height(),
chainActive.Tip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n",
FormatISO8601DateTime(chainActive.Tip()->GetBlockTime()));
file << "\n";
// add the base58check encoded extended master if the wallet uses HD
CHDChain hdChain;
SecureString ssMnemonic;
pwallet->GetDecryptedHDChain(hdChain);
if (!pwallet->GetMnemonic(hdChain, ssMnemonic))
throw std::runtime_error(std::string(__func__) + ": Get Mnemonic failed");
file << "# mnemonic: " << ssMnemonic << "\n";
SecureVector vchSeed = hdChain.GetSeed();
file << "# HD seed: " << HexStr(vchSeed) << "\n\n";
CExtKey masterKey;
masterKey.SetMaster(&vchSeed[0], vchSeed.size());
/*
CBitcoinExtKey b58extkey;
b58extkey.SetKey(masterKey);
file << "# extended private masterkey: " << b58extkey.ToString() << "\n";
CExtPubKey masterPubkey;
masterPubkey = masterKey.Neuter();
CBitcoinExtPubKey b58extpubkey;
b58extpubkey.SetKey(masterPubkey);
file << "# extended public masterkey: " << b58extpubkey.ToString() << "\n\n";
*/
for (size_t i = 0; i < hdChain.CountAccounts(); ++i) {
CHDAccount acc;
if(hdChain.GetAccount(i, acc)) {
file << "# external chain counter: " << acc.nExternalChainCounter << "\n";
file << "# internal chain counter: " << acc.nInternalChainCounter << "\n\n";
} else {
file << "# WARNING: ACCOUNT " << i << " IS MISSING!" << "\n\n";
}
}
// Rather than just print out the keypaths in a somewhat random order
// Put into a map so they can be ordered by hdkeypath
// after map is created, print out
std::map<uint64_t,std::string> keypaths;
for (const auto& it : vKeyBirth) {
const CKeyID &keyid = it.second;
std::string strTime = FormatISO8601DateTime(it.first);
std::string strAddr = EncodeDestination(keyid);
CKey key;
std::string fullstr="";
if (pwallet->GetKey(keyid, key)) {
fullstr += strprintf("%s %s ", EncodeSecret(key),strTime);
if (pwallet->mapAddressBook.count(keyid)) {
fullstr += strprintf("label=%s",EncodeDumpString(pwallet->mapAddressBook[keyid].name));
} else if (mapKeyPool.count(keyid)) {
fullstr += "reserve=1";
} else {
fullstr += "change=1";
}
{
std::string hdkeypath="";
if (pwallet->mapHdPubKeys.count(keyid)) hdkeypath += pwallet->mapHdPubKeys[keyid].GetKeyPath();
fullstr += strprintf(" # addr=%s,hdkeypath=%s\n", strAddr, hdkeypath);
// This is to make the output keys sorted by path
// Put into a std::map based on numeric path that will be stored in sorted order
std::vector<std::string> vParts;
Split(vParts, hdkeypath, "/");
uint64_t keynum = std::stoi(vParts.back());
vParts.pop_back();
uint64_t ext = std::stoi(vParts.back());
uint64_t order = ext*100000+keynum;
keypaths.insert(make_pair(order,fullstr));
}
}
}
// Print sorted map
for (const auto& s : keypaths) {
file << s.second;
}
file << "\n";
for (const CScriptID &scriptid : scripts) {
CScript script;
std::string create_time = "0";
std::string address = EncodeDestination(scriptid);
// get birth times for scripts with metadata
auto it = pwallet->m_script_metadata.find(scriptid);
if (it != pwallet->m_script_metadata.end()) {
create_time = FormatISO8601DateTime(it->second.nCreateTime);
}
if (pwallet->GetCScript(scriptid, script)) {
file << strprintf("%s %s script=1",
HexStr(script.begin(), script.end()),
create_time);
file << strprintf(" # addr=%s\n", address);
}
}
file << "\n";
file << "# End of dump\n";
file.close();
UniValue reply(UniValue::VOBJ);
reply.pushKV("filename", filepath.string());
return reply;
}
int64_t GetImportTimestamp(const UniValue &data, int64_t now) {
if (data.exists("timestamp")) {
const UniValue ×tamp = data["timestamp"];
if (timestamp.isNum()) {
return timestamp.get_int64();
} else if (timestamp.isStr() && timestamp.get_str() == "now") {
return now;
}
throw JSONRPCError(RPC_TYPE_ERROR,
strprintf("Expected number or \"now\" timestamp "
"value for key. got type %s",
uvTypeName(timestamp.type())));
}
throw JSONRPCError(RPC_TYPE_ERROR,
"Missing required timestamp field for key");
}
static UniValue getmyrewardinfo(const Config &config, const JSONRPCRequest &request) {
if (request.fHelp || request.params.size() != 0)
throw std::runtime_error(
"getmyrewardinfo \"filename\"\n"
"\nReturns status for all of my valid reward UTXOs.\n"
"\nExamples:\n"
+ HelpExampleCli("getmyrewardinfo","")
+ HelpExampleRpc("getmyrewardinfo",""));
#ifdef ENABLE_WALLET
CWallet *const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
const int nMinRewardInCoins = config.GetChainParams().GetConsensus().nMinReward.toIntCoins();
const int nMinBlocks = config.GetChainParams().GetConsensus().nMinRewardBlocks;
const int nBlocksPerYear = config.GetChainParams().GetConsensus().nBlocksPerYear;
const int nPowTargetSpacing = config.GetChainParams().GetConsensus().nPowTargetSpacing;
const int nMaxYearIndex = config.GetChainParams().GetConsensus().nPerCentPerYear.size()-1;
UniValue result(UniValue::VARR);
std::vector<CRewardValue> rewards = prewards->GetOrderedRewards();
UniValue total(UniValue::VOBJ);
total.push_back(Pair("Total Number of Rewards", (int)prewards->GetNumberOfCandidates()));
result.push_back(total);
std::time_t cftime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
// Minimum balances for 1 month payout given current reward % of 15,12,9,7,5
std::vector<double> nMinBalance;
for (auto pc : config.GetChainParams().GetConsensus().nPerCentPerYear) {
double val = nMinRewardInCoins * 12 * 100.0 / pc;
nMinBalance.push_back(val);
}
for (auto& val : rewards) {
isminetype mine = ::IsMine(*pwallet, val.scriptPubKey());
if (mine == ISMINE_SPENDABLE && val.IsActive()) {
const uint32_t nMyHeight = val.GetHeight();
UniValue delta(UniValue::VOBJ);
delta.push_back(Pair("Addr",GetAddrFromTxOut(val.GetTxOut())));
delta.push_back(Pair("Value",ValueFromAmount(val.GetValue())));
delta.push_back(Pair("created at Height",(int)val.GetCreationHeight()));
if (val.GetPayCount() > 0) {
delta.push_back(Pair("Last paid at Height",(int)val.GetHeight()));
}
delta.push_back(Pair("paid times",(int)val.GetPayCount()));
int nNumOlder = 0;
for (auto& inner_val : rewards) {
if ((inner_val.GetHeight() < nMyHeight) && inner_val.IsActive()) nNumOlder++;
}
delta.push_back(Pair("reward candidates older than this one",nNumOlder));
// Use nMinBlocks unless there are more older candidates that need to get paid out
int nYear = nMyHeight/nBlocksPerYear;
if (nYear > nMaxYearIndex) nYear = nMaxYearIndex;
// Check if balance is below minimum required for 1 month payout,
// if it is, then extend the needed number of blocks for payout
int neededBlocks = nMinBlocks;
if (val.GetValue().toIntCoins() < (int)nMinBalance[nYear]) {
neededBlocks *= std::ceil(nMinBalance[nYear]/val.GetValue().toIntCoins());
}
// In event of very large number of older payouts that need to be made,
// extend by even more blocks
nNumOlder = std::max(nNumOlder,neededBlocks);
int payoutHeight = nMyHeight+nNumOlder;
int blocksNeeded = payoutHeight - chainActive.Height();
// Use blocksNeeded to estimate date
std::time_t nexttime = cftime + blocksNeeded*nPowTargetSpacing;
delta.push_back(Pair("estimated reward block", payoutHeight));
delta.push_back(Pair("estimated next reward date", FormatISO8601Date(nexttime)));
result.push_back(delta);
}
}
#else
UniValue result(UniValue::VARR);
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet required for this function to provide information");
#endif
return result;
}
// clang-format off
static const ContextFreeRPCCommand commands[] = {
// category name actor (function) argNames
// ------------------- ------------------------ ---------------------- ----------
{ "wallet", "abortrescan", abortrescan, {} },
{ "wallet", "dumpprivkey", dumpprivkey, {"address"} },
{ "wallet", "dumpwallet", dumpwallet, {"filename"} },
{ "wallet", "importaddress", importaddress, {"address","label","rescan","p2sh"} },
{ "wallet", "importprunedfunds", importprunedfunds, {"rawtransaction","txoutproof"} },
{ "wallet", "importpubkey", importpubkey, {"pubkey","label","rescan"} },
{ "wallet", "removeprunedfunds", removeprunedfunds, {"txid"} },
{ "wallet", "getmyrewardinfo", getmyrewardinfo, {} },
};
// clang-format on
void RegisterDumpRPCCommands(CRPCTable &t) {
for (auto& command : commands) {
t.appendCommand(command.name, &command);
}
}
| 39.673993 | 120 | 0.579017 | [
"object",
"vector"
] |
6a6b2d57cf41403f8b55556619a2188bc247ee08 | 1,419 | cpp | C++ | LeetCode/LeetCode/main.cpp | yulingtianxia/leetcode | aee9af7e49bcba2cb473216fc564987612165d39 | [
"MIT"
] | null | null | null | LeetCode/LeetCode/main.cpp | yulingtianxia/leetcode | aee9af7e49bcba2cb473216fc564987612165d39 | [
"MIT"
] | null | null | null | LeetCode/LeetCode/main.cpp | yulingtianxia/leetcode | aee9af7e49bcba2cb473216fc564987612165d39 | [
"MIT"
] | null | null | null | //
// main.cpp
// LeetCode
//
// Created by 杨萧玉 on 14/11/27.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
#include <array>
#include <stack>
#include <queue>
#include <set>
#include <math.h>
#include <stdlib.h>
#include <sstream>
#include <unordered_set>
#include <unordered_map>
#include <iomanip>
#include <numeric>
#include <limits>
#include <list>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
struct UndirectedGraphNode {
int label;
vector<UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {};
};
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
set<int> tag;
for (int i = 0; i < nums.size(); ++i) {
if(tag.find(nums[i])!= tag.end())
return true;
else
tag.insert(nums[i]);
}
return false;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
Solution s = Solution();
return 0;
} | 18.92 | 69 | 0.596899 | [
"vector"
] |
6a6e3c894a4740dc07cf81c85074cdb9cc1fd36e | 2,597 | cpp | C++ | 2_DesignPattern/DesignPatterns/codes/2_BehavioralPatterns/State/demo.cpp | XingxinHE/SoftwareDevelopment | 64ef9ede17999231bb50fe41980102db382addef | [
"MIT"
] | null | null | null | 2_DesignPattern/DesignPatterns/codes/2_BehavioralPatterns/State/demo.cpp | XingxinHE/SoftwareDevelopment | 64ef9ede17999231bb50fe41980102db382addef | [
"MIT"
] | null | null | null | 2_DesignPattern/DesignPatterns/codes/2_BehavioralPatterns/State/demo.cpp | XingxinHE/SoftwareDevelopment | 64ef9ede17999231bb50fe41980102db382addef | [
"MIT"
] | null | null | null | #include <iostream>
#include <typeinfo>
/**
* The base State class declares methods that all Concrete State should
* implement and also provides a backreference to the Context object, associated
* with the State. This backreference can be used by States to transition the
* Context to another State.
*/
class Context;
class State {
/**
* @var Context
*/
protected:
Context *context_;
public:
virtual ~State() {
}
void set_context(Context *context) {
this->context_ = context;
}
virtual void Handle1() = 0;
virtual void Handle2() = 0;
};
/**
* The Context defines the interface of interest to clients. It also maintains a
* reference to an instance of a State subclass, which represents the current
* state of the Context.
*/
class Context {
/**
* @var State A reference to the current state of the Context.
*/
private:
State *state_;
public:
Context(State *state) : state_(nullptr) {
this->TransitionTo(state);
}
~Context() {
delete state_;
}
/**
* The Context allows changing the State object at runtime.
*/
void TransitionTo(State *state) {
std::cout << "Context: Transition to " << typeid(*state).name() << ".\n";
if (this->state_ != nullptr)
delete this->state_;
this->state_ = state;
this->state_->set_context(this);
}
/**
* The Context delegates part of its behavior to the current State object.
*/
void Request1() {
this->state_->Handle1();
}
void Request2() {
this->state_->Handle2();
}
};
/**
* Concrete States implement various behaviors, associated with a state of the
* Context.
*/
class ConcreteStateA : public State {
public:
void Handle1() override;
void Handle2() override {
std::cout << "ConcreteStateA handles request2.\n";
}
};
class ConcreteStateB : public State {
public:
void Handle1() override {
std::cout << "ConcreteStateB handles request1.\n";
}
void Handle2() override {
std::cout << "ConcreteStateB handles request2.\n";
std::cout << "ConcreteStateB wants to change the state of the context.\n";
this->context_->TransitionTo(new ConcreteStateA);
}
};
void ConcreteStateA::Handle1() {
{
std::cout << "ConcreteStateA handles request1.\n";
std::cout << "ConcreteStateA wants to change the state of the context.\n";
this->context_->TransitionTo(new ConcreteStateB);
}
}
/**
* The client code.
*/
void ClientCode() {
Context *context = new Context(new ConcreteStateA);
context->Request1();
context->Request2();
delete context;
}
int main() {
ClientCode();
return 0;
} | 21.823529 | 80 | 0.661533 | [
"object"
] |
6a750cd1709c3fd2ef7cfb402b78b86e4afd87b6 | 787 | cpp | C++ | Game/Event/EventMessage/WorldObjectRemoveEvent.cpp | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | Game/Event/EventMessage/WorldObjectRemoveEvent.cpp | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | Game/Event/EventMessage/WorldObjectRemoveEvent.cpp | LukasKalinski/Gravity-Game | 5c817e3ae7658e5e42a8cff760a57380eb11fe3e | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////
// WorldObjectRemoveEvent.cpp
// Implementation of the Class WorldObjectRemoveEvent
// Created on: 16-Apr-2008 23:56:24
// Original author: Lukas Kalinski
///////////////////////////////////////////////////////////
#include "WorldObjectRemoveEvent.h"
/**
* Constructs a removal event of the specified world object.
*
* @param wo
*/
WorldObjectRemoveEvent::WorldObjectRemoveEvent(const WorldObject* wo):
m_worldObject(wo)
{
}
WorldObjectRemoveEvent::~WorldObjectRemoveEvent() {
}
/**
* Returns the world object that is to be removed from the world (i.e., is not
* removed *yet*).
*/
const WorldObject* WorldObjectRemoveEvent::getRemoved() const {
return m_worldObject;
} | 23.848485 | 79 | 0.593393 | [
"object"
] |
6a793c49f5bcd77a6976fad9270f343d8b07a887 | 4,046 | cc | C++ | src/theia/sfm/find_common_tracks_in_views_test.cc | maxchernet/TheiaSfM | 603f3ad8bfea1e54fe23fa553f268760a9c9276c | [
"BSD-3-Clause"
] | 770 | 2015-02-12T14:32:01.000Z | 2022-03-16T00:54:33.000Z | src/theia/sfm/find_common_tracks_in_views_test.cc | maxchernet/TheiaSfM | 603f3ad8bfea1e54fe23fa553f268760a9c9276c | [
"BSD-3-Clause"
] | 237 | 2015-02-20T18:50:16.000Z | 2022-01-18T05:21:48.000Z | src/theia/sfm/find_common_tracks_in_views_test.cc | maxchernet/TheiaSfM | 603f3ad8bfea1e54fe23fa553f268760a9c9276c | [
"BSD-3-Clause"
] | 278 | 2015-02-12T06:20:26.000Z | 2022-03-23T17:25:21.000Z | // Copyright (C) 2015 The Regents of the University of California (Regents).
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// * Neither the name of The Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include <algorithm>
#include <utility>
#include <vector>
#include "gtest/gtest.h"
#include "theia/sfm/find_common_tracks_in_views.h"
#include "theia/sfm/reconstruction.h"
#include "theia/sfm/types.h"
namespace theia {
TEST(FindCommonTracksInViews, NoCommonTracks) {
const Feature feature;
const std::vector<std::pair<ViewId, Feature> > track1 = {{0, feature},
{1, feature}};
const std::vector<std::pair<ViewId, Feature> > track2 = {{1, feature},
{2, feature}};
const std::vector<std::pair<ViewId, Feature> > track3 = {{2, feature},
{3, feature}};
Reconstruction reconstruction;
reconstruction.AddView("0");
reconstruction.AddView("1");
reconstruction.AddView("2");
reconstruction.AddView("3");
reconstruction.AddTrack(track1);
reconstruction.AddTrack(track2);
reconstruction.AddTrack(track3);
const std::vector<ViewId> views_to_find_common_tracks = { 0, 1, 2, 3};
const std::vector<TrackId> common_tracks = FindCommonTracksInViews(
reconstruction, views_to_find_common_tracks);
EXPECT_EQ(common_tracks.size(), 0);
}
TEST(FindCommonTracksInViews, CommonTracks) {
const Feature feature;
const std::vector<std::pair<ViewId, Feature> > track1 = {{1, feature},
{2, feature}};
const std::vector<std::pair<ViewId, Feature> > track2 = {
{0, feature}, {1, feature}, {2, feature}, {3, feature}};
const std::vector<std::pair<ViewId, Feature> > track3 = {{2, feature},
{3, feature}};
Reconstruction reconstruction;
reconstruction.AddView("0");
reconstruction.AddView("1");
reconstruction.AddView("2");
reconstruction.AddView("3");
reconstruction.AddTrack(track1);
reconstruction.AddTrack(track2);
reconstruction.AddTrack(track3);
const std::vector<ViewId> views_to_find_common_tracks = { 0, 1, 2, 3};
const std::vector<TrackId> common_tracks = FindCommonTracksInViews(
reconstruction, views_to_find_common_tracks);
EXPECT_EQ(common_tracks.size(), 1);
}
} // namespace theia
| 42.145833 | 78 | 0.681167 | [
"vector"
] |
6a847f670bb6807be48729f8827680337909f76d | 2,783 | hpp | C++ | src/stan/lang/grammars/indexes_grammar.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2019-07-05T01:40:40.000Z | 2019-07-05T01:40:40.000Z | src/stan/lang/grammars/indexes_grammar.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | null | null | null | src/stan/lang/grammars/indexes_grammar.hpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2018-08-28T12:09:08.000Z | 2018-08-28T12:09:08.000Z | #ifndef STAN_LANG_GRAMMARS_INDEXES_GRAMMAR_HPP
#define STAN_LANG_GRAMMARS_INDEXES_GRAMMAR_HPP
#include <stan/lang/ast.hpp>
#include <stan/lang/grammars/expression_grammar.hpp>
#include <stan/lang/grammars/semantic_actions.hpp>
#include <stan/lang/grammars/whitespace_grammar.hpp>
#include <boost/spirit/include/qi.hpp>
#include <string>
#include <sstream>
#include <vector>
namespace stan {
namespace lang {
// needed to break circularity of expression grammar including indexes
template <typename Iterator>
struct expression_grammar;
template <typename Iterator>
struct indexes_grammar
: boost::spirit::qi::grammar<Iterator,
std::vector<idx>(scope),
whitespace_grammar<Iterator> > {
variable_map& var_map_;
std::stringstream& error_msgs_;
expression_grammar<Iterator>& expression_g;
indexes_grammar(variable_map& var_map,
std::stringstream& error_msgs,
expression_grammar<Iterator>& eg);
boost::spirit::qi::rule<Iterator,
std::vector<idx>(scope),
whitespace_grammar<Iterator> >
indexes_r;
boost::spirit::qi::rule<Iterator,
idx(scope),
whitespace_grammar<Iterator> >
index_r;
boost::spirit::qi::rule<Iterator,
boost::spirit::qi::unused_type,
whitespace_grammar<Iterator> >
close_indexes_r;
boost::spirit::qi::rule<Iterator,
uni_idx(scope),
whitespace_grammar<Iterator> >
uni_index_r;
boost::spirit::qi::rule<Iterator,
multi_idx(scope),
whitespace_grammar<Iterator> >
multi_index_r;
boost::spirit::qi::rule<Iterator,
omni_idx(scope),
whitespace_grammar<Iterator> >
omni_index_r;
boost::spirit::qi::rule<Iterator,
lb_idx(scope),
whitespace_grammar<Iterator> >
lb_index_r;
boost::spirit::qi::rule<Iterator,
ub_idx(scope),
whitespace_grammar<Iterator> >
ub_index_r;
boost::spirit::qi::rule<Iterator,
lub_idx(scope),
whitespace_grammar<Iterator> >
lub_index_r;
boost::spirit::qi::rule<Iterator,
expression(scope),
whitespace_grammar<Iterator> >
int_expression_r;
};
}
}
#endif
| 30.922222 | 74 | 0.53719 | [
"vector"
] |
6a8636dfaac43802fa5ed9c2ea0de74ad43e8a26 | 10,139 | cc | C++ | onnxruntime/contrib_ops/cpu/quantization/dynamic_quantize_lstm.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 5 | 2021-02-20T04:53:48.000Z | 2021-03-09T19:29:27.000Z | onnxruntime/contrib_ops/cpu/quantization/dynamic_quantize_lstm.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 5 | 2021-03-01T21:35:50.000Z | 2022-03-09T05:38:38.000Z | onnxruntime/contrib_ops/cpu/quantization/dynamic_quantize_lstm.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 2 | 2021-01-29T09:36:51.000Z | 2021-02-01T13:42:40.000Z | #include "core/providers/cpu/rnn/lstm_base.h"
#include "core/providers/cpu/rnn/rnn_helpers.h"
#include "core/providers/cpu/rnn/uni_directional_lstm.h"
namespace onnxruntime {
namespace contrib {
using namespace rnn::detail;
class DynamicQuantizeLSTM : public OpKernel, public LSTMBase {
public:
DynamicQuantizeLSTM(const OpKernelInfo& info) : OpKernel(info), LSTMBase(info) {}
#ifdef MLAS_SUPPORTS_PACKED_GEMM_U8X8
Status PrePack(const Tensor& tensor, int input_idx, bool& is_packed) override;
#endif
Status Compute(OpKernelContext* context) const override;
~DynamicQuantizeLSTM() override = default;
private:
#ifdef MLAS_SUPPORTS_PACKED_GEMM_U8X8
Status TryPackWeights(const Tensor& weights, PackedWeights& packed_weights, bool& is_packed, bool& is_weight_signed);
#endif
template <typename T>
Status ComputeImpl(OpKernelContext& context) const;
PackedWeights packed_W_;
PackedWeights packed_R_;
bool is_W_signed_;
bool is_R_signed_;
};
#ifdef MLAS_SUPPORTS_PACKED_GEMM_U8X8
Status DynamicQuantizeLSTM::TryPackWeights(const Tensor& weights, PackedWeights& packed_weights, bool& is_packed, bool& is_weight_signed) {
const auto& shape = weights.Shape();
if (shape.NumDimensions() != 3) {
return Status::OK();
}
// weights: [num_directions, input_size, 4*hidden_size]
// recurrence weights: [num_directions, hidden_size, 4*hidden_size]
const size_t K = static_cast<size_t>(shape[1]);
const size_t N = static_cast<size_t>(shape[2]);
if ((shape[0] != num_directions_) || (N != static_cast<size_t>(hidden_size_ * 4))) {
return Status::OK();
}
is_weight_signed = weights.IsDataType<int8_t>();
const size_t packed_weights_size = MlasGemmPackBSize(N, K, is_weight_signed);
if (packed_weights_size == 0) {
return Status::OK();
}
auto alloc = Info().GetAllocator(0, OrtMemTypeDefault);
auto* packed_weights_data = alloc->Alloc(SafeInt<size_t>(packed_weights_size) * num_directions_);
packed_weights.buffer_ = BufferUniquePtr(packed_weights_data, BufferDeleter(alloc));
packed_weights.weights_size_ = packed_weights_size;
packed_weights.shape_ = shape;
const auto* weights_data = static_cast<const uint8_t*>(weights.DataRaw());
for (int i = 0; i < num_directions_; i++) {
MlasGemmPackB(N, K, weights_data, N, is_weight_signed, packed_weights_data);
packed_weights_data = static_cast<uint8_t*>(packed_weights_data) + packed_weights_size;
weights_data += N * K;
}
is_packed = true;
return Status::OK();
}
Status DynamicQuantizeLSTM::PrePack(const Tensor& tensor, int input_idx, bool& is_packed) {
is_packed = false;
if (input_idx == 1) {
return TryPackWeights(tensor, packed_W_, is_packed, is_W_signed_);
} else if (input_idx == 2) {
return TryPackWeights(tensor, packed_R_, is_packed, is_R_signed_);
}
return Status::OK();
}
#endif
#define WeightCheck(weight_shape, weight_name) \
if (weight_shape.NumDimensions() != 1 && weight_shape.NumDimensions() != 2 || \
weight_shape.NumDimensions() == 2 && weight_shape[1] != hidden_size_ * 4 || \
weight_shape[0] != num_directions_) { \
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, \
"Input ", #weight_name, " must have shape {", num_directions_, "} for per-tensor/layer quantization or shape {", \
num_directions_, ", 4*", hidden_size_, "} for per-channel quantization. Actual:", weight_shape); \
}
#define ZeroPointCheck(w_zp, zp_shape, is_W_signed, weight_name) \
if (zp_shape.NumDimensions() == 2) { \
const int64_t zp_size = zp_shape.Size(); \
const uint8_t* w_zp_data = static_cast<const uint8_t*>(w_zp->DataRaw()); \
if (is_W_signed) { \
for (int64_t i = 0; i < zp_size; i++) { \
if (w_zp_data[i] != 0) { \
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "DynamicQuantizeLSTM : ", #weight_name, "Weight zero point must be zero"); \
} \
} \
} else { \
const uint8_t W_zero_point_value = w_zp_data[0]; \
for (int64_t i = 1; i < zp_size; i++) { \
if (w_zp_data[i] != W_zero_point_value) { \
return ORT_MAKE_STATUS(ONNXRUNTIME, INVALID_ARGUMENT, "DynamicQuantizeLSTM : ", #weight_name, "Weight point must be constant"); \
} \
} \
} \
}
Status DynamicQuantizeLSTM::Compute(OpKernelContext* context) const {
// weights. [num_directions, input_size, 4*hidden_size]
const Tensor* W = packed_W_.buffer_ ? nullptr : context->Input<Tensor>(1);
// recurrence weights. [num_directionshidden_size, 4*hidden_size]
const Tensor* R = packed_R_.buffer_ ? nullptr : context->Input<Tensor>(2);
const auto& W_shape = (W != nullptr) ? W->Shape() : packed_W_.shape_;
const auto& R_shape = (R != nullptr) ? R->Shape() : packed_R_.shape_;
const Tensor* w_scale = context->Input<Tensor>(8);
const Tensor* w_zp = context->Input<Tensor>(9);
const Tensor* r_scale = context->Input<Tensor>(10);
const Tensor* r_zp = context->Input<Tensor>(11);
const TensorShape& W_zp_shape = w_zp->Shape();
const TensorShape& R_zp_shape = w_zp->Shape();
const TensorShape& W_scale_shape = w_scale->Shape();
const TensorShape& R_scale_shape = r_scale->Shape();
WeightCheck(W_zp_shape, W_zero_point);
WeightCheck(R_zp_shape, R_zero_point);
WeightCheck(W_scale_shape, W_scale);
WeightCheck(W_scale_shape, R_scale);
const bool is_W_signed = (W != nullptr) ? W->IsDataType<int8_t>() : is_W_signed_;
const bool is_R_signed = (R != nullptr) ? R->IsDataType<int8_t>() : is_R_signed_;
ZeroPointCheck(w_zp, W_zp_shape, is_W_signed, Input);
ZeroPointCheck(r_zp, R_zp_shape, is_R_signed, Recurrent);
size_t W_scale_size = W_scale_shape.NumDimensions() == 2 ? W_scale_shape[1] : 1;
size_t R_scale_size = R_scale_shape.NumDimensions() == 2 ? R_scale_shape[1] : 1;
QuantizationParameter quant_para_W_1(w_scale->Data<float>(),
static_cast<const uint8_t*>(w_zp->DataRaw()),
is_W_signed,
W_scale_size);
QuantizationParameter quant_para_R_1(r_scale->Data<float>(),
static_cast<const uint8_t*>(r_zp->DataRaw()),
is_R_signed,
R_scale_size);
const uint8_t* W_data = W != nullptr ? static_cast<const uint8_t*>(W->DataRaw()) : nullptr;
const uint8_t* R_data = R != nullptr ? static_cast<const uint8_t*>(R->DataRaw()) : nullptr;
// spans for first direction
const size_t W_size_per_direction = W_shape[1] * W_shape[2];
const size_t R_size_per_direction = R_shape[1] * R_shape[2];
GemmWeights<uint8_t> W_1(0, W_data, W_size_per_direction, packed_W_, &quant_para_W_1);
GemmWeights<uint8_t> R_1(0, R_data, R_size_per_direction, packed_R_, &quant_para_R_1);
GemmWeights<uint8_t> W_2;
GemmWeights<uint8_t> R_2;
QuantizationParameter quant_para_W_2(quant_para_W_1);
QuantizationParameter quant_para_R_2(quant_para_R_1);
if (direction_ == Direction::kBidirectional) {
quant_para_W_2.scale += W_scale_size;
quant_para_R_2.scale += R_scale_size;
quant_para_W_2.zero_point += W_scale_size; // zero_point and scale have same size
quant_para_R_2.zero_point += R_scale_size; // zero_point and scale have same size
W_2.Init(1, W_data, W_size_per_direction, packed_W_, &quant_para_W_2);
R_2.Init(1, R_data, R_size_per_direction, packed_R_, &quant_para_R_2);
}
return LSTMBase::ComputeImpl<float, uint8_t>(*context, W_1, W_2, R_1, R_2);
}
ONNX_OPERATOR_TYPED_KERNEL_EX(
DynamicQuantizeLSTM,
kMSDomain,
1,
float,
kCpuExecutionProvider,
KernelDefBuilder()
.TypeConstraint("T", DataTypeImpl::GetTensorType<float>())
.TypeConstraint("T1", DataTypeImpl::GetTensorType<int32_t>())
.TypeConstraint("T2", {DataTypeImpl::GetTensorType<uint8_t>(), DataTypeImpl::GetTensorType<int8_t>()}),
DynamicQuantizeLSTM);
} // namespace contrib
} // namespace onnxruntime
| 49.945813 | 141 | 0.551336 | [
"shape"
] |
6a89617981348484498dd42f898e5911e3369933 | 1,839 | cpp | C++ | source/plc/src/document/STATEMENT.cpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | source/plc/src/document/STATEMENT.cpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | source/plc/src/document/STATEMENT.cpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | null | null | null | // This file was generated using Parlex's cpp_generator
#include "STATEMENT.hpp"
#include "plange_grammar.hpp"
#include "parlex/detail/document.hpp"
#include "ASSIGNMENT_CHAIN.hpp"
#include "BREAK.hpp"
#include "CONTINUE.hpp"
#include "DEFINITION.hpp"
#include "DO.hpp"
#include "EXPRESSION.hpp"
#include "FOR.hpp"
#include "FOR_COLLECTION.hpp"
#include "FREE.hpp"
#include "IC.hpp"
#include "IMPORT.hpp"
#include "LOCK.hpp"
#include "LOOP.hpp"
#include "READ_LOCK.hpp"
#include "RETURN.hpp"
#include "THROW.hpp"
#include "TRY.hpp"
#include "TYPE_CONSTRAINT.hpp"
#include "USING.hpp"
#include "WRITE_LOCK.hpp"
plc::STATEMENT plc::STATEMENT::build(parlex::detail::ast_node const & n) {
static auto const * b = state_machine().behavior;
parlex::detail::document::walk w{ n.children.cbegin(), n.children.cend() };
auto const & children = b->children;
auto v0 = parlex::detail::document::element<std::variant<
erased<ASSIGNMENT_CHAIN>,
erased<BREAK>,
erased<CONTINUE>,
erased<DEFINITION>,
erased<DO>,
erased<EXPRESSION>,
erased<FOR>,
erased<FOR_COLLECTION>,
erased<FREE>,
erased<IMPORT>,
erased<LOCK>,
erased<LOOP>,
erased<READ_LOCK>,
erased<RETURN>,
erased<THROW>,
erased<TRY>,
erased<TYPE_CONSTRAINT>,
erased<WRITE_LOCK>,
erased<USING>
>>::build(&*children[0], w);
auto v1 = parlex::detail::document::element<std::vector<erased<IC>>>::build(&*children[1], w);
auto v2 = parlex::detail::document::element<parlex::detail::document::text<literal_0x3B_t>>::build(&*children[2], w);
return STATEMENT(std::move(v0), std::move(v1), std::move(v2));
}
parlex::detail::state_machine const & plc::STATEMENT::state_machine() {
static auto const & result = *static_cast<parlex::detail::state_machine const *>(&plange_grammar::get().get_recognizer(plange_grammar::get().STATEMENT));
return result;
}
| 28.734375 | 154 | 0.717781 | [
"vector"
] |
6a8a854044a7df077f13df0bd0d380120d4d0647 | 7,926 | cpp | C++ | sources/enduro2d/high/world.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | null | null | null | sources/enduro2d/high/world.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | null | null | null | sources/enduro2d/high/world.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | null | null | null | /*******************************************************************************
* This file is part of the "Enduro2D"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#include <enduro2d/high/world.hpp>
#include <enduro2d/high/components/actor.hpp>
#include <enduro2d/high/components/behaviour.hpp>
#include <enduro2d/high/components/disabled.hpp>
namespace
{
using namespace e2d;
class gobject_state final : public gobject::state {
private:
enum flag_masks : u32 {
fm_destroyed = 1u << 0,
fm_invalided = 1u << 1,
};
public:
gobject_state(world& w, ecs::entity e)
: world_(w)
, entity_(std::move(e)) {}
void mark_destroyed() noexcept {
math::set_flags_inplace(flags_, fm_destroyed);
}
void mark_invalided() noexcept {
math::set_flags_inplace(flags_, fm_invalided);
}
public:
void destroy() noexcept final {
gobject go{this};
world_.destroy_instance(go);
}
bool destroyed() const noexcept final {
return math::check_any_flags(flags_, fm_destroyed);
}
bool invalided() const noexcept final {
return math::check_any_flags(flags_, fm_invalided);
}
ecs::entity raw_entity() noexcept final {
E2D_ASSERT(!invalided());
return entity_;
}
ecs::const_entity raw_entity() const noexcept final {
E2D_ASSERT(!invalided());
return entity_;
}
private:
world& world_;
ecs::entity entity_;
u32 flags_{0u};
};
}
namespace
{
using namespace e2d;
void delete_instance(const gobject& inst) noexcept {
gcomponent<actor> inst_a{inst};
auto inst_n = inst_a ? inst_a->node() : nullptr;
if ( inst_n ) {
inst_n->remove_from_parent();
while ( const node_iptr& child = inst_n->first_child() ) {
delete_instance(child->owner());
}
}
if ( inst ) {
auto inst_g = dynamic_pointer_cast<gobject_state>(inst.internal_state());
inst_g->raw_entity().destroy();
inst_g->mark_destroyed();
inst_g->mark_invalided();
}
}
gobject new_instance(world& world, const prefab& root_prefab) {
ecs::entity ent = world.registry().create_entity(root_prefab.prototype());
auto ent_defer = make_error_defer([&ent](){
ent.destroy();
});
gobject root_i(make_intrusive<gobject_state>(world, ent));
E2D_ERROR_DEFER([&root_i](){
delete_instance(root_i);
});
ent_defer.dismiss();
{
gcomponent<actor> root_a{root_i};
node_iptr new_root_node = node::create(root_i);
if ( root_a && root_a->node() ) {
new_root_node->transform(root_a->node()->transform());
}
root_a.ensure().node(new_root_node);
}
{
gcomponent<behaviour> root_b{root_i};
if ( root_b && root_b->script() ) {
const behaviours::fill_result r = behaviours::fill_meta_table(*root_b);
if ( r == behaviours::fill_result::failed ) {
root_i.component<disabled<behaviour>>().ensure();
}
}
}
for ( const prefab& child_prefab : root_prefab.children() ) {
gobject child_i = new_instance(world, child_prefab);
E2D_ERROR_DEFER([&child_i](){
delete_instance(child_i);
});
gcomponent<actor> root_a{root_i};
gcomponent<actor> child_a{child_i};
root_a->node()->add_child(child_a->node());
}
return root_i;
}
void shutdown_instance(gobject& inst) noexcept {
gcomponent<actor> inst_a = inst.component<actor>();
if ( !inst_a ) {
return;
}
nodes::for_extracted_components_from_children<behaviour>(
inst_a->node(),
[](gcomponent<behaviour>& inst_b){
behaviours::call_meta_method(
*inst_b,
"on_shutdown",
inst_b.owner());
}, nodes::options().recursive(true).include_root(true));
}
void start_instance(gobject& inst) {
gcomponent<actor> inst_a = inst.component<actor>();
if ( !inst_a ) {
return;
}
nodes::for_extracted_components_from_children<behaviour>(
inst_a->node(),
[&inst](gcomponent<behaviour>& inst_b){
const auto result = behaviours::call_meta_method(
*inst_b,
"on_start",
inst_b.owner());
if ( result == behaviours::call_result::failed ) {
inst.component<disabled<behaviour>>().assign();
}
}, nodes::options().recursive(true).include_root(true));
}
}
namespace e2d
{
world::~world() noexcept = default;
ecs::registry& world::registry() noexcept {
return registry_;
}
const ecs::registry& world::registry() const noexcept {
return registry_;
}
gobject world::instantiate() {
return instantiate(prefab(), nullptr);
}
gobject world::instantiate(const t2f& transform) {
return instantiate(prefab(), nullptr, transform);
}
gobject world::instantiate(const node_iptr& parent) {
return instantiate(prefab(), parent);
}
gobject world::instantiate(const node_iptr& parent, const t2f& transform) {
return instantiate(prefab(), parent, transform);
}
gobject world::instantiate(const prefab& prefab) {
return instantiate(prefab, nullptr);
}
gobject world::instantiate(const prefab& prefab, const t2f& transform) {
return instantiate(prefab, nullptr, transform);
}
gobject world::instantiate(const prefab& prefab, const node_iptr& parent) {
E2D_PROFILER_SCOPE("world.instantiate");
gobject inst = new_instance(*this, prefab);
E2D_ERROR_DEFER([inst](){
delete_instance(inst);
});
if ( const node_iptr& node = inst.component<actor>()->node() ) {
if ( parent ) {
parent->add_child(node);
}
}
start_instance(inst);
return inst;
}
gobject world::instantiate(const prefab& prefab, const node_iptr& parent, const t2f& transform) {
E2D_PROFILER_SCOPE("world.instantiate");
gobject inst = new_instance(*this, prefab);
E2D_ERROR_DEFER([inst](){
delete_instance(inst);
});
if ( const node_iptr& node = inst.component<actor>()->node() ) {
node->transform(transform);
if ( parent ) {
parent->add_child(node);
}
}
start_instance(inst);
return inst;
}
void world::destroy_instance(gobject inst) noexcept {
auto gstate = inst
? dynamic_pointer_cast<gobject_state>(inst.internal_state())
: nullptr;
if ( gstate && !gstate->destroyed() && !gstate->invalided() ) {
gstate->mark_destroyed();
destroying_states_.push_back(*gstate);
}
}
void world::finalize_instances() noexcept {
E2D_PROFILER_SCOPE("world.finalize_instances");
while ( !destroying_states_.empty() ) {
gobject inst{&destroying_states_.front()};
destroying_states_.pop_front();
shutdown_instance(inst);
delete_instance(inst);
}
}
}
| 30.367816 | 101 | 0.551981 | [
"transform"
] |
6a8acc0770a1bca051d598ba8f478aa8b7994202 | 2,506 | hpp | C++ | inference-engine/thirdparty/clDNN/api/mutable_data.hpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2022-02-10T08:05:09.000Z | 2022-02-10T08:05:09.000Z | inference-engine/thirdparty/clDNN/api/mutable_data.hpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 40 | 2020-12-04T07:46:57.000Z | 2022-02-21T13:04:40.000Z | inference-engine/thirdparty/clDNN/api/mutable_data.hpp | JOCh1958/openvino | 070201feeec5550b7cf8ec5a0ffd72dc879750be | [
"Apache-2.0"
] | 1 | 2021-08-18T14:29:37.000Z | 2021-08-18T14:29:37.000Z | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "primitive.hpp"
#include "memory.hpp"
#include <vector>
namespace cldnn {
/// @addtogroup cpp_api C++ API
/// @{
/// @addtogroup cpp_topology Network Topology
/// @{
/// @addtogroup cpp_primitives Primitives
/// @{
/// @brief Provides mutable data.
/// @details This primitive allows to pass data which can be written to during training.
/// For example, weights and biases for scoring networks.
/// This primitive can be also set as other primitive's output. In this case the underlying buffer will be the same in mutable_data and preceding primitive.
struct mutable_data : public primitive_base<mutable_data> {
CLDNN_DECLARE_PRIMITIVE(mutable_data)
/// @brief Enum type to specify function for data filling.
enum filler_type { no_fill, zero, one, xavier };
/// @brief Constructs mutable_data primitive.
/// @param id This primitive id.
/// @param mem @ref memory object which contains data.
/// @param filler_type @ref data filling function, default is zero
/// @note If memory is attached by memory::attach(), the attached buffer should be valid till network build.
mutable_data(const primitive_id& id, const memory& mem, filler_type fill_type = filler_type::no_fill)
: primitive_base(id, {}, padding()), mem(mem), fill_type(fill_type) {}
/// @brief Constructs mutable_data primitive with inputs.
/// @param id This primitive id.
/// @param input Vector of input primitives ids.
/// @param mem @ref memory object which contains data.
/// @note If memory is attached by memory::attach(), the attached buffer should be valid till network build.
/// @param filler_type @ref data filling function, default is zero
mutable_data(const primitive_id& id,
const std::vector<primitive_id>& input,
const memory& mem,
filler_type fill_type = filler_type::no_fill)
: primitive_base(id, {input}, padding()), mem(mem), fill_type(fill_type) {}
/// @brief @ref memory object which contains data.
/// @note If memory is attached by memory::attach(), the attached buffer should be valid till network build.
memory mem;
/// @brief Specifies function which will be used to fill weights.
filler_type fill_type;
};
/// @}
/// @}
/// @}
} // namespace cldnn
| 41.766667 | 156 | 0.666002 | [
"object",
"vector"
] |
6a8cb6fc641a3f8d52bf8b1a4782327ccbf4d3f8 | 11,909 | cpp | C++ | src/gct/generate_blas.cpp | Fadis/gct | bde211f9336e945e4db21f5abb4ce01dcad78049 | [
"MIT"
] | 1 | 2022-03-03T09:27:09.000Z | 2022-03-03T09:27:09.000Z | src/gct/generate_blas.cpp | Fadis/gct | bde211f9336e945e4db21f5abb4ce01dcad78049 | [
"MIT"
] | 1 | 2021-12-02T03:45:45.000Z | 2021-12-03T23:44:37.000Z | src/gct/generate_blas.cpp | Fadis/gct | bde211f9336e945e4db21f5abb4ce01dcad78049 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_set>
#include <nlohmann/json.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <glm/ext/matrix_clip_space.hpp>
#include <glm/gtx/string_cast.hpp>
#include <gct/get_extensions.hpp>
#include <gct/instance.hpp>
#include <gct/queue.hpp>
#include <gct/device.hpp>
#include <gct/allocator.hpp>
#include <gct/device_create_info.hpp>
#include <gct/image_create_info.hpp>
#include <gct/wait_for_sync.hpp>
#include <gct/gltf.hpp>
#include <gct/device_address.hpp>
#include <gct/acceleration_structure.hpp>
#include <gct/acceleration_structure_geometry.hpp>
#include <gct/acceleration_structure_build_geometry_info.hpp>
#include <gct/acceleration_structure_geometry_triangles_data.hpp>
namespace gct::gltf {
std::shared_ptr< acceleration_structure_t >
generate_blas(
const std::shared_ptr< buffer_t > &vertex,
std::uint32_t vertex_offset,
std::uint32_t vertex_count,
const pipeline_vertex_input_state_create_info_t &vistat_,
command_buffer_recorder_t &rec,
const std::shared_ptr< allocator_t > &allocator
) {
auto vistat = vistat_;
vistat.rebuild_chain();
auto device = allocator->get_factory();
glm::mat4x3 trans( 1.0f );
auto ident_matrix = rec.load_buffer(
allocator,
reinterpret_cast< const void* >( &trans ),
sizeof( glm::mat4x3 ),
vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR
);
auto ident_matrix_addr = ident_matrix->get_address();
rec.barrier(
vk::AccessFlagBits::eTransferWrite,
vk::AccessFlagBits::eAccelerationStructureReadKHR,
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eAccelerationStructureBuildKHR,
vk::DependencyFlagBits( 0 ),
{ ident_matrix },
{}
);
auto triangles =
gct::acceleration_structure_geometry_triangles_data_t();
{
const auto buffer_address = vertex->get_address();
const auto buffer_offset = vertex_offset;
triangles
.set_vertex_data(
buffer_address + buffer_offset
);
}
const auto vbbegin = vistat.get_basic().pVertexBindingDescriptions;
const auto vbend = std::next( vistat.get_basic().pVertexBindingDescriptions, vistat.get_basic().vertexBindingDescriptionCount );
const auto vabegin = vistat.get_basic().pVertexAttributeDescriptions;
const auto vaend = std::next( vistat.get_basic().pVertexAttributeDescriptions, vistat.get_basic().vertexAttributeDescriptionCount );
const auto attribute = std::find_if(
vabegin,
vaend,
[]( const auto &v ) {
return v.binding == 0u;
}
);
if( attribute == vaend ) {
std::cout << "oops1" << std::endl;
abort();
}
const auto binding = std::find_if(
vbbegin,
vbend,
[]( const auto &v ) {
return v.binding == 0u;
}
);
if( binding == vbend ) {
std::cout << "oops2" << std::endl;
abort();
}
auto asbgi = gct::acceleration_structure_build_geometry_info_t()
.set_basic(
vk::AccelerationStructureBuildGeometryInfoKHR()
.setType(
vk::AccelerationStructureTypeKHR::eBottomLevel
)
.setFlags(
vk::BuildAccelerationStructureFlagBitsKHR::eAllowUpdate
)
.setMode(
vk::BuildAccelerationStructureModeKHR::eBuild
)
)
.add_geometry(
gct::acceleration_structure_geometry_t()
.set_triangle(
triangles
.set_basic(
vk::AccelerationStructureGeometryTrianglesDataKHR()
.setIndexType( vk::IndexType::eNoneKHR )
.setVertexFormat( attribute->format )
.setVertexStride( binding->stride )
.setMaxVertex( vertex_count )
)
.set_transform_data(
ident_matrix_addr
)
)
);
std::vector< std::uint32_t > max_primitive_count{ vertex_count / 3u };
auto size = device->get_acceleration_structure_build_size(
vk::AccelerationStructureBuildTypeKHR::eDevice,
asbgi,
max_primitive_count
);
auto scratch_buffer_addr = allocator->create_buffer(
gct::buffer_create_info_t()
.set_basic(
vk::BufferCreateInfo()
.setSize( size.get_basic().buildScratchSize )
.setUsage(
vk::BufferUsageFlagBits::eStorageBuffer|
vk::BufferUsageFlagBits::eShaderDeviceAddress
)
),
VMA_MEMORY_USAGE_GPU_ONLY
)->get_address();
auto asb = allocator->create_buffer(
gct::buffer_create_info_t()
.set_basic(
vk::BufferCreateInfo()
.setSize( size.get_basic().accelerationStructureSize )
.setUsage(
vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR|
vk::BufferUsageFlagBits::eShaderDeviceAddress
)
),
VMA_MEMORY_USAGE_GPU_ONLY
);
auto as = asb->create_acceleration_structure(
vk::AccelerationStructureTypeKHR::eBottomLevel
);
asbgi
.set_src( as )
.set_dst( as )
.set_scratch( scratch_buffer_addr )
.rebuild_chain();
rec.build_acceleration_structure(
asbgi,
std::vector< vk::AccelerationStructureBuildRangeInfoKHR >{
vk::AccelerationStructureBuildRangeInfoKHR()
.setPrimitiveCount( vertex_count / 3u )
}
);
return as;
}
std::tuple<
std::vector< std::shared_ptr< acceleration_structure_t > >,
std::vector< std::shared_ptr< gct::buffer_t > >,
std::vector< std::uint32_t >
>
generate_blas(
const document_t &doc,
command_buffer_recorder_t &rec,
const std::shared_ptr< allocator_t > &allocator
) {
auto device = allocator->get_factory();
std::vector< std::shared_ptr< gct::acceleration_structure_t > > as;
std::vector< std::shared_ptr< gct::buffer_t > > as_buf;
std::vector< std::uint32_t > mesh2prim;
glm::mat4x3 trans( 1.0f );
vk::TransformMatrixKHR transformMatrix{
std::array< std::array< float, 4 >, 3 >{
std::array< float, 4 >{ 1.0f, 0.0f, 0.0f, 0.0f },
std::array< float, 4 >{ 0.0f, 1.0f, 0.0f, 0.0f },
std::array< float, 4 >{ 0.0f, 0.0f, 1.0f, 0.0f }
}
};
auto ident_matrix = rec.load_buffer(
allocator,
reinterpret_cast< const void* >( &transformMatrix ),
sizeof( vk::TransformMatrixKHR ),
vk::BufferUsageFlagBits::eAccelerationStructureBuildInputReadOnlyKHR
);
auto ident_matrix_addr = ident_matrix->get_address();
rec.barrier(
vk::AccessFlagBits::eTransferWrite,
vk::AccessFlagBits::eAccelerationStructureReadKHR,
vk::PipelineStageFlagBits::eTransfer,
vk::PipelineStageFlagBits::eAccelerationStructureBuildKHR,
vk::DependencyFlagBits( 0 ),
{ ident_matrix },
{}
);
for( const auto &m: doc.mesh ) {
mesh2prim.push_back( as.size() );
for( const auto &p: m.primitive ) {
auto triangles =
gct::acceleration_structure_geometry_triangles_data_t();
if( p.indexed ) {
const auto buffer_address = doc.buffer[ p.index_buffer.index ]->get_address();
const auto buffer_offset = p.index_buffer.offset;
triangles
.set_index_data(
buffer_address + buffer_offset
);
}
{
const auto pos = p.vertex_buffer.find( 0u );
if( pos == p.vertex_buffer.end() ) {
std::cout << "oops3" << std::endl;
abort();
}
const auto buffer_address = doc.buffer[ pos->second.index ]->get_address();
const auto buffer_offset = pos->second.offset;
triangles
.set_vertex_data(
buffer_address + buffer_offset
);
}
const auto attribute = std::find_if(
p.vertex_input_attribute.begin(),
p.vertex_input_attribute.end(),
[]( const auto &v ) {
return v.binding == 0u;
}
);
if( attribute == p.vertex_input_attribute.end() ) {
std::cout << "oops1" << std::endl;
abort();
}
const auto binding = std::find_if(
p.vertex_input_binding.begin(),
p.vertex_input_binding.end(),
[]( const auto &v ) {
return v.binding == 0u;
}
);
if( binding == p.vertex_input_binding.end() ) {
std::cout << "oops2" << std::endl;
abort();
}
auto asbgi = gct::acceleration_structure_build_geometry_info_t()
.set_basic(
vk::AccelerationStructureBuildGeometryInfoKHR()
.setType(
vk::AccelerationStructureTypeKHR::eBottomLevel
)
.setFlags(
vk::BuildAccelerationStructureFlagBitsKHR::ePreferFastTrace
)
.setMode(
vk::BuildAccelerationStructureModeKHR::eBuild
)
)
.add_geometry(
gct::acceleration_structure_geometry_t()
.set_triangle(
triangles
.set_basic(
vk::AccelerationStructureGeometryTrianglesDataKHR()
.setIndexType( p.index_buffer_type )
.setVertexFormat( attribute->format )
.setVertexStride( binding->stride )
.setMaxVertex( p.count )
)
.set_transform_data(
ident_matrix_addr
)
)
);
std::vector< std::uint32_t > max_primitive_count{ p.count / 3u };
auto size = device->get_acceleration_structure_build_size(
vk::AccelerationStructureBuildTypeKHR::eDevice,
asbgi,
max_primitive_count
);
auto scratch_buffer_addr = allocator->create_buffer(
gct::buffer_create_info_t()
.set_basic(
vk::BufferCreateInfo()
.setSize( size.get_basic().buildScratchSize )
.setUsage(
vk::BufferUsageFlagBits::eStorageBuffer|
vk::BufferUsageFlagBits::eShaderDeviceAddress
)
),
VMA_MEMORY_USAGE_GPU_ONLY
)->get_address();
auto asb = allocator->create_buffer(
gct::buffer_create_info_t()
.set_basic(
vk::BufferCreateInfo()
.setSize( size.get_basic().accelerationStructureSize )
.setUsage(
vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR|
vk::BufferUsageFlagBits::eShaderDeviceAddress
)
),
VMA_MEMORY_USAGE_GPU_ONLY
);
as_buf.push_back( asb );
as.push_back(
asb->create_acceleration_structure(
vk::AccelerationStructureTypeKHR::eBottomLevel
)
);
asbgi
.set_src( as.back() )
.set_dst( as.back() )
.set_scratch( scratch_buffer_addr )
.rebuild_chain();
rec.build_acceleration_structure(
asbgi,
std::vector< vk::AccelerationStructureBuildRangeInfoKHR >{
vk::AccelerationStructureBuildRangeInfoKHR()
.setPrimitiveCount( p.count / 3u )
}
);
}
}
rec.barrier(
vk::AccessFlagBits::eAccelerationStructureWriteKHR,
vk::AccessFlagBits::eAccelerationStructureReadKHR,
vk::PipelineStageFlagBits::eAccelerationStructureBuildKHR,
vk::PipelineStageFlagBits::eAccelerationStructureBuildKHR,
vk::DependencyFlagBits( 0 ),
as_buf,
{}
);
mesh2prim.push_back( as.size() );
return std::make_tuple( as, as_buf, mesh2prim );
}
}
| 34.518841 | 136 | 0.601058 | [
"mesh",
"vector"
] |
6a8e87fb81c74bfe72135be6ce3c31834214bfa5 | 496 | cpp | C++ | IO/FILE_READERS/test_punreader.cpp | gitter-badger/QC_Tools | 5ce3ec665d5a11c93257309b016f5a5458709005 | [
"MIT"
] | null | null | null | IO/FILE_READERS/test_punreader.cpp | gitter-badger/QC_Tools | 5ce3ec665d5a11c93257309b016f5a5458709005 | [
"MIT"
] | null | null | null | IO/FILE_READERS/test_punreader.cpp | gitter-badger/QC_Tools | 5ce3ec665d5a11c93257309b016f5a5458709005 | [
"MIT"
] | null | null | null |
#include <string>
#include <vector>
#include <iostream>
#include <cassert>
#include "punreader.hpp"
using namespace std;
int main(void){
cerr << "Testing: PunReader Constructor" << endl;
{
PunReader pr("file.pun");
}
cerr << "Testing: PunReader read" << endl;
{
PunReader pr("../../GAUSSIANFILES/90_unordered/90_pair.pun");
pr.read();
auto m = pr.getCoefsMatrix("Alpha");
assert(m->get_rows() == 92);
assert(pr.restrictedShell());
}
return 0;
}
| 17.714286 | 65 | 0.620968 | [
"vector"
] |
6a93a140a472724b2682e220bf65f8db9107b635 | 16,198 | cpp | C++ | src/engine/core/menu/ControlSettings.cpp | gerstrong/Commander-Genius | 7afb8701aba1c370d54af8c93372e9849fd6efe1 | [
"X11"
] | 137 | 2015-01-01T21:04:51.000Z | 2022-03-30T01:41:10.000Z | src/engine/core/menu/ControlSettings.cpp | gerstrong/Commander-Genius | 7afb8701aba1c370d54af8c93372e9849fd6efe1 | [
"X11"
] | 154 | 2015-01-01T16:34:39.000Z | 2022-01-28T14:14:45.000Z | src/engine/core/menu/ControlSettings.cpp | gerstrong/Commander-Genius | 7afb8701aba1c370d54af8c93372e9849fd6efe1 | [
"X11"
] | 35 | 2015-03-24T02:20:54.000Z | 2021-05-13T11:44:22.000Z | /*
* CControlsettings.cpp
*
* Created on: 28.11.2009
* Author: gerstrong
*/
#include "fileio/CConfiguration.h"
#include <base/utils/StringUtils.h>
#include "SelectionMenu.h"
#include "ControlSettings.h"
#include "engine/core/CBehaviorEngine.h"
#include <base/CInput.h>
#include "widgets/InputText.h"
#include <algorithm>
static std::vector<std::string> defaultPresets =
{
"XInput",
"DInput",
"Keyboard",
"ClonePadA",
"ClonePadB",
"ClonePadC",
"ClonePadD",
"ClonePadE"
};
/**
* \brief This sets the default settings for a classic gameplay
*/
class ReadInputEvent : public InvokeFunctorEvent
{
public:
ReadInputEvent( const int selPlayer,
const InpCmd command,
const std::string &commandName ) :
mSelPlayer(selPlayer),
mCommand(command),
mCommandName(commandName)
{}
void setButtonPtr(std::shared_ptr<GsButton> button)
{
mpButton = button;
}
void operator()() const
{
gInput.setupNewEvent(Uint8(mSelPlayer-1),
mCommand);
const std::string buf = mCommandName;
mpButton->setText(buf + "=Reading=");
}
int mSelPlayer;
InpCmd mCommand;
const std::string mCommandName;
std::shared_ptr<GsButton> mpButton;
};
CControlsettings::CControlsettings(const int selectedPlayer ,
const Style style) :
GameMenu( GsRect<float>(0.1f, 0.25f, 0.8f, 0.5f), style ),
mSelectedPlayer(selectedPlayer)
{
mpMenuDialog->add(
new GameButton( "Load Preset",
[this]()
{
gEventManager.add( new OpenMenuEvent(
new CControlSettingsLoadPreset(mSelectedPlayer,
this->getStyle()) ) );
},
style ) );
mpMenuDialog->add(
new GameButton( "Movement",
[this]()
{
gEventManager.add( new OpenMenuEvent(
new CControlSettingsMovement(mSelectedPlayer,
this->getStyle()) ) );
},
style ) );
mpMenuDialog->add(
new GameButton( "Diagonal",
[this]()
{
gEventManager.add( new OpenMenuEvent(
new CControlSettingsMoveDiag(mSelectedPlayer,
this->getStyle()) ) );
},
style ) );
mpMenuDialog->add(
new GameButton( "Action",
[this]()
{
gEventManager.add( new OpenMenuEvent(
new CControlSettingsGameplayActions(mSelectedPlayer,
this->getStyle()) ) );
},
style ) );
mpMenuDialog->add(
new GameButton( "Misc",
[this]()
{
gEventManager.add( new OpenMenuEvent(
new CControlSettingsMisc(mSelectedPlayer,
this->getStyle()) ) );
},
style ) );
mpTwoButtonSwitch =
mpMenuDialog->add( new Switch( "Two Button Fire", style ) );
mpTwoButtonSwitch->enable(gInput.getTwoButtonFiring(mSelectedPlayer-1));
mpAnalogSwitch =
mpMenuDialog->add( new Switch( "Analog Movement", style ) );
mpAnalogSwitch->enable(gInput.isAnalog(mSelectedPlayer-1));
mpSuperPogoSwitch =
mpMenuDialog->add( new Switch( "Super Pogo", style ) );
mpSuperPogoSwitch->enable(gInput.SuperPogo(mSelectedPlayer-1));
mpImpPogoSwitch =
mpMenuDialog->add( new Switch( "Impossible Pogo", style ) );
mpImpPogoSwitch->enable(gInput.ImpossiblePogo(mSelectedPlayer-1));
mpAutoGunSwitch =
mpMenuDialog->add( new Switch( "Auto Gun", style ) );
mpAutoGunSwitch->enable(gInput.AutoGun(mSelectedPlayer-1));
mpMenuDialog->add(
new GameButton( "Save Preset",
[this]()
{
gEventManager.add( new OpenMenuEvent(
new CControlSettingsSavePreset(mSelectedPlayer,
this->getStyle()) ) );
},
style ) );
setMenuLabel("KEYBMENULABEL");
mpMenuDialog->fit();
select(1);
}
void CControlsettings::refresh()
{}
void CControlsettings::release()
{
gInput.setTwoButtonFiring(mSelectedPlayer-1, mpTwoButtonSwitch->isEnabled() );
gInput.enableAnalog(mSelectedPlayer-1, mpAnalogSwitch->isEnabled() );
gInput.setSuperPogo(mSelectedPlayer-1, mpSuperPogoSwitch->isEnabled() );
gInput.setImpossiblePogo(mSelectedPlayer-1, mpImpPogoSwitch->isEnabled() );
gInput.setAutoGun(mSelectedPlayer-1, mpAutoGunSwitch->isEnabled() );
gInput.saveControlconfig("");
}
// Movements Parts of the Control Settings
CControlSettingsBase::
CControlSettingsBase(const int selectedPlayer,
const Style style) :
GameMenu(
GsRect<float>(0.01f,
(1.0f-((MAX_COMMANDS/2.0f)+2)*0.06f)*0.5f,
0.98f,
(MAX_COMMANDS/2.0f+2)*0.06f), style ),
mSelectedPlayer(selectedPlayer)
{
}
CControlSettingsBaseWithMapping::
CControlSettingsBaseWithMapping(const int selectedPlayer,
const Style style) :
CControlSettingsBase(selectedPlayer, style) {}
void CControlSettingsBase::ponder(const float deltaT)
{
GameMenu::ponder(deltaT);
}
void CControlSettingsBaseWithMapping::ponder(const float deltaT)
{
auto &input = gInput;
if( !mapping && input.MappingInput() ) // mapping changed!
{
mapping = true;
}
else if( !input.MappingInput() )
{
if(mapping) // mapping changed!
{
mapping = false;
int pos; unsigned char inputVal;
std::string evName = input.getNewMappedEvent(pos, inputVal);
InpCmd com = static_cast<InpCmd>(pos);
mpButtonMap[com]->setText(mCommandName[com] + evName);
}
}
CControlSettingsBase::ponder(deltaT);
}
void CControlSettingsBase::addBottomText()
{
GsRect<float> rect;
if(getStyle() == Style::GALAXY )
{
rect = GsRect<float>(0.0f, 0.85f, 1.0f, 0.1f);
}
else
{
rect = GsRect<float>(0.05f, 0.85f, 1.0f, 0.1f);
}
auto deleteText = mpMenuDialog->add(
new CGUIText("Remove: ALT + BACKSPC", rect) );
deleteText->setTextColor(GsColor(0xBF, 0x00, 0x00));
deleteText->enableCenteringH(false);
}
void CControlSettingsBase::release()
{
gInput.saveControlconfig("");
}
void CControlSettingsBaseWithMapping::release()
{
if(!mCommandName.empty())
mCommandName.clear();
CControlSettingsBase::release();
}
void CControlSettingsMovement::refresh()
{
mapping = false;
mCommandName[IC_LEFT] = "Left: ";
mCommandName[IC_RIGHT] = "Right: ";
mCommandName[IC_UP] = "Up: ";
mCommandName[IC_DOWN] = "Down: ";
if(!mpButtonMap.empty())
mpButtonMap.clear();
std::map<InpCmd, std::string>::iterator it = mCommandName.begin();
for ( ; it != mCommandName.end(); it++ )
{
const std::string buf = it->second;
const std::string buf2 = gInput.getEventShortName( it->first,
mSelectedPlayer-1 );
ReadInputEvent *rie =
new ReadInputEvent(mSelectedPlayer,
it->first,
it->second);
auto guiButton =
mpMenuDialog->add(
new GameButton( buf+buf2,
rie,
getStyle() ) );
mpButtonMap[it->first] = guiButton;
rie->setButtonPtr(
std::static_pointer_cast<GsButton>(guiButton)
);
}
setMenuLabel("MOVEMENULABEL");
mpMenuDialog->fit();
addBottomText();
}
void CControlSettingsMoveDiag::refresh()
{
mapping = false;
mCommandName[IC_UPPERLEFT] = "U-left: ";
mCommandName[IC_UPPERRIGHT] = "U-right:";
mCommandName[IC_LOWERLEFT] = "D-left: ";
mCommandName[IC_LOWERRIGHT] = "D-right:";
if(!mpButtonMap.empty())
mpButtonMap.clear();
std::map<InpCmd, std::string>::iterator it = mCommandName.begin();
for ( ; it != mCommandName.end(); it++ )
{
const std::string buf = it->second;
const std::string buf2 = gInput.getEventShortName( it->first,
mSelectedPlayer-1 );
ReadInputEvent *rie =
new ReadInputEvent(mSelectedPlayer,
it->first,
it->second);
auto guiButton =
mpMenuDialog->add(
new GameButton( buf+buf2,
rie,
getStyle() ) );
mpButtonMap[it->first] = guiButton;
rie->setButtonPtr(
std::static_pointer_cast<GsButton>(guiButton)
);
}
setMenuLabel("MOVEMENULABEL");
mpMenuDialog->fit();
addBottomText();
}
// Action Parts of the Control Settings
void CControlSettingsGameplayActions::refresh()
{
mapping = false;
mCommandName[IC_JUMP] = "Jump: ";
mCommandName[IC_POGO] = "Pogo: ";
mCommandName[IC_FIRE] = "Fire: ";
mCommandName[IC_RUN] = "Run: ";
mCommandName[IC_STATUS] = "Status: ";
mCommandName[IC_CAMLEAD] = "Camlead: ";
if(!mpButtonMap.empty())
mpButtonMap.clear();
std::map<InpCmd, std::string>::iterator it = mCommandName.begin();
for ( ; it != mCommandName.end(); it++ )
{
const std::string buf = it->second;
const std::string buf2 = gInput.getEventShortName( it->first,
mSelectedPlayer-1 );
ReadInputEvent *rie =
new ReadInputEvent(mSelectedPlayer,
it->first, it->second);
auto guiButton =
mpMenuDialog->add(
new GameButton( buf+buf2,
rie,
getStyle() ) );
mpButtonMap[it->first] = guiButton;
rie->setButtonPtr(
std::static_pointer_cast<GsButton>(guiButton)
);
}
setMenuLabel("BUTTONMENULABEL");
mpMenuDialog->fit();
addBottomText();
}
// Misc Parts of the Control Settings
void CControlSettingsMisc::refresh()
{
mapping = false;
mCommandName[IC_HELP] = "Help: ";
mCommandName[IC_BACK] = "Back: ";
mCommandName[IC_QUICKSAVE] = "Quicksave:";
mCommandName[IC_QUICKLOAD] = "Quickload:";
if(!mpButtonMap.empty())
mpButtonMap.clear();
std::map<InpCmd, std::string>::iterator it = mCommandName.begin();
for ( ; it != mCommandName.end(); it++ )
{
const std::string buf = it->second;
const std::string buf2 = gInput.getEventShortName( it->first,
mSelectedPlayer-1 );
ReadInputEvent *rie =
new ReadInputEvent(mSelectedPlayer,
it->first, it->second);
auto guiButton =
mpMenuDialog->add(
new GameButton( buf+buf2,
rie,
getStyle() ) );
mpButtonMap[it->first] = guiButton;
rie->setButtonPtr(
std::static_pointer_cast<GsButton>(guiButton)
);
}
setMenuLabel("BUTTONMENULABEL");
mpMenuDialog->fit();
addBottomText();
}
void readPresetList(std::vector<std::string> &presetList,
const int playerIdx)
{
CConfiguration configuration;
if(configuration.Parse())
{
auto secListUnfiltered = configuration.getSectionList();
decltype (secListUnfiltered) secList;
for( const auto &sec : secListUnfiltered )
{
const std::string inputStr = "input" + itoa(playerIdx) + "-";
const auto pos = sec.find(inputStr);
if(pos == sec.npos)
continue;
presetList.push_back( sec.substr(inputStr.length()) );
}
}
}
// Presets part
void CControlSettingsLoadPreset::refresh()
{
const auto playerIdx = this->mSelectedPlayer-1;
auto refreshControlMenus = [this](const int player)
{
gEventManager.add( new CloseMenuEvent(false) );
gEventManager.add( new CloseMenuEvent(false) );
gEventManager.add(new OpenMenuEvent(
new CControlsettings(player, getStyle()) ));
};
mpMenuDialog->add(
new GameButton( "Factory Default",
[this, refreshControlMenus]()
{
const auto sel =
this->mSelectedPlayer-1;
assert(sel>=0);
gInput.resetControls(sel);
refreshControlMenus(sel+1);
},
getStyle() ) );
// Load preset list
std::vector<std::string> presetList;
readPresetList(presetList, playerIdx);
for(int i=0 ; i<8 ; i++)
{
std::string text = "<new>";
if(i < int(presetList.size()))
text = presetList.at(i);
else
continue;
auto input =
mpMenuDialog->add( new InputText(
text,
GsRect<float>(
0.0f, 0.1f+(i*0.1f),
1.0f, 0.1f), i,
getStyle() ) );
input->setActivationEvent([this, input, text, refreshControlMenus]()
{
input->setReleased(false);
gInput.loadControlconfig(text);
gInput.saveControlconfig("");
const auto sel = this->mSelectedPlayer-1;
assert(sel>=0);
refreshControlMenus(sel+1);
});
}
setMenuLabel("BUTTONMENULABEL");
mpMenuDialog->fit();
}
void CControlSettingsSavePreset::refresh()
{
// Load the presets list
std::vector<std::string> presetList = defaultPresets;
for(int i=0 ; i<8 ; i++)
{
std::string text = "<new>";
if(i < int(presetList.size()))
text = presetList.at(i);
else
continue;
auto input =
mpMenuDialog->add( new InputText(
text,
GsRect<float>(
0.0f, 0.1f+(i*0.1f),
1.0f, 0.1f), i,
getStyle() ) );
input->setActivationEvent([text,input]()
{
input->setReleased(false);
gInput.saveControlconfig(text);
gEventManager.add( new CloseMenuEvent(false) );
});
}
}
| 29.397459 | 88 | 0.498086 | [
"vector"
] |
6a967ad5fc68c0ea4c8705c82fb5a24b526e5077 | 13,133 | cpp | C++ | src/mongo/db/storage/heap1/heap1_database_catalog_entry.cpp | baiyanghese/mongo | 89fcbab94c7103105e8c72f654a5774a066bdb90 | [
"Apache-2.0"
] | 1 | 2015-11-06T05:42:37.000Z | 2015-11-06T05:42:37.000Z | src/mongo/db/storage/heap1/heap1_database_catalog_entry.cpp | baiyanghese/mongo | 89fcbab94c7103105e8c72f654a5774a066bdb90 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/storage/heap1/heap1_database_catalog_entry.cpp | baiyanghese/mongo | 89fcbab94c7103105e8c72f654a5774a066bdb90 | [
"Apache-2.0"
] | null | null | null | // heap1_database_catalog_entry.cpp
/**
* Copyright (C) 2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/storage/heap1/heap1_database_catalog_entry.h"
#include "mongo/db/catalog/collection_options.h"
#include "mongo/db/index/2d_access_method.h"
#include "mongo/db/index/btree_access_method.h"
#include "mongo/db/index/fts_access_method.h"
#include "mongo/db/index/hash_access_method.h"
#include "mongo/db/index/haystack_access_method.h"
#include "mongo/db/index/index_access_method.h"
#include "mongo/db/index/index_descriptor.h"
#include "mongo/db/index/s2_access_method.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/storage/heap1/heap1_btree_impl.h"
#include "mongo/db/storage/heap1/heap1_recovery_unit.h"
#include "mongo/db/structure/record_store_heap.h"
namespace mongo {
Heap1DatabaseCatalogEntry::Heap1DatabaseCatalogEntry( const StringData& name )
: DatabaseCatalogEntry( name ) {
_everHadACollection = false;
}
Heap1DatabaseCatalogEntry::~Heap1DatabaseCatalogEntry() {
for ( EntryMap::const_iterator i = _entryMap.begin(); i != _entryMap.end(); ++i ) {
delete i->second;
}
_entryMap.clear();
}
bool Heap1DatabaseCatalogEntry::isEmpty() const {
boost::mutex::scoped_lock lk( _entryMapLock );
return _entryMap.empty();
}
void Heap1DatabaseCatalogEntry::appendExtraStats( OperationContext* opCtx,
BSONObjBuilder* out,
double scale ) const {
}
CollectionCatalogEntry* Heap1DatabaseCatalogEntry::getCollectionCatalogEntry( OperationContext* opCtx,
const StringData& ns ) {
boost::mutex::scoped_lock lk( _entryMapLock );
EntryMap::iterator i = _entryMap.find( ns.toString() );
if ( i == _entryMap.end() )
return NULL;
return i->second;
}
RecordStore* Heap1DatabaseCatalogEntry::getRecordStore( OperationContext* opCtx,
const StringData& ns ) {
boost::mutex::scoped_lock lk( _entryMapLock );
EntryMap::iterator i = _entryMap.find( ns.toString() );
if ( i == _entryMap.end() )
return NULL;
return i->second->rs.get();
}
void Heap1DatabaseCatalogEntry::getCollectionNamespaces( std::list<std::string>* out ) const {
boost::mutex::scoped_lock lk( _entryMapLock );
for ( EntryMap::const_iterator i = _entryMap.begin(); i != _entryMap.end(); ++i ) {
out->push_back( i->first );
}
}
Status Heap1DatabaseCatalogEntry::createCollection( OperationContext* opCtx,
const StringData& ns,
const CollectionOptions& options,
bool allocateDefaultSpace ) {
dynamic_cast<Heap1RecoveryUnit*>( opCtx->recoveryUnit() )->rollbackPossible = false;
boost::mutex::scoped_lock lk( _entryMapLock );
Entry*& entry = _entryMap[ ns.toString() ];
if ( entry )
return Status( ErrorCodes::NamespaceExists,
"cannot create collection, already exists" );
entry = new Entry( ns );
if ( options.capped ) {
entry->rs.reset(new HeapRecordStore(ns,
true,
options.cappedSize
? options.cappedSize : 4096, // default size
options.cappedMaxDocs
? options.cappedMaxDocs : -1)); // no limit
}
else {
entry->rs.reset( new HeapRecordStore( ns ) );
}
return Status::OK();
}
Status Heap1DatabaseCatalogEntry::dropCollection( OperationContext* opCtx,
const StringData& ns ) {
//TODO: invariant( opCtx->lockState()->isWriteLocked( ns ) );
dynamic_cast<Heap1RecoveryUnit*>( opCtx->recoveryUnit() )->rollbackPossible = false;
boost::mutex::scoped_lock lk( _entryMapLock );
EntryMap::iterator i = _entryMap.find( ns.toString() );
if ( i == _entryMap.end() )
return Status( ErrorCodes::NamespaceNotFound, "namespace not found" );
delete i->second;
_entryMap.erase( i );
return Status::OK();
}
IndexAccessMethod* Heap1DatabaseCatalogEntry::getIndex( OperationContext* txn,
const CollectionCatalogEntry* collection,
IndexCatalogEntry* index ) {
const Entry* entry = dynamic_cast<const Entry*>( collection );
Entry::Indexes::const_iterator i = entry->indexes.find( index->descriptor()->indexName() );
if ( i == entry->indexes.end() ) {
// index doesn't exist
return NULL;
}
const string& type = index->descriptor()->getAccessMethodName();
#if 1 // Toggle to use Btree on HeapRecordStore
// Need the Head to be non-Null to avoid asserts. TODO remove the asserts.
index->headManager()->setHead(txn, DiskLoc(0xDEAD, 0xBEAF));
// When is a btree not a Btree? When it is a Heap1BtreeImpl!
std::auto_ptr<BtreeInterface> btree(getHeap1BtreeImpl(index, &i->second->data));
#else
if (!i->second->rs)
i->second->rs.reset(new HeapRecordStore( index->descriptor()->indexName() ));
std::auto_ptr<BtreeInterface> btree(
BtreeInterface::getInterface(index->headManager(),
i->second->rs,
index->ordering(),
index->descriptor()->indexNamespace(),
index->descriptor()->version(),
&BtreeBasedAccessMethod::invalidateCursors));
#endif
if ("" == type)
return new BtreeAccessMethod( index, btree.release() );
if (IndexNames::HASHED == type)
return new HashAccessMethod( index, btree.release() );
if (IndexNames::GEO_2DSPHERE == type)
return new S2AccessMethod( index, btree.release() );
if (IndexNames::TEXT == type)
return new FTSAccessMethod( index, btree.release() );
if (IndexNames::GEO_HAYSTACK == type)
return new HaystackAccessMethod( index, btree.release() );
if (IndexNames::GEO_2D == type)
return new TwoDAccessMethod( index, btree.release() );
log() << "Can't find index for keyPattern " << index->descriptor()->keyPattern();
fassertFailed(18518);
}
Status Heap1DatabaseCatalogEntry::renameCollection( OperationContext* txn,
const StringData& fromNS,
const StringData& toNS,
bool stayTemp ) {
invariant( false );
}
// ------------------
Heap1DatabaseCatalogEntry::Entry::Entry( const StringData& ns)
: CollectionCatalogEntry( ns ) {
}
Heap1DatabaseCatalogEntry::Entry::~Entry() {
for ( Indexes::const_iterator i = indexes.begin(); i != indexes.end(); ++i )
delete i->second;
indexes.clear();
}
int Heap1DatabaseCatalogEntry::Entry::getTotalIndexCount() const {
return static_cast<int>( indexes.size() );
}
int Heap1DatabaseCatalogEntry::Entry::getCompletedIndexCount() const {
int ready = 0;
for ( Indexes::const_iterator i = indexes.begin(); i != indexes.end(); ++i )
if ( i->second->ready )
ready++;
return ready;
}
void Heap1DatabaseCatalogEntry::Entry::getAllIndexes( std::vector<std::string>* names ) const {
for ( Indexes::const_iterator i = indexes.begin(); i != indexes.end(); ++i )
names->push_back( i->second->name );
}
BSONObj Heap1DatabaseCatalogEntry::Entry::getIndexSpec( const StringData& idxName ) const {
Indexes::const_iterator i = indexes.find( idxName.toString() );
invariant( i != indexes.end() );
return i->second->spec;
}
bool Heap1DatabaseCatalogEntry::Entry::isIndexMultikey( const StringData& idxName) const {
Indexes::const_iterator i = indexes.find( idxName.toString() );
invariant( i != indexes.end() );
return i->second->isMultikey;
}
bool Heap1DatabaseCatalogEntry::Entry::setIndexIsMultikey(OperationContext* txn,
const StringData& idxName,
bool multikey ) {
Indexes::const_iterator i = indexes.find( idxName.toString() );
invariant( i != indexes.end() );
if (i->second->isMultikey == multikey)
return false;
i->second->isMultikey = multikey;
return true;
}
DiskLoc Heap1DatabaseCatalogEntry::Entry::getIndexHead( const StringData& idxName ) const {
Indexes::const_iterator i = indexes.find( idxName.toString() );
invariant( i != indexes.end() );
return i->second->head;
}
void Heap1DatabaseCatalogEntry::Entry::setIndexHead( OperationContext* txn,
const StringData& idxName,
const DiskLoc& newHead ) {
Indexes::const_iterator i = indexes.find( idxName.toString() );
invariant( i != indexes.end() );
i->second->head = newHead;
}
bool Heap1DatabaseCatalogEntry::Entry::isIndexReady( const StringData& idxName ) const {
Indexes::const_iterator i = indexes.find( idxName.toString() );
invariant( i != indexes.end() );
return i->second->ready;
}
Status Heap1DatabaseCatalogEntry::Entry::removeIndex( OperationContext* txn,
const StringData& idxName ) {
indexes.erase( idxName.toString() );
return Status::OK();
}
Status Heap1DatabaseCatalogEntry::Entry::prepareForIndexBuild( OperationContext* txn,
const IndexDescriptor* spec ) {
auto_ptr<IndexEntry> newEntry( new IndexEntry() );
newEntry->name = spec->indexName();
newEntry->spec = spec->infoObj();
newEntry->ready = false;
newEntry->isMultikey = false;
indexes[spec->indexName()] = newEntry.release();
return Status::OK();
}
void Heap1DatabaseCatalogEntry::Entry::indexBuildSuccess( OperationContext* txn,
const StringData& idxName ) {
Indexes::const_iterator i = indexes.find( idxName.toString() );
invariant( i != indexes.end() );
i->second->ready = true;
}
void Heap1DatabaseCatalogEntry::Entry::updateTTLSetting( OperationContext* txn,
const StringData& idxName,
long long newExpireSeconds ) {
invariant( false );
}
}
| 42.228296 | 106 | 0.572603 | [
"vector"
] |
6a987624bdb612f02981bb1ae6e7c068c5be1e37 | 11,111 | cc | C++ | tensorflow/core/tfrt/eager/function_cache_test.cc | mcx/tensorflow | d7e521a1ad21681855b439b9c2a05837c804e488 | [
"Apache-2.0"
] | 1 | 2022-03-18T17:36:11.000Z | 2022-03-18T17:36:11.000Z | tensorflow/core/tfrt/eager/function_cache_test.cc | mcx/tensorflow | d7e521a1ad21681855b439b9c2a05837c804e488 | [
"Apache-2.0"
] | null | null | null | tensorflow/core/tfrt/eager/function_cache_test.cc | mcx/tensorflow | d7e521a1ad21681855b439b9c2a05837c804e488 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2021 The TensorFlow 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 "tensorflow/core/tfrt/eager/function_cache.h"
#include <memory>
#include "absl/types/span.h"
#include "tensorflow/c/eager/abstract_tensor_handle.h"
#include "tensorflow/c/eager/c_api_experimental.h"
#include "tensorflow/c/eager/c_api_test_util.h"
#include "tensorflow/c/eager/c_api_unified_experimental.h"
#include "tensorflow/c/eager/c_api_unified_experimental_internal.h"
#include "tensorflow/c/experimental/ops/array_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/c/tf_tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/llvm_rtti/llvm_rtti.h"
#include "tensorflow/core/platform/errors.h"
#include "tensorflow/core/platform/refcount.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/tfrt/eager/c_api_tfrt.h"
namespace tfrt {
namespace tf {
namespace {
using tensorflow::Status;
using tensorflow::StatusFromTF_Status;
using tensorflow::TF_StatusPtr;
constexpr char kCpuName[] = "/job:localhost/replica:0/task:0/device:CPU:0";
constexpr char kFunctionName[] = "test_fn";
class CppTests : public ::testing::TestWithParam<const char*> {
protected:
void SetUp() override {
TF_StatusPtr status(TF_NewStatus());
TF_SetTracingImplementation(GetParam(), status.get());
Status s = StatusFromTF_Status(status.get());
CHECK_EQ(tensorflow::errors::OK, s.code()) << s.error_message();
}
};
// Computes `inputs[0] + inputs[1]` and records it on the tape.
tensorflow::Status Add(
tensorflow::AbstractContext* ctx,
absl::Span<tensorflow::AbstractTensorHandle* const> inputs,
absl::Span<tensorflow::AbstractTensorHandle*> outputs) {
tensorflow::AbstractOperationPtr add_op(ctx->CreateOperation());
TF_RETURN_IF_ERROR(add_op.get()->Reset("Add", /*raw_device_name=*/nullptr));
if (isa<tensorflow::tracing::TracingOperation>(add_op.get())) {
TF_RETURN_IF_ERROR(
dyn_cast<tensorflow::tracing::TracingOperation>(add_op.get())
->SetOpName("my_add"));
}
TF_RETURN_IF_ERROR(add_op.get()->AddInput(inputs[0]));
TF_RETURN_IF_ERROR(add_op.get()->AddInput(inputs[1]));
int num_retvals = 1;
return add_op.get()->Execute(outputs, &num_retvals);
}
// Computes
// return inputs[0] + inputs[1]
tensorflow::Status AddModel(
tensorflow::AbstractContext* ctx,
absl::Span<tensorflow::AbstractTensorHandle* const> inputs,
absl::Span<tensorflow::AbstractTensorHandle*> outputs) {
std::vector<tensorflow::AbstractTensorHandle*> add_outputs(1);
// Compute x+y.
TF_RETURN_IF_ERROR(Add(ctx, inputs, absl::MakeSpan(add_outputs)));
outputs[0] = add_outputs[0];
return ::tensorflow::OkStatus();
}
tensorflow::AbstractContext* BuildFunction(const char* fn_name) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TF_ExecutionContext* graph_ctx = TF_CreateFunction(fn_name, status.get());
return tensorflow::unwrap(graph_ctx);
}
tensorflow::Status CreateParamsForInputs(
tensorflow::AbstractContext* ctx,
absl::Span<tensorflow::AbstractTensorHandle* const> inputs,
std::vector<tensorflow::AbstractTensorHandle*>* params) {
tensorflow::tracing::TracingTensorHandle* handle = nullptr;
for (auto input : inputs) {
tensorflow::PartialTensorShape shape;
TF_RETURN_IF_ERROR(input->Shape(&shape));
TF_RETURN_IF_ERROR(
dyn_cast<tensorflow::tracing::TracingContext>(ctx)->AddParameter(
input->DataType(), shape, &handle));
params->emplace_back(handle);
}
return ::tensorflow::OkStatus();
}
using Model = std::function<tensorflow::Status(
tensorflow::AbstractContext*,
absl::Span<tensorflow::AbstractTensorHandle* const>,
absl::Span<tensorflow::AbstractTensorHandle*>)>;
tensorflow::Status PrepareFunction(
Model model, tensorflow::AbstractContext* ctx,
absl::Span<tensorflow::AbstractTensorHandle* const> inputs,
absl::Span<tensorflow::AbstractTensorHandle*> outputs) {
tensorflow::core::RefCountPtr<tensorflow::AbstractFunction> scoped_func;
tensorflow::AbstractContextPtr func_ctx(BuildFunction(kFunctionName));
std::vector<tensorflow::AbstractTensorHandle*> func_inputs;
func_inputs.reserve(inputs.size());
TF_RETURN_IF_ERROR(
CreateParamsForInputs(func_ctx.get(), inputs, &func_inputs));
tensorflow::OutputList output_list;
output_list.expected_num_outputs = outputs.size();
output_list.outputs.resize(outputs.size());
TF_RETURN_IF_ERROR(model(func_ctx.get(), absl::MakeSpan(func_inputs),
absl::MakeSpan(output_list.outputs)));
for (auto func_input : func_inputs) {
func_input->Unref();
}
tensorflow::AbstractFunction* func = nullptr;
TF_RETURN_IF_ERROR(
dyn_cast<tensorflow::tracing::TracingContext>(func_ctx.get())
->Finalize(&output_list, &func));
scoped_func.reset(func);
for (auto output : output_list.outputs) {
output->Unref();
}
TF_RETURN_IF_ERROR(ctx->RegisterFunction(func));
return ::tensorflow::OkStatus();
}
tensorflow::Status BuildImmediateExecutionContext(
bool use_tfrt, tensorflow::AbstractContext** ctx) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_ContextOptions* opts = TFE_NewContextOptions();
TFE_ContextOptionsSetTfrt(opts, use_tfrt);
*ctx = tensorflow::unwrap(TF_NewEagerExecutionContext(opts, status.get()));
TF_RETURN_IF_ERROR(tensorflow::StatusFromTF_Status(status.get()));
TFE_DeleteContextOptions(opts);
return ::tensorflow::OkStatus();
}
tensorflow::Status TestScalarTensorHandle(
tensorflow::AbstractContext* ctx, float value,
tensorflow::AbstractTensorHandle** tensor) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
TFE_Context* eager_ctx =
TF_ExecutionContextGetTFEContext(wrap(ctx), status.get());
TF_RETURN_IF_ERROR(tensorflow::StatusFromTF_Status(status.get()));
TFE_TensorHandle* input_eager = TestScalarTensorHandle(eager_ctx, value);
*tensor = tensorflow::unwrap(
TF_CreateAbstractTensorFromEagerTensor(input_eager, status.get()));
return ::tensorflow::OkStatus();
}
TEST_P(CppTests, TestFunctionCacheWithAdd) {
std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status(
TF_NewStatus(), TF_DeleteStatus);
tensorflow::AbstractContextPtr ctx;
{
tensorflow::AbstractContext* ctx_raw = nullptr;
tensorflow::Status s = BuildImmediateExecutionContext(true, &ctx_raw);
ASSERT_EQ(tensorflow::errors::OK, s.code()) << s.error_message();
ctx.reset(ctx_raw);
}
tensorflow::AbstractTensorHandlePtr x;
{
tensorflow::AbstractTensorHandle* x_raw = nullptr;
tensorflow::Status s = TestScalarTensorHandle(ctx.get(), 2.0f, &x_raw);
ASSERT_EQ(tensorflow::errors::OK, s.code()) << s.error_message();
x.reset(x_raw);
}
tensorflow::AbstractTensorHandlePtr y;
{
tensorflow::AbstractTensorHandle* y_raw = nullptr;
tensorflow::Status s = TestScalarTensorHandle(ctx.get(), 2.0f, &y_raw);
ASSERT_EQ(tensorflow::errors::OK, s.code()) << s.error_message();
y.reset(y_raw);
}
// Pseudo-code:
// outputs = x + y
tensorflow::Status s;
std::vector<tensorflow::AbstractTensorHandle*> outputs(1);
s = PrepareFunction(AddModel, ctx.get(), {x.get(), y.get()},
absl::MakeSpan(outputs));
::tfrt::tf::FunctionCache cache;
::tfrt::tf::ContextInterface* tfrt_ctx =
static_cast<::tfrt::tf::ContextInterface*>(ctx.get());
::tfrt::CoreRuntime* corert = tfrt_ctx->GetCoreRuntime();
tensorflow::EagerContext* eager_ctx = tfrt_ctx->GetEagerContext();
// Cache is empty initially.
ASSERT_EQ(cache.Size(), 0);
ASSERT_EQ(cache.Contains(kFunctionName, kCpuName), false);
tensorflow::DeviceSet dev_set;
const tensorflow::DeviceMgr* device_mgr =
tfrt_ctx->GetEagerContext()->local_device_mgr();
for (auto d : device_mgr->ListDevices()) dev_set.AddDevice(d);
auto& device = corert->GetHostContext()->GetHostDevice();
const Device* input_devices[2] = {&device, &device};
auto req_ctx = RequestContextBuilder(corert->GetHostContext(),
/*resource_context=*/nullptr)
.build();
ExecutionContext exec_ctx(std::move(*req_ctx));
auto request_ctx_fn =
[host = corert->GetHostContext()](
tensorflow::tfrt_stub::OpKernelRunnerTable* runner_table,
RCReference<RequestContext>* request_ctx) {
*request_ctx =
std::move(*RequestContextBuilder(host,
/*resource_context=*/nullptr)
.build());
return ::tensorflow::OkStatus();
};
// Inserts a new cache entry.
FunctionCache::FunctionCacheResult result;
TF_ASSERT_OK(cache.GetOrAddFunction(
kFunctionName, kCpuName, dev_set, eager_ctx, corert, request_ctx_fn,
/*loc=*/{}, tensorflow::TfrtFunctionCompileOptions(), input_devices,
&result));
ASSERT_NE(result.function_state.get(), nullptr);
// Cache contains the inserted entry now.
ASSERT_EQ(cache.Contains(kFunctionName, kCpuName), true);
// There's one entry in the cache.
ASSERT_EQ(cache.Size(), 1);
// This lookup is a cache hit.
TF_ASSERT_OK(cache.GetOrAddFunction(
kFunctionName, kCpuName, dev_set, eager_ctx, corert, request_ctx_fn,
/*loc=*/{}, tensorflow::TfrtFunctionCompileOptions(), input_devices,
&result));
ASSERT_NE(result.function_state.get(), nullptr);
// Cache hit doesn't create new entry in the cache.
ASSERT_EQ(cache.Size(), 1);
// Add another entry with the same function name but different device name.
// This lookup is a cache miss.
TF_ASSERT_OK(cache.GetOrAddFunction(
kFunctionName, "", dev_set, eager_ctx, corert, request_ctx_fn,
/*loc=*/{}, tensorflow::TfrtFunctionCompileOptions(), input_devices,
&result));
ASSERT_NE(result.function_state.get(), nullptr);
// Cache miss adds a new entry in the cache.
ASSERT_EQ(cache.Size(), 2);
cache.RemoveFunction(kFunctionName);
// RemoveFunction removes all entries in the cache since they have the same
// function name.
ASSERT_EQ(cache.Size(), 0);
}
INSTANTIATE_TEST_SUITE_P(UnifiedCAPI, CppTests, ::testing::Values("graphdef"));
} // namespace
} // namespace tf
} // namespace tfrt
| 38.446367 | 80 | 0.717937 | [
"shape",
"vector",
"model"
] |
6aa4c65ac6d4e0b12b756677e939d88e3d6e4034 | 425 | cpp | C++ | BOJ_problem/10804.cpp | Geol2/PSCode | adaa6d3c7712caa8cc0ce9b00711e5d866907ddc | [
"MIT"
] | null | null | null | BOJ_problem/10804.cpp | Geol2/PSCode | adaa6d3c7712caa8cc0ce9b00711e5d866907ddc | [
"MIT"
] | null | null | null | BOJ_problem/10804.cpp | Geol2/PSCode | adaa6d3c7712caa8cc0ce9b00711e5d866907ddc | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
vector<int> a(21);
for (int i = 0; i < 21; i++) a[i] = i;
int num1, num2;
for (int i = 0; i < 10; i++) {
cin >> num1 >> num2;
reverse(a.begin() + num1, a.begin() + num2 + 1);
}
for (int i = 1; i < 21; i++)
cout << a[i] << ' ';
return 0;
return 0;
} | 17.708333 | 50 | 0.56 | [
"vector"
] |
6aaf134087010d457d9af0035a6b8cb51184dc5e | 31,473 | cc | C++ | lib/lang/ast.cc | daadaada/triton | e5248b655b237f26b8134b9cad08de41fb885fb1 | [
"MIT"
] | null | null | null | lib/lang/ast.cc | daadaada/triton | e5248b655b237f26b8134b9cad08de41fb885fb1 | [
"MIT"
] | null | null | null | lib/lang/ast.cc | daadaada/triton | e5248b655b237f26b8134b9cad08de41fb885fb1 | [
"MIT"
] | null | null | null | #include "triton/lang/ast.h"
#include "triton/lang/error.h"
#include "triton/lang/evaluator.h"
#include "triton/lang/mem_pool.h"
#include "triton/lang/parser.h"
#include "triton/lang/token.h"
static MemPoolImp<BinaryOp> binaryOpPool;
static MemPoolImp<TransOp> transOpPool;
static MemPoolImp<ConditionalOp> conditionalOpPool;
static MemPoolImp<FuncCall> funcCallPool;
static MemPoolImp<Declaration> initializationPool;
static MemPoolImp<Object> objectPool;
static MemPoolImp<Identifier> identifierPool;
static MemPoolImp<Enumerator> enumeratorPool;
static MemPoolImp<Constant> constantPool;
static MemPoolImp<TempVar> tempVarPool;
static MemPoolImp<UnaryOp> unaryOpPool;
static MemPoolImp<EmptyStmt> emptyStmtPool;
static MemPoolImp<IfStmt> ifStmtPool;
static MemPoolImp<ForStmt> forStmtPool;
static MemPoolImp<JumpStmt> jumpStmtPool;
static MemPoolImp<ReturnStmt> returnStmtPool;
static MemPoolImp<LabelStmt> labelStmtPool;
static MemPoolImp<CompoundStmt> compoundStmtPool;
static MemPoolImp<FuncDef> funcDefPool;
/*
* Accept
*/
void Declaration::Accept(Visitor* v) {
v->VisitDeclaration(this);
}
void EmptyStmt::Accept(Visitor* v) {
// Nothing to do
}
void LabelStmt::Accept(Visitor* v) {
v->VisitLabelStmt(this);
}
void IfStmt::Accept(Visitor* v) {
v->VisitIfStmt(this);
}
void ForStmt::Accept(Visitor* v) {
v->VisitForStmt(this);
}
void JumpStmt::Accept(Visitor* v) {
v->VisitJumpStmt(this);
}
void ReturnStmt::Accept(Visitor* v) {
v->VisitReturnStmt(this);
}
void CompoundStmt::Accept(Visitor* v) {
v->VisitCompoundStmt(this);
}
void BinaryOp::Accept(Visitor* v) {
v->VisitBinaryOp(this);
}
void UnaryOp::Accept(Visitor* v) {
v->VisitUnaryOp(this);
}
void TransOp::Accept(Visitor* v) {
v->VisitTransOp(this);
}
void ConditionalOp::Accept(Visitor* v) {
v->VisitConditionalOp(this);
}
void FuncCall::Accept(Visitor* v) {
v->VisitFuncCall(this);
}
void Identifier::Accept(Visitor* v) {
v->VisitIdentifier(this);
}
void Object::Accept(Visitor* v) {
v->VisitObject(this);
}
void Constant::Accept(Visitor* v) {
v->VisitConstant(this);
}
void Enumerator::Accept(Visitor* v)
{
v->VisitEnumerator(this);
}
void TempVar::Accept(Visitor* v) {
v->VisitTempVar(this);
}
void FuncDef::Accept(Visitor* v) {
v->VisitFuncDef(this);
}
void TranslationUnit::Accept(Visitor* v) {
v->VisitTranslationUnit(this);
}
// Casting array to pointer, function to pointer to function
Expr* Expr::MayCast(Expr* expr) {
auto type = Type::MayCast(expr->Type());
// If the types are equal, no need cast
if (type != expr->Type()) { // Pointer comparison is enough
return UnaryOp::New(Token::CAST, expr, type);
}
return expr;
}
Expr* Expr::MayCast(Expr* expr, QualType desType) {
expr = MayCast(expr);
auto srcType = expr->Type();
if (desType->ToPointer() && srcType->ToPointer())
if (desType->IsVoidPointer() || srcType->IsVoidPointer())
return expr;
if (!desType->Compatible(*expr->Type()))
expr = UnaryOp::New(Token::CAST, expr, desType);
return expr;
}
// Extract the operand's scalar type if possible
// and emit an error otherwise
::Type* Expr::TryExtractScalarType(Expr* loc, Expr *operand) {
auto scalType = operand->Type()->ScalarType();
if(!scalType)
Error(loc, "expect tile or scalar operand");
return scalType;
}
// If operand is a tile, return a tile of the same shape and
// provided element type
// If operand is a scalar, return provided element type
// directly
::Type* Expr::ScalarOrLikeTile(Expr* operand, ::Type* ty) {
assert(ty->IsScalar());
::Type *retTy = ty;
if(TileType *T = operand->Type()->ToTile())
retTy = TileType::New(T->Shape(), retTy);
return retTy;
}
BinaryOp* BinaryOp::New(const Token* tok, Expr* lhs, Expr* rhs) {
return New(tok, tok->tag_, lhs, rhs);
}
BinaryOp* BinaryOp::New(const Token* tok, int op, Expr* lhs, Expr* rhs) {
switch (op) {
case ',': case '.': case '=':
case '*': case '/': case '%':
case '+': case '-': case '&':
case '^': case '|': case '<':
case '>':
case Token::LEFT:
case Token::RIGHT:
case Token::LE:
case Token::GE:
case Token::EQ:
case Token::NE:
case Token::LOGICAL_AND:
case Token::LOGICAL_OR:
case Token::ELLIPSIS:
case Token::MATMUL:
case Token::MASKED_DEREF:
break;
default:
assert(0);
}
auto ret = new (binaryOpPool.Alloc()) BinaryOp(tok, op, lhs, rhs);
ret->pool_ = &binaryOpPool;
ret->TypeChecking();
return ret;
}
ArithmType* BinaryOp::Convert() {
// Both lhs and rhs are ensured to be have arithmetic scalar type
auto lhsType = lhs_->Type()->ScalarType()->ToArithm();
auto rhsType = rhs_->Type()->ScalarType()->ToArithm();
assert(lhsType && rhsType);
auto maxType = ArithmType::MaxType(lhsType, rhsType);
if (lhsType != maxType) { // Pointer comparation is enough!
lhs_ = UnaryOp::New(Token::CAST, lhs_, ScalarOrLikeTile(lhs_, maxType));
}
if (rhsType != maxType) {
rhs_ = UnaryOp::New(Token::CAST, rhs_, ScalarOrLikeTile(rhs_, maxType));
}
return maxType;
}
void BinaryOp::Broadcast(Expr* loc, Expr *&lhs, Expr *&rhs, QualType& type) {
auto lhsType = lhs->Type()->ToTile();
auto rhsType = rhs->Type()->ToTile();
auto eleType = type->ScalarType();
assert(eleType);
if(!lhsType && !rhsType)
return ;
else if(lhsType && !rhsType){
type = TileType::New(lhsType->Shape(), eleType);
::Type* rtype = TileType::New(lhsType->Shape(), rhs->Type()->ScalarType());
rhs = UnaryOp::New(Token::CAST, rhs, rtype);
}
else if(!lhsType && rhsType){
type = TileType::New(rhsType->Shape(), eleType);
::Type* ltype = TileType::New(rhsType->Shape(), lhs->Type()->ScalarType());
lhs = UnaryOp::New(Token::CAST, lhs, ltype);
}
else {
auto lhsShape = lhsType->Shape();
auto rhsShape = rhsType->Shape();
auto lhsRank = lhsShape.size();
auto rhsRank = rhsShape.size();
auto retRank = std::max(lhsRank, rhsRank);
// pad to the left until shapes have the same rank
while(lhsShape.size() < retRank)
lhsShape.insert(lhsShape.begin(), 1);
while(rhsShape.size() < retRank)
rhsShape.insert(rhsShape.begin(), 1);
// broadcast if possible
TileType::ShapeInt retShape(retRank);
for(size_t i = 0; i < retRank; i++) {
if(lhsShape[i] == 1)
retShape[i] = rhsShape[i];
else if(rhsShape[i] == 1)
retShape[i] = lhsShape[i];
else if(lhsShape[i] == rhsShape[i])
retShape[i] = lhsShape[i];
else
Error(loc, "cannot broadcast dimension %d "
"for operands of shape %d and %d",
i, lhsShape[i], rhsShape[i]);
}
::Type* ltype = TileType::New(retShape, lhsType->ScalarType());
::Type* rtype = TileType::New(retShape, rhsType->ScalarType());
type = TileType::New(retShape, eleType);
if(retShape != lhsShape)
lhs = UnaryOp::New(Token::CAST, lhs, ltype);
if(retShape != rhsShape)
rhs = UnaryOp::New(Token::CAST, rhs, rtype);
}
}
/*
* Type checking
*/
void Expr::EnsureCompatibleOrVoidPointer(const QualType lhs,
const QualType rhs) const {
if (lhs->ToPointer() && rhs->ToPointer() &&
(lhs->IsVoidPointer() || rhs->IsVoidPointer())) {
return;
}
EnsureCompatible(lhs, rhs);
}
void Expr::EnsureCompatible(const QualType lhs, const QualType rhs) const {
if (!lhs->Compatible(*rhs))
Error(this, "incompatible types");
}
void BinaryOp::TypeChecking() {
switch (op_) {
case '.':
return MemberRefOpTypeChecking();
case '*':
case '/':
case '%':
return MultiOpTypeChecking();
case '+':
case '-':
return AdditiveOpTypeChecking();
case Token::LEFT:
case Token::RIGHT:
return ShiftOpTypeChecking();
case '<':
case '>':
case Token::LE:
case Token::GE:
return RelationalOpTypeChecking();
case Token::EQ:
case Token::NE:
return EqualityOpTypeChecking();
case '&':
case '^':
case '|':
return BitwiseOpTypeChecking();
case Token::LOGICAL_AND:
case Token::LOGICAL_OR:
return LogicalOpTypeChecking();
case '=':
return AssignOpTypeChecking();
case ',':
return CommaOpTypeChecking();
case Token::ELLIPSIS:
return RangeOpTypeChecking();
case Token::MATMUL:
return MatmulOpTypeChecking();
case Token::MASKED_DEREF:
return MaskedDerefOpTypeChecking();
default:
assert(0);
}
}
void BinaryOp::CommaOpTypeChecking() {
type_ = rhs_->Type();
}
void BinaryOp::SubScriptingOpTypeChecking() {
assert(false);
}
void BinaryOp::MemberRefOpTypeChecking() {
type_ = rhs_->Type();
}
void BinaryOp::MultiOpTypeChecking() {
::Type* lhsScalType = lhs_->Type()->ScalarType();
::Type* rhsScalType = rhs_->Type()->ScalarType();
if(!lhsScalType || !rhsScalType) {
Error(this, "operands should have type or scalar type");
}
if (!lhsScalType->ToArithm() || !rhsScalType->ToArithm()) {
Error(this, "operands should have arithmetic type");
}
if ('%' == op_ &&
!(lhsScalType->IsInteger() && rhsScalType->IsInteger())) {
Error(this, "operands of '%%' should be integers");
}
type_ = Convert();
Broadcast(this, lhs_, rhs_, type_);
}
/*
* Additive operator is only allowed between:
* 1. arithmetic types (bool, interger, floating)
* 2. pointer can be used:
* 1. lhs of MINUS operator, and rhs must be integer or pointer;
* 2. lhs/rhs of ADD operator, and the other operand must be integer;
* 3. tiles can be used:
* 1. the scalar type of lhs/rhs satisfy the above requirements
* 2. lhs/rhs that have identical shape
* 3. lhs/rhs that can be broadcast as per numpy-like semantics
*/
void BinaryOp::AdditiveOpTypeChecking() {
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
auto lhsPtrType = lhsScalType->ToPointer();
auto rhsPtrType = rhsScalType->ToPointer();
if (lhsPtrType) {
if (op_ == '-') {
if (rhsPtrType) {
if (!lhsPtrType->Compatible(*rhsPtrType))
Error(this, "invalid operands to binary -");
type_ = ArithmType::New(T_LONG); // ptrdiff_t
} else if (!rhsScalType->IsInteger()) {
Error(this, "invalid operands to binary -");
} else {
type_ = lhsPtrType;
}
} else if (!rhsScalType->IsInteger()) {
Error(this, "invalid operands to binary +");
} else {
type_ = lhsPtrType;
}
} else if (rhsPtrType) {
if (op_ == '+' && !lhsScalType->IsInteger()) {
Error(this, "invalid operands to binary '+'");
} else if (op_ == '-' && !lhsPtrType) {
Error(this, "invalid operands to binary '-'");
}
type_ = op_ == '-' ? ArithmType::New(T_LONG): rhsScalType;
std::swap(lhs_, rhs_); // To simplify code gen
} else {
if (!lhsScalType->ToArithm() || !rhsScalType->ToArithm()) {
Error(this, "invalid operands to binary %s", tok_->str_.c_str());
}
type_ = Convert();
}
Broadcast(this, lhs_, rhs_, type_);
}
void BinaryOp::RangeOpTypeChecking() {
auto lhsType = lhs_->Type()->ToArithm();
auto rhsType = rhs_->Type()->ToArithm();
if(!lhsType || !lhsType->IsInteger() || !rhsType || !rhsType->IsInteger())
Error(this, "expect integers for range operator");
lhs_ = Expr::MayCast(lhs_, ArithmType::IntegerPromote(lhsType));
rhs_ = Expr::MayCast(rhs_, ArithmType::IntegerPromote(rhsType));
long begin = Evaluator<long>().Eval(lhs_);
long end = Evaluator<long>().Eval(rhs_);
int len = static_cast<int>(end - begin);
if(len < 0)
Error(this, "range cannot be negative");
type_ = TileType::New(TileType::ShapeInt{len}, lhs_->Type());
}
void BinaryOp::MaskedDerefOpTypeChecking() {
// auto lhsTileType = lhs_->Type()->ToTile();
// auto rhsTileType = rhs_->Type()->ToTile();
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
auto lhsType = lhsScalType->ToArithm();
auto rhsType = rhsScalType->ToPointer();
if (!rhsType)
Error(this, "pointer expected for deref pointer in operator '*?'");
if (!lhsType || (lhsType && !lhsType->IsBool()))
Error(this, "bool expected for deref mask in operator '*?'");
type_ = ScalarOrLikeTile(rhs_, rhsType->Derived().GetPtr());
Broadcast(this, lhs_, rhs_, type_);
}
void BinaryOp::MatmulOpTypeChecking() {
auto lhsType = lhs_->Type()->ToTile();
auto rhsType = rhs_->Type()->ToTile();
if(!lhsType || !rhsType)
Error(this, "expect tile operands for matrix multiplication");
auto lhsShape = lhsType->Shape();
auto rhsShape = rhsType->Shape();
size_t lhsRank = lhsShape.size();
size_t rhsRank = rhsShape.size();
if(lhsRank != rhsRank)
Error(this, "matrix multiplication operands have incompatible rank"
"%d and %d", lhsRank, rhsRank);
for(int d = 2; d < lhsRank; d++)
if(lhsShape[d] != rhsShape[d])
Error(this, "matrix multiplication operands have incompatible batch dimension"
"%d and %d for axis %d", lhsShape[d], rhsShape[d], d);
if(lhsShape[1] != rhsShape[0])
Error(this, "matrix multiplication operands have incompatible inner dimension"
" %d and %d", lhsShape[1], rhsShape[0]);
// ret shape
TileType::ShapeInt retShape = {lhsShape[0], rhsShape[1]};
for(int d = 2; d < lhsRank; d++)
retShape.push_back(lhsShape[d]);
QualType retType = lhsType->Derived();
if(retType != rhsType->Derived())
Error(this, "matrix multiplication operands have incompatible data types");
ArithmType* ScalType = lhsType->ScalarType()->ToArithm();
if(ScalType->Tag() & T_HALF)
ScalType = ArithmType::New(T_FLOAT);
type_ = TileType::New(retShape, ScalType);
}
void BinaryOp::ShiftOpTypeChecking() {
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
auto lhsType = lhsScalType->ToArithm();
auto rhsType = rhsScalType->ToArithm();
if (!lhsType || !lhsType->IsInteger() || !rhsType || !rhsType->IsInteger())
Error(this, "expect integers for shift operator");
lhs_ = Expr::MayCast(lhs_, ScalarOrLikeTile(lhs_, ArithmType::IntegerPromote(lhsType)));
rhs_ = Expr::MayCast(rhs_, ScalarOrLikeTile(rhs_, ArithmType::IntegerPromote(rhsType)));
type_ = lhs_->Type();
Broadcast(this, lhs_, rhs_, type_);
}
void BinaryOp::RelationalOpTypeChecking() {
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
if (lhsScalType->ToPointer() || rhsScalType->ToPointer()) {
EnsureCompatible(lhsScalType, rhsScalType);
} else {
if (!lhsScalType->IsReal() || !rhsScalType->IsReal()) {
Error(this, "expect real type of operands");
}
Convert();
}
type_ = ArithmType::New(T_BOOL);
Broadcast(this, lhs_, rhs_, type_);
}
void BinaryOp::EqualityOpTypeChecking() {
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
if (lhsScalType->ToPointer() || rhsScalType->ToPointer()) {
EnsureCompatibleOrVoidPointer(lhsScalType, rhsScalType);
} else {
if (!lhsScalType->ToArithm() || !rhsScalType->ToArithm())
Error(this, "invalid operands to binary %s", tok_->str_.c_str());
Convert();
}
type_ = ArithmType::New(T_BOOL);
Broadcast(this, lhs_, rhs_, type_);
}
void BinaryOp::BitwiseOpTypeChecking() {
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
if (!lhsScalType->IsInteger() || !rhsScalType->IsInteger())
Error(this, "operands of '&' should be integer");
type_ = Convert();
Broadcast(this, lhs_, rhs_, type_);
}
void BinaryOp::LogicalOpTypeChecking() {
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
if (!lhsScalType->IsScalar() || !rhsScalType->IsScalar())
Error(this, "the operand should be arithmetic type or pointer");
type_ = ArithmType::New(T_BOOL);
Broadcast(this, lhs_, rhs_, type_);
}
void BinaryOp::AssignOpTypeChecking() {
if (lhs_->IsConstQualified()) {
Error(lhs_, "left operand of '=' is const qualified");
} else if (!lhs_->IsLVal()) {
Error(lhs_, "lvalue expression expected");
}
::Type* lhsScalType = TryExtractScalarType(this, lhs_);
::Type* rhsScalType = TryExtractScalarType(this, rhs_);
if (!lhsScalType->ToArithm() || !rhsScalType->ToArithm()) {
EnsureCompatibleOrVoidPointer(lhsScalType, rhsScalType);
}
// The other constraints are lefted to cast operator
rhs_ = Expr::MayCast(rhs_, ScalarOrLikeTile(rhs_, lhsScalType));
type_ = lhs_->Type();
rhs_ = UnaryOp::New(Token::CAST, rhs_, type_);
}
/*
* Unary Operators
*/
UnaryOp* UnaryOp::New(int op, Expr* operand, QualType type, int info) {
auto ret = new (unaryOpPool.Alloc()) UnaryOp(op, operand, type, info);
ret->pool_ = &unaryOpPool;
ret->TypeChecking();
return ret;
}
int UnaryOp::encodeRed(int ax, int tag) {
int result = 0;
result |= ax;
result |= tag << 16;
return result;
}
void UnaryOp::decodeRed(int info, int& ax, int& tag) {
ax = info & 0x0000FFFF;
tag = (info & 0xFFFF0000) >> 16;
}
bool UnaryOp::IsLVal() {
// Only deref('*') could be lvalue;
return op_ == Token::DEREF;
}
::Type* UnaryOp::Convert() {
auto scalType = operand_->Type()->ScalarType();
assert(scalType);
auto arithmType = scalType->ToArithm();
assert(arithmType);
if (arithmType->IsInteger())
arithmType = ArithmType::IntegerPromote(arithmType);
::Type* retType = ScalarOrLikeTile(operand_, arithmType);
operand_ = Expr::MayCast(operand_, retType);
return retType;
}
void UnaryOp::TypeChecking() {
switch (op_) {
case Token::POSTFIX_INC:
case Token::POSTFIX_DEC:
case Token::PREFIX_INC:
case Token::PREFIX_DEC:
return IncDecOpTypeChecking();
case Token::ADDR:
return AddrOpTypeChecking();
case Token::DEREF:
return DerefOpTypeChecking();
case Token::PLUS:
case Token::MINUS:
case '~':
case '!':
return UnaryArithmOpTypeChecking();
case Token::BITCAST:
return BitcastOpTypeChecking();
case Token::CAST:
return CastOpTypeChecking();
case Token::REDUCE:
return ReduceOpTypeChecking();
case Token::EXP:
case Token::LOG:
case Token::SQRTF:
return IntrinsicOpTypeChecking();
default:
assert(false);
}
}
void UnaryOp::IncDecOpTypeChecking() {
if (operand_->IsConstQualified()) {
Error(this, "increment/decrement of const qualified expression");
} else if (!operand_->IsLVal()) {
Error(this, "lvalue expression expected");
}
auto scalType = TryExtractScalarType(this, operand_);
if (!scalType->IsReal() && !scalType->ToPointer()) {
Error(this, "expect operand of real type or pointer");
}
type_ = operand_->Type();
}
void UnaryOp::AddrOpTypeChecking() {
auto funcType = operand_->Type()->ToFunc();
if (funcType == nullptr && !operand_->IsLVal())
Error(this, "expression must be an lvalue or function designator");
if(operand_->Type()->IsTile())
Error(this, "cannot take the address of a tile");
type_ = PointerType::New(operand_->Type());
}
void UnaryOp::DerefOpTypeChecking() {
auto scalType = TryExtractScalarType(this, operand_);
auto pointerType = scalType->ToPointer();
if (!pointerType)
Error(this, "pointer expected for deref operator '*'");
type_ = ScalarOrLikeTile(operand_, pointerType->Derived().GetPtr());
}
void UnaryOp::ReduceOpTypeChecking() {
int ax, tag;
decodeRed(info_, ax, tag);
auto tileType = operand_->Type()->ToTile();
if(!tileType)
Error(this, "array expected for reduction operation");
auto shape = tileType->Shape();
shape.erase(shape.begin() + ax);
if(shape.empty())
type_ = tileType->Derived();
else
type_ = TileType::New(shape, tileType->Derived());
}
void UnaryOp::UnaryArithmOpTypeChecking() {
auto scalType = TryExtractScalarType(this, operand_);
if (Token::PLUS == op_ || Token::MINUS == op_) {
if (!scalType->ToArithm())
Error(this, "Arithmetic type expected");
Convert();
type_ = operand_->Type();
} else if ('~' == op_) {
if (!scalType->IsInteger())
Error(this, "integer expected for operator '~'");
Convert();
type_ = operand_->Type();
} else if (!scalType->IsScalar()) {
Error(this, "arithmetic type or pointer expected for operator '!'");
} else {
type_ = ScalarOrLikeTile(operand_, ArithmType::New(T_INT));
}
}
void UnaryOp::BitcastOpTypeChecking() {
auto operandType = Type::MayCast(operand_->Type());
if(type_->Width() != operandType->Width())
Error(this, "cannot bitcast to type of different width");
}
void UnaryOp::CastOpTypeChecking() {
auto operandType = Type::MayCast(operand_->Type());
// The type_ has been initiated to dest type
if (type_->ToVoid()) {
// The expression becomes a void expression
} else if(type_->IsTile() || operandType->IsTile()) {
/* Broadcasting rules:
* 1. Tiles with 1 element can be converted to scalar
* 2. Scalar can be converted to tiles of any shapes
* 3. Tiles can be converted to another tile only if the
* mismatching dimensions are unitary
*/
if(type_->IsScalar() && operandType->ToTile()->NumEle() != 1)
Error(this, "tile with more than one element cannot be casted to scalar");
if(type_->IsTile() && operandType->IsTile()){
auto operandShape = operandType->ToTile()->Shape();
auto shape = type_->ToTile()->Shape();
// this is a shape downcast
if(operandShape.size() > shape.size()){
size_t operandNumel = 1;
size_t numel = 1;
for(auto x: operandShape)
operandNumel *= x;
for(auto x: shape)
numel *= x;
if(operandNumel != numel)
Error(this, "cast cannot change number of elements");
return;
}
// this is a shape upcast
while(operandShape.size() < shape.size())
operandShape.insert(operandShape.begin(), 1);
for(size_t i = 0; i < shape.size(); i++) {
if(shape[i] != 1 && operandShape[i] != 1 && shape[i] != operandShape[i])
Error(this, "cannot broadcast dimension %d "
"for operands of shape %d and %d",
i, shape[i], operandShape[i]);
}
}
} else if (!type_->IsScalar() || !operandType->IsScalar()) {
if (!type_->Compatible(*operandType))
Error(this, "the cast type should be arithemetic type or pointer");
} else if (type_->IsFloat() && operandType->ToPointer()) {
Error(this, "cannot cast a pointer to floating");
} else if (type_->ToPointer() && operandType->IsFloat()) {
Error(this, "cannot cast a floating to pointer");
}
}
void UnaryOp::IntrinsicOpTypeChecking() {
type_ = ScalarOrLikeTile(operand_, ArithmType::New(T_FLOAT));
}
/*
* Transposition Operator
*/
void TransOp::TypeChecking() {
auto tileType = operand_->Type()->ToTile();
if(!tileType)
Error(this, "tile expected for transposition operator '^'");
auto opShape = tileType->Shape();
if(perm_.size() != opShape.size())
Error(this, "invalid permutations");
// permutate input shape
TileType::ShapeInt resShape(opShape.size());
for(int d = 0; d < opShape.size(); d++)
resShape[d] = opShape[perm_[d]];
type_ = TileType::New(resShape, tileType->Derived());
}
TransOp* TransOp::New(const PermInt& perm, Expr* operand) {
auto ret = new (transOpPool.Alloc()) TransOp(perm, operand);
ret->pool_ = &transOpPool;
ret->TypeChecking();
return ret;
}
/*
* Conditional Operator
*/
ConditionalOp* ConditionalOp::New(const Token* tok,
Expr* cond,
Expr* exprTrue,
Expr* exprFalse) {
auto ret = new (conditionalOpPool.Alloc())
ConditionalOp(cond, exprTrue, exprFalse);
ret->pool_ = &conditionalOpPool;
ret->TypeChecking();
return ret;
}
ArithmType* ConditionalOp::Convert() {
auto lhsType = exprTrue_->Type()->ScalarType()->ToArithm();
auto rhsType = exprFalse_->Type()->ScalarType()->ToArithm();
assert(lhsType && rhsType);
auto type = ArithmType::MaxType(lhsType, rhsType);
if (lhsType != type) { // Pointer comparation is enough!
exprTrue_ = UnaryOp::New(Token::CAST, exprTrue_, type);
}
if (rhsType != type) {
exprFalse_ = UnaryOp::New(Token::CAST, exprFalse_, type);
}
return type;
}
void ConditionalOp::TypeChecking() {
auto condScalarType = TryExtractScalarType(this, cond_);
if (!condScalarType) {
Error(cond_->Tok(), "condition must be tile or scalar");
}
auto lhsType = TryExtractScalarType(this, exprTrue_);
auto rhsType = TryExtractScalarType(this, exprFalse_);
if (lhsType->ToArithm() && rhsType->ToArithm()) {
type_ = Convert();
} else {
EnsureCompatibleOrVoidPointer(lhsType, rhsType);
type_ = lhsType;
}
BinaryOp::Broadcast(this, exprFalse_, exprTrue_, type_);
}
/*
* Function Call
*/
FuncCall* FuncCall::New(Expr* designator, const ArgList& args) {
auto ret = new (funcCallPool.Alloc()) FuncCall(designator, args);
ret->pool_ = &funcCallPool;
ret->TypeChecking();
return ret;
}
void FuncCall::TypeChecking() {
auto pointerType = designator_->Type()->ToPointer();
if (pointerType) {
if (!pointerType->Derived()->ToFunc())
Error(designator_, "called object is not a function or function pointer");
// Convert function pointer to function type
designator_ = UnaryOp::New(Token::DEREF, designator_);
}
auto funcType = designator_->Type()->ToFunc();
if (!funcType) {
Error(designator_, "called object is not a function or function pointer");
} else if (!funcType->Derived()->ToVoid() &&
!funcType->Derived()->Complete()) {
Error(designator_, "invalid use of incomplete return type");
}
auto arg = args_.begin();
for (auto param: funcType->Params()) {
if (arg == args_.end())
Error(this, "too few arguments for function call");
*arg = Expr::MayCast(*arg, param->Type());
++arg;
}
if (arg != args_.end() && !funcType->Variadic())
Error(this, "too many arguments for function call");
// C11 6.5.2.2 [6]: promote float to double if it has no prototype
while (arg != args_.end()) {
if ((*arg)->Type()->IsFloat() && (*arg)->Type()->Width() == 4) {
auto type = ArithmType::New(T_DOUBLE);
*arg = UnaryOp::New(Token::CAST, *arg, type);
}
++arg;
}
type_ = funcType->Derived();
}
/*
* Identifier
*/
Identifier* Identifier::New(const Token* tok,
QualType type,
enum Linkage linkage,
const AttrList &attrList) {
auto ret = new (identifierPool.Alloc()) Identifier(tok, type, linkage, attrList);
ret->pool_ = &identifierPool;
return ret;
}
Enumerator* Enumerator::New(const Token* tok, int val) {
auto ret = new (enumeratorPool.Alloc()) Enumerator(tok, val);
ret->pool_ = &enumeratorPool;
return ret;
}
Declaration* Declaration::New(Object* obj) {
auto ret = new (initializationPool.Alloc()) Declaration(obj);
ret->pool_ = &initializationPool;
return ret;
}
void Declaration::AddInit(Initializer init) {
init.expr_ = Expr::MayCast(init.expr_, init.type_);
auto res = inits_.insert(init);
if (!res.second) {
inits_.erase(res.first);
inits_.insert(init);
}
}
/*
* Object
*/
Object* Object::New(const Token* tok,
QualType type,
int storage,
enum Linkage linkage,
unsigned char bitFieldBegin,
unsigned char bitFieldWidth,
const AttrList& attrList) {
auto ret = new (objectPool.Alloc())
Object(tok, type, storage, linkage, bitFieldBegin, bitFieldWidth, attrList);
ret->pool_ = &objectPool;
static long id = 0;
if (ret->IsStatic() || ret->Anonymous())
ret->id_ = ++id;
return ret;
}
Object* Object::NewAnony(const Token* tok,
QualType type,
int storage,
enum Linkage linkage,
unsigned char bitFieldBegin,
unsigned char bitFieldWidth,
const AttrList& attrList) {
auto ret = new (objectPool.Alloc())
Object(tok, type, storage, linkage, bitFieldBegin, bitFieldWidth, attrList);
ret->pool_ = &objectPool;
ret->anonymous_ = true;
static long id = 0;
if (ret->IsStatic() || ret->anonymous_)
ret->id_ = ++id;
return ret;
}
/*
* Constant
*/
Constant* Constant::New(const Token* tok, int tag, long val) {
auto type = ArithmType::New(tag);
auto ret = new (constantPool.Alloc()) Constant(tok, type, val);
ret->pool_ = &constantPool;
return ret;
}
Constant* Constant::New(const Token* tok, int tag, double val) {
auto type = ArithmType::New(tag);
auto ret = new (constantPool.Alloc()) Constant(tok, type, val);
ret->pool_ = &constantPool;
return ret;
}
Constant* Constant::New(const Token* tok, int tag, const std::string* val) {
auto derived = ArithmType::New(tag);
auto type = ArrayType::New(val->size() / derived->Width(), derived);
auto ret = new (constantPool.Alloc()) Constant(tok, type, val);
ret->pool_ = &constantPool;
static long id = 0;
ret->id_ = ++id;
return ret;
}
std::string Constant::SValRepr() const {
std::vector<char> buf(4 * sval_->size() + 1);
for (size_t i = 0; i < sval_->size(); ++i) {
int c = (*sval_)[i];
sprintf(&buf[i * 4], "\\x%1x%1x", (c >> 4) & 0xf, c & 0xf);
}
return std::string(buf.begin(), buf.end() - 1);
}
/*
* TempVar
*/
TempVar* TempVar::New(QualType type) {
auto ret = new (tempVarPool.Alloc()) TempVar(type);
ret->pool_ = &tempVarPool;
return ret;
}
/*
* Statement
*/
EmptyStmt* EmptyStmt::New() {
auto ret = new (emptyStmtPool.Alloc()) EmptyStmt();
ret->pool_ = &emptyStmtPool;
return ret;
}
// The else stmt could be null
IfStmt* IfStmt::New(Expr* cond, Stmt* then, Stmt* els) {
auto ret = new (ifStmtPool.Alloc()) IfStmt(cond, then, els);
ret->pool_ = &ifStmtPool;
return ret;
}
CompoundStmt* CompoundStmt::New(std::list<Stmt*>& stmts, ::Scope* scope) {
auto ret = new (compoundStmtPool.Alloc()) CompoundStmt(stmts, scope);
ret->pool_ = &compoundStmtPool;
return ret;
}
ForStmt* ForStmt::New(Stmt* body, Stmt* init, Expr* cond, Expr* step) {
auto ret = new (forStmtPool.Alloc()) ForStmt(body, init, cond, step);
ret->pool_ = &forStmtPool;
return ret;
}
JumpStmt* JumpStmt::New(LabelStmt* label) {
auto ret = new (jumpStmtPool.Alloc()) JumpStmt(label);
ret->pool_ = &jumpStmtPool;
return ret;
}
ReturnStmt* ReturnStmt::New(Expr* expr) {
auto ret = new (returnStmtPool.Alloc()) ReturnStmt(expr);
ret->pool_ = &returnStmtPool;
return ret;
}
LabelStmt* LabelStmt::New() {
auto ret = new (labelStmtPool.Alloc()) LabelStmt();
ret->pool_ = &labelStmtPool;
return ret;
}
FuncDef* FuncDef::New(Identifier* ident, LabelStmt* retLabel) {
auto ret = new (funcDefPool.Alloc()) FuncDef(ident, retLabel);
ret->pool_ = &funcDefPool;
return ret;
}
bool Initializer::operator<(const Initializer& rhs) const {
if (offset_ < rhs.offset_)
return true;
return (offset_ == rhs.offset_ && bitFieldBegin_ < rhs.bitFieldBegin_);
}
| 28.252244 | 90 | 0.645982 | [
"object",
"shape",
"vector"
] |
6ab520d8b5c07c3f3c0eddcc807b8386f068b1be | 1,383 | hpp | C++ | libautom8/include/autom8/device/x10/cm15a/cm15a_device_system.hpp | clangen/autom8 | 69db4176fecd133fc352a95176dbc812d43e128f | [
"Artistic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2019-03-02T03:48:28.000Z | 2022-03-28T10:54:54.000Z | libautom8/include/autom8/device/x10/cm15a/cm15a_device_system.hpp | clangen/autom8 | 69db4176fecd133fc352a95176dbc812d43e128f | [
"Artistic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2020-07-15T21:42:11.000Z | 2020-07-15T21:42:11.000Z | libautom8/include/autom8/device/x10/cm15a/cm15a_device_system.hpp | clangen/autom8 | 69db4176fecd133fc352a95176dbc812d43e128f | [
"Artistic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | #ifndef __C_AUTOM8_CM15A_DEVICE_SYSTEM_HPP__
#define __C_AUTOM8_CM15A_DEVICE_SYSTEM_HPP__
#include <windows.h>
#include <boost/shared_ptr.hpp>
#include <autom8/util/signal_handler.hpp>
#include <autom8/device/device_model.hpp>
#include <autom8/device/x10/x10_device_system.hpp>
#include <autom8/device/x10/x10_device.hpp>
#include <autom8/device/x10/x10_device_controller.hpp>
namespace autom8 {
class cm15a_device_system: public x10_device_system, public signal_handler {
public:
cm15a_device_system();
virtual ~cm15a_device_system();
virtual std::string description() { return "cm15a (usb)"; }
virtual device_model& model();
virtual bool send_device_message(command_type message_type, const char* message_params);
virtual std::string controller_type() const { return "cm15a"; }
virtual void requery_device_status(const std::string& address);
virtual void on_message_received(const char ** argv, int argc);
private:
void on_device_removed(database_id id);
void on_device_updated(database_id id);
HMODULE dll_;
device_list devices_;
x10_device_controller controller_;
device_model_ptr model_;
device_factory_ptr factory_;
bool is_functional_;
};
}
#endif // __C_AUTOM8_CM15A_DEVICE_SYSTEM_HPP__ | 35.461538 | 97 | 0.711497 | [
"model"
] |
6ab830fa280aa0eceacb48d417d762ba8e7eef17 | 12,744 | cpp | C++ | modules/aruco/perf/perf_aruco.cpp | pccvlab/opencv_contrib | f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93 | [
"Apache-2.0"
] | null | null | null | modules/aruco/perf/perf_aruco.cpp | pccvlab/opencv_contrib | f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93 | [
"Apache-2.0"
] | null | null | null | modules/aruco/perf/perf_aruco.cpp | pccvlab/opencv_contrib | f6a39c5d01a7b2d2bb223a2a67beb9736fce7d93 | [
"Apache-2.0"
] | null | null | null | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "perf_precomp.hpp"
namespace opencv_test {
using namespace perf;
typedef tuple<bool, int> UseArucoParams;
typedef TestBaseWithParam<UseArucoParams> EstimateAruco;
#define ESTIMATE_PARAMS Combine(Values(false, true), Values(-1))
static double deg2rad(double deg) { return deg * CV_PI / 180.; }
class MarkerPainter
{
private:
int imgMarkerSize = 0;
Mat cameraMatrix;
public:
MarkerPainter(const int size)
{
setImgMarkerSize(size);
}
void setImgMarkerSize(const int size)
{
imgMarkerSize = size;
cameraMatrix = Mat::eye(3, 3, CV_64FC1);
cameraMatrix.at<double>(0, 0) = cameraMatrix.at<double>(1, 1) = imgMarkerSize;
cameraMatrix.at<double>(0, 2) = imgMarkerSize / 2.0;
cameraMatrix.at<double>(1, 2) = imgMarkerSize / 2.0;
}
static std::pair<Mat, Mat> getSyntheticRT(double yaw, double pitch, double distance)
{
auto rvec_tvec = std::make_pair(Mat(3, 1, CV_64FC1), Mat(3, 1, CV_64FC1));
Mat& rvec = rvec_tvec.first;
Mat& tvec = rvec_tvec.second;
// Rvec
// first put the Z axis aiming to -X (like the camera axis system)
Mat rotZ(3, 1, CV_64FC1);
rotZ.ptr<double>(0)[0] = 0;
rotZ.ptr<double>(0)[1] = 0;
rotZ.ptr<double>(0)[2] = -0.5 * CV_PI;
Mat rotX(3, 1, CV_64FC1);
rotX.ptr<double>(0)[0] = 0.5 * CV_PI;
rotX.ptr<double>(0)[1] = 0;
rotX.ptr<double>(0)[2] = 0;
Mat camRvec, camTvec;
composeRT(rotZ, Mat(3, 1, CV_64FC1, Scalar::all(0)), rotX, Mat(3, 1, CV_64FC1, Scalar::all(0)),
camRvec, camTvec);
// now pitch and yaw angles
Mat rotPitch(3, 1, CV_64FC1);
rotPitch.ptr<double>(0)[0] = 0;
rotPitch.ptr<double>(0)[1] = pitch;
rotPitch.ptr<double>(0)[2] = 0;
Mat rotYaw(3, 1, CV_64FC1);
rotYaw.ptr<double>(0)[0] = yaw;
rotYaw.ptr<double>(0)[1] = 0;
rotYaw.ptr<double>(0)[2] = 0;
composeRT(rotPitch, Mat(3, 1, CV_64FC1, Scalar::all(0)), rotYaw,
Mat(3, 1, CV_64FC1, Scalar::all(0)), rvec, tvec);
// compose both rotations
composeRT(camRvec, Mat(3, 1, CV_64FC1, Scalar::all(0)), rvec,
Mat(3, 1, CV_64FC1, Scalar::all(0)), rvec, tvec);
// Tvec, just move in z (camera) direction the specific distance
tvec.ptr<double>(0)[0] = 0.;
tvec.ptr<double>(0)[1] = 0.;
tvec.ptr<double>(0)[2] = distance;
return rvec_tvec;
}
std::pair<Mat, vector<Point2f> > getProjectMarker(int id, double yaw, double pitch,
const Ptr<aruco::DetectorParameters>& parameters,
const Ptr<aruco::Dictionary>& dictionary)
{
auto marker_corners = std::make_pair(Mat(imgMarkerSize, imgMarkerSize, CV_8UC1, Scalar::all(255)), vector<Point2f>());
Mat& img = marker_corners.first;
vector<Point2f>& corners = marker_corners.second;
// canonical image
const int markerSizePixels = static_cast<int>(imgMarkerSize/sqrt(2.f));
aruco::drawMarker(dictionary, id, markerSizePixels, img, parameters->markerBorderBits);
// get rvec and tvec for the perspective
const double distance = 0.1;
auto rvec_tvec = MarkerPainter::getSyntheticRT(yaw, pitch, distance);
Mat& rvec = rvec_tvec.first;
Mat& tvec = rvec_tvec.second;
const float markerLength = 0.05f;
vector<Point3f> markerObjPoints;
markerObjPoints.emplace_back(Point3f(-markerLength / 2.f, +markerLength / 2.f, 0));
markerObjPoints.emplace_back(markerObjPoints[0] + Point3f(markerLength, 0, 0));
markerObjPoints.emplace_back(markerObjPoints[0] + Point3f(markerLength, -markerLength, 0));
markerObjPoints.emplace_back(markerObjPoints[0] + Point3f(0, -markerLength, 0));
// project markers and draw them
Mat distCoeffs(5, 1, CV_64FC1, Scalar::all(0));
projectPoints(markerObjPoints, rvec, tvec, cameraMatrix, distCoeffs, corners);
vector<Point2f> originalCorners;
originalCorners.emplace_back(Point2f(0.f, 0.f));
originalCorners.emplace_back(originalCorners[0]+Point2f((float)markerSizePixels, 0));
originalCorners.emplace_back(originalCorners[0]+Point2f((float)markerSizePixels, (float)markerSizePixels));
originalCorners.emplace_back(originalCorners[0]+Point2f(0, (float)markerSizePixels));
Mat transformation = getPerspectiveTransform(originalCorners, corners);
warpPerspective(img, img, transformation, Size(imgMarkerSize, imgMarkerSize), INTER_NEAREST, BORDER_CONSTANT,
Scalar::all(255));
return marker_corners;
}
std::pair<Mat, map<int, vector<Point2f> > > getProjectMarkersTile(const int numMarkers,
const Ptr<aruco::DetectorParameters>& params,
const Ptr<aruco::Dictionary>& dictionary)
{
Mat tileImage(imgMarkerSize*numMarkers, imgMarkerSize*numMarkers, CV_8UC1, Scalar::all(255));
map<int, vector<Point2f> > idCorners;
int iter = 0, pitch = 0, yaw = 0;
for (int i = 0; i < numMarkers; i++)
{
for (int j = 0; j < numMarkers; j++)
{
int currentId = iter;
auto marker_corners = getProjectMarker(currentId, deg2rad(70+yaw), deg2rad(pitch), params, dictionary);
Point2i startPoint(j*imgMarkerSize, i*imgMarkerSize);
Mat tmp_roi = tileImage(Rect(startPoint.x, startPoint.y, imgMarkerSize, imgMarkerSize));
marker_corners.first.copyTo(tmp_roi);
for (Point2f& point: marker_corners.second)
point += static_cast<Point2f>(startPoint);
idCorners[currentId] = marker_corners.second;
auto test = idCorners[currentId];
yaw = (yaw + 10) % 51; // 70+yaw >= 70 && 70+yaw <= 120
iter++;
}
pitch = (pitch + 60) % 360;
}
return std::make_pair(tileImage, idCorners);
}
};
static inline double getMaxDistance(map<int, vector<Point2f> > &golds, const vector<int>& ids,
const vector<vector<Point2f> >& corners)
{
std::map<int, double> mapDist;
for (const auto& el : golds)
mapDist[el.first] = std::numeric_limits<double>::max();
for (size_t i = 0; i < ids.size(); i++)
{
int id = ids[i];
const auto gold_corners = golds.find(id);
if (gold_corners != golds.end()) {
double distance = 0.;
for (int c = 0; c < 4; c++)
distance = std::max(distance, cv::norm(gold_corners->second[c] - corners[i][c]));
mapDist[id] = distance;
}
}
return std::max_element(std::begin(mapDist), std::end(mapDist),
[](const pair<int, double>& p1, const pair<int, double>& p2){return p1.second < p2.second;})->second;
}
PERF_TEST_P(EstimateAruco, ArucoFirst, ESTIMATE_PARAMS)
{
UseArucoParams testParams = GetParam();
Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
detectorParams->minDistanceToBorder = 1;
detectorParams->markerBorderBits = 1;
detectorParams->cornerRefinementMethod = cv::aruco::CORNER_REFINE_SUBPIX;
const int markerSize = 100;
const int numMarkersInRow = 9;
//USE_ARUCO3
detectorParams->useAruco3Detection = get<0>(testParams);
if (detectorParams->useAruco3Detection) {
detectorParams->minSideLengthCanonicalImg = 32;
detectorParams->minMarkerLengthRatioOriginalImg = 0.04f / numMarkersInRow;
}
MarkerPainter painter(markerSize);
auto image_map = painter.getProjectMarkersTile(numMarkersInRow, detectorParams, dictionary);
// detect markers
vector<vector<Point2f> > corners;
vector<int> ids;
TEST_CYCLE()
{
aruco::detectMarkers(image_map.first, dictionary, corners, ids, detectorParams);
}
ASSERT_EQ(numMarkersInRow*numMarkersInRow, static_cast<int>(ids.size()));
double maxDistance = getMaxDistance(image_map.second, ids, corners);
ASSERT_LT(maxDistance, 3.);
SANITY_CHECK_NOTHING();
}
PERF_TEST_P(EstimateAruco, ArucoSecond, ESTIMATE_PARAMS)
{
UseArucoParams testParams = GetParam();
Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
detectorParams->minDistanceToBorder = 1;
detectorParams->markerBorderBits = 1;
detectorParams->cornerRefinementMethod = cv::aruco::CORNER_REFINE_SUBPIX;
//USE_ARUCO3
detectorParams->useAruco3Detection = get<0>(testParams);
if (detectorParams->useAruco3Detection) {
detectorParams->minSideLengthCanonicalImg = 64;
detectorParams->minMarkerLengthRatioOriginalImg = 0.f;
}
const int markerSize = 200;
const int numMarkersInRow = 11;
MarkerPainter painter(markerSize);
auto image_map = painter.getProjectMarkersTile(numMarkersInRow, detectorParams, dictionary);
// detect markers
vector<vector<Point2f> > corners;
vector<int> ids;
TEST_CYCLE()
{
aruco::detectMarkers(image_map.first, dictionary, corners, ids, detectorParams);
}
ASSERT_EQ(numMarkersInRow*numMarkersInRow, static_cast<int>(ids.size()));
double maxDistance = getMaxDistance(image_map.second, ids, corners);
ASSERT_LT(maxDistance, 3.);
SANITY_CHECK_NOTHING();
}
struct Aruco3Params
{
bool useAruco3Detection = false;
float minMarkerLengthRatioOriginalImg = 0.f;
int minSideLengthCanonicalImg = 0;
Aruco3Params(bool useAruco3, float minMarkerLen, int minSideLen): useAruco3Detection(useAruco3),
minMarkerLengthRatioOriginalImg(minMarkerLen),
minSideLengthCanonicalImg(minSideLen) {}
friend std::ostream& operator<<(std::ostream& os, const Aruco3Params& d)
{
os << d.useAruco3Detection << " " << d.minMarkerLengthRatioOriginalImg << " " << d.minSideLengthCanonicalImg;
return os;
}
};
typedef tuple<Aruco3Params, pair<int, int>> ArucoTestParams;
typedef TestBaseWithParam<ArucoTestParams> EstimateLargeAruco;
#define ESTIMATE_FHD_PARAMS Combine(Values(Aruco3Params(false, 0.f, 0), Aruco3Params(true, 0.f, 32), \
Aruco3Params(true, 0.015f, 32), Aruco3Params(true, 0.f, 16), Aruco3Params(true, 0.0069f, 16)), \
Values(std::make_pair(1440, 1), std::make_pair(480, 3), std::make_pair(144, 10)))
PERF_TEST_P(EstimateLargeAruco, ArucoFHD, ESTIMATE_FHD_PARAMS)
{
ArucoTestParams testParams = GetParam();
Ptr<aruco::Dictionary> dictionary = aruco::getPredefinedDictionary(aruco::DICT_6X6_250);
Ptr<aruco::DetectorParameters> detectorParams = aruco::DetectorParameters::create();
detectorParams->minDistanceToBorder = 1;
detectorParams->markerBorderBits = 1;
detectorParams->cornerRefinementMethod = cv::aruco::CORNER_REFINE_SUBPIX;
//USE_ARUCO3
detectorParams->useAruco3Detection = get<0>(testParams).useAruco3Detection;
if (detectorParams->useAruco3Detection) {
detectorParams->minSideLengthCanonicalImg = get<0>(testParams).minSideLengthCanonicalImg;
detectorParams->minMarkerLengthRatioOriginalImg = get<0>(testParams).minMarkerLengthRatioOriginalImg;
}
const int markerSize = get<1>(testParams).first; // 1440 or 480 or 144
const int numMarkersInRow = get<1>(testParams).second; // 1 or 3 or 144
MarkerPainter painter(markerSize); // num pixels is 1440x1440 as in FHD 1920x1080
auto image_map = painter.getProjectMarkersTile(numMarkersInRow, detectorParams, dictionary);
// detect markers
vector<vector<Point2f> > corners;
vector<int> ids;
TEST_CYCLE()
{
aruco::detectMarkers(image_map.first, dictionary, corners, ids, detectorParams);
}
ASSERT_EQ(numMarkersInRow*numMarkersInRow, static_cast<int>(ids.size()));
double maxDistance = getMaxDistance(image_map.second, ids, corners);
ASSERT_LT(maxDistance, 3.);
SANITY_CHECK_NOTHING();
}
}
| 42.765101 | 126 | 0.645559 | [
"vector"
] |
6ac0fd844f1e0b5cd78b02f3ea6a4a869267eb7c | 20,469 | cc | C++ | src/nbt/chunk.cc | kofuk/pixel-terrain | f39e2a0120aab5a11311f57cfd1ab46efa65fddd | [
"MIT"
] | 2 | 2020-10-16T08:46:45.000Z | 2020-11-04T02:19:19.000Z | src/nbt/chunk.cc | kofuk/pixel-terrain | f39e2a0120aab5a11311f57cfd1ab46efa65fddd | [
"MIT"
] | null | null | null | src/nbt/chunk.cc | kofuk/pixel-terrain | f39e2a0120aab5a11311f57cfd1ab46efa65fddd | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: MIT
/* Class to access chunk data structure.
This implementation based on matcool/anvil-parser with
performance tuning and biome support. */
#include <cmath>
#include <cstdint>
#include <exception>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
#include "nbt/chunk.hh"
#include "nbt/constants.hh"
#if USE_V3_NBT_PARSER
#include "nbt/nbt.hh"
#include "nbt/tag.hh"
#else
#include "nbt/pull_parser/nbt_pull_parser.hh"
#endif
namespace pixel_terrain::anvil {
#if USE_V3_NBT_PARSER
chunk::chunk(std::vector<std::uint8_t> const &data) {
palettes.fill(nullptr);
block_states.fill(nullptr);
auto *nbt_file = nbt::nbt::from_iterator(data.begin(), data.end());
if (nbt_file == nullptr) {
throw chunk_parse_error("Parse error");
}
try {
init_fields(*nbt_file);
} catch (...) {
delete nbt_file;
std::rethrow_exception(std::current_exception());
}
delete nbt_file;
}
#else
chunk::chunk(std::vector<std::uint8_t> *data)
: parser(nbt::nbt_pull_parser(data->data(), data->size())),
chunk_data_(data) {
palettes.fill(nullptr);
block_states.fill(nullptr);
}
#endif
chunk::~chunk() {
#if !USE_V3_NBT_PARSER
delete chunk_data_;
#endif
for (std::vector<std::string> *e : palettes) {
delete e;
}
for (std::vector<std::uint64_t> *e : block_states) {
delete e;
}
}
#if USE_V3_NBT_PARSER
namespace {
auto const sections_path =
nbt::nbt_path::compile("//Level/Sections").set_ignore_empty_list();
auto const last_update_path =
nbt::nbt_path::compile("//Level/LastUpdate")
.set_ignore_empty_list();
auto const y_path =
nbt::nbt_path::compile("/Y").set_ignore_empty_list();
auto const block_states_path =
nbt::nbt_path::compile("/BlockStates").set_ignore_empty_list();
auto const palette_path =
nbt::nbt_path::compile("/Palette").set_ignore_empty_list();
#if USE_BLOCK_LIGHT_DATA
auto const block_light_path =
nbt::nbt_path::compile("/BlockLight").set_ignore_empty_list();
#endif
auto const name_path =
nbt::nbt_path::compile("/Name").set_ignore_empty_list();
auto const biomes_path =
nbt::nbt_path::compile("//Level/Biomes").set_ignore_empty_list();
auto const data_version_path =
nbt::nbt_path::compile("//DataVersion").set_ignore_empty_list();
} // namespace
#if USE_BLOCK_LIGHT_DATA
auto decode_nibble(std::vector<std::uint8_t> input)
-> std::vector<std::uint8_t> {
std::vector<uint8_t> result;
for (auto const &e : input) {
result.push_back(e & 0xf);
result.push_back(e >> 4);
}
return result;
}
#endif
void chunk::init_fields(nbt::nbt const &nbt_file) noexcept(false) {
auto *sections_node =
nbt_file.query<nbt::tag_list_payload>(sections_path);
if (sections_node == nullptr) {
throw not_generated_chunk_error("Sections data not found");
}
if (sections_node->payload_type() != nbt::tag_type::TAG_COMPOUND) {
nbt::tag_type got_type = sections_node->payload_type();
delete sections_node;
throw broken_chunk_error("Invalid Sections data type: " +
nbt::tag_type_repr(got_type));
}
for (std::size_t i = 0, E = (*sections_node)->size(); i < E; ++i) {
auto *node = sections_node->get<nbt::tag_compound_payload>(i);
auto *y_node = node->query<nbt::tag_byte_payload>(y_path);
if (y_node == nullptr) {
continue;
}
std::uint8_t y = **y_node;
delete y_node;
if (y < 0 || 16 <= y) {
/* Out of range. */
continue;
}
auto *block_states_node =
node->query<nbt::tag_long_array_payload>(block_states_path);
if (block_states_node == nullptr) {
/* If there's no BlockStates, there's no way to
refer to Palette, so we continue here. */
continue;
}
auto *states = new std::vector<std::uint64_t>;
for (std::uint64_t state : **block_states_node) {
states->push_back(state);
}
block_states[static_cast<std::size_t>(y)] = states;
delete block_states_node;
auto *palette_node =
node->query<nbt::tag_list_payload>(palette_path);
if (palette_node == nullptr ||
palette_node->payload_type() != nbt::tag_type::TAG_COMPOUND) {
delete palette_node;
continue;
}
auto *palette = new std::vector<std::string>;
for (std::size_t j = 0, F = (*palette_node)->size(); j < F; ++j) {
auto *element_node =
palette_node->get<nbt::tag_compound_payload>(j);
auto *name_node =
element_node->query<nbt::tag_string_payload>(name_path);
if (name_node == nullptr) {
continue;
}
palette->push_back(**name_node);
delete name_node;
}
palettes[static_cast<std::size_t>(y)] = palette;
delete palette_node;
#if USE_BLOCK_LIGHT_DATA
auto *block_light_node =
node->query<nbt::tag_byte_array_payload>(block_light_path);
if (block_light_node != nullptr) {
if ((*block_light_node)->size() == 2048) {
std::vector<std::uint8_t> nibbles =
decode_nibble(**block_light_node);
block_lights_[y] = std::move(nibbles);
}
delete block_light_node;
}
#endif
}
delete sections_node;
auto *last_update_node =
nbt_file.query<nbt::tag_long_payload>(last_update_path);
if (last_update_node == nullptr) {
throw broken_chunk_error("LastUpdate data not found");
}
last_update = **last_update_node;
delete last_update_node;
auto *biomes_node =
nbt_file.query<nbt::tag_int_array_payload>(biomes_path);
if (biomes_node == nullptr) {
throw broken_chunk_error("Biomes data not found");
}
biomes = **biomes_node;
delete biomes_node;
auto *data_version_node =
nbt_file.query<nbt::tag_int_payload>(data_version_path);
if (data_version_node == nullptr) {
throw broken_chunk_error("DataVersion data not found");
}
data_version = **data_version_node;
delete data_version_node;
}
#endif
auto chunk::get_last_update() noexcept(false) -> std::uint64_t {
#if !USE_V3_NBT_PARSER
make_sure_field_parsed(FIELD_LAST_UPDATE);
#endif
return last_update;
}
#if !USE_V3_NBT_PARSER
void chunk::parse_sections() {
nbt::parser_event ev = parser.next();
for (;;) {
if (ev == nbt::parser_event::TAG_END) {
break;
}
if (ev != nbt::parser_event::TAG_START) {
throw std::runtime_error("Broken Sections");
}
unsigned char y = nbt::biomes::CHUNK_MAX_Y;
/* parse first tag */
ev = parser.next();
if (ev == nbt::parser_event::TAG_END) {
ev = parser.next();
continue;
}
if (ev != nbt::parser_event::TAG_START) {
throw std::runtime_error("Broken contents of Sections");
}
/* if it is "Y", it propably invalid element in Sections so we check
* for it to skip early. */
if (parser.get_tag_type() == nbt::TAG_BYTE &&
parser.get_tag_name() == "Y") {
parser.next();
y = parser.get_byte();
if (y >= nbt::biomes::PALETTE_Y_MAX) {
/* we just throw away content in invalid element. */
for (int level = 2; level != 0;) {
ev = parser.next();
if (ev == nbt::parser_event::TAG_START) {
++level;
} else if (ev == nbt::parser_event::TAG_END) {
--level;
}
}
ev = parser.next();
continue;
}
ev = parser.next();
}
auto *palette = new std::vector<std::string>;
auto *block_state = new std::vector<std::uint64_t>;
for (;;) {
if (parser.get_tag_name() == "BlockStates") {
if (parser.get_tag_type() != nbt::TAG_LONG_ARRAY) {
throw std::runtime_error(
"BlockStates is not TAG_Long_Array");
}
for (; parser.next() == nbt::parser_event::DATA;) {
block_state->push_back(parser.get_long());
}
} else if (parser.get_tag_name() == "Palette") {
if (parser.get_tag_type() != nbt::TAG_LIST) {
throw std::runtime_error("Palette is not TAG_List");
}
ev = parser.next();
for (; ev != nbt::parser_event::TAG_END;) {
ev = parser.next();
for (; ev != nbt::parser_event::TAG_END;) {
if (ev == nbt::parser_event::TAG_START) {
if (parser.get_tag_type() == nbt::TAG_STRING &&
parser.get_tag_name() == "Name") {
/* parser_event::DATA */
parser.next();
palette->push_back(parser.get_string());
/* parser_event::TAG_END */
parser.next();
} else {
for (int i = 1; i != 0;) {
ev = parser.next();
if (ev ==
nbt::parser_event::TAG_START) {
++i;
} else if (ev ==
nbt::parser_event::TAG_END) {
--i;
}
}
}
}
ev = parser.next();
}
ev = parser.next();
}
} else if (parser.get_tag_name() == "Y") {
if (parser.get_tag_type() != nbt::TAG_BYTE) {
throw std::runtime_error("Y is not TAG_Byte");
}
/* update only if this tag was parsed above. */
if (ev != nbt::parser_event::TAG_END) {
parser.next();
y = parser.get_byte();
parser.next();
}
} else {
/* skip others because they aren't needed. */
for (int i = 1; i != 0;) {
ev = parser.next();
if (ev == nbt::parser_event::TAG_START) {
++i;
} else if (ev == nbt::parser_event::TAG_END) {
--i;
}
}
}
ev = parser.next();
if (ev == nbt::parser_event::TAG_START) {
continue;
}
if (ev == nbt::parser_event::TAG_END) {
break;
}
throw std::runtime_error("Broken Sections tag");
}
if (y >= nbt::biomes::PALETTE_Y_MAX) {
delete palette;
delete block_state;
} else {
palettes[y] = palette;
block_states[y] = block_state;
}
ev = parser.next();
}
}
void chunk::parse_fields() {
nbt::parser_event ev = parser.get_event_type();
while (ev != nbt::parser_event::DOCUMENT_END) {
if (ev == nbt::parser_event::TAG_START) {
tag_structure.push_back(parser.get_tag_name());
unsigned char f = current_field();
if (f == FIELD_SECTIONS) {
parse_sections();
return;
}
if (f == FIELD_LAST_UPDATE) {
ev = parser.next();
if (ev != nbt::parser_event::DATA ||
parser.get_tag_type() != nbt::TAG_LONG) {
throw std::runtime_error("LastUpdate is not TAG_Long");
}
last_update = parser.get_long();
parser.next();
return;
}
if (f == FIELD_BIOMES) {
if (parser.get_tag_type() != nbt::TAG_INT_ARRAY) {
throw std::runtime_error("Biomes is not TAG_Int_Array");
}
while (parser.next() == nbt::parser_event::DATA) {
biomes.push_back(parser.get_int());
}
return;
}
if (f == FIELD_DATA_VERSION) {
ev = parser.next();
if (ev != nbt::parser_event::DATA ||
parser.get_tag_type() != nbt::TAG_INT) {
throw std::runtime_error(
"DataVersion is not TAG_Int_Array");
}
data_version = parser.get_int();
parser.next();
return;
}
} else if (ev == nbt::parser_event::TAG_END) {
tag_structure.pop_back();
}
ev = parser.next();
}
}
void chunk::make_sure_field_parsed(unsigned char field) noexcept(false) {
if ((loaded_fields & field) == 0) {
do {
parse_fields();
} while ((loaded_fields & field) == 0 &&
parser.get_event_type() !=
nbt::parser_event::DOCUMENT_END);
if ((loaded_fields & field) == 0) {
throw std::runtime_error("Tag not found: " +
std::to_string(field));
}
}
}
auto chunk::current_field() -> unsigned char {
if (tag_structure.size() < 2 || !tag_structure[0].empty()) {
return 0;
}
unsigned char result = 0;
if (tag_structure[1] == "DataVersion") {
result = FIELD_DATA_VERSION;
} else if (tag_structure.size() >= 3 && tag_structure[0].empty() &&
tag_structure[1] == "Level") {
if (tag_structure[2] == "Sections") {
result = FIELD_SECTIONS;
} else if (tag_structure[2] == "LastUpdate") {
result = FIELD_LAST_UPDATE;
} else if (tag_structure[2] == "Biomes") {
result = FIELD_BIOMES;
}
}
loaded_fields |= result;
return result;
}
#endif // not USE_V3_NBT_PARSER
auto chunk::get_palette(unsigned char y) -> std::vector<std::string> * {
if (y >= nbt::biomes::PALETTE_Y_MAX) {
return nullptr;
}
#if !USE_V3_NBT_PARSER
make_sure_field_parsed(FIELD_SECTIONS);
#endif
return palettes[y];
}
auto chunk::get_biome(int32_t x, int32_t y, int32_t z) -> int32_t {
#if !USE_V3_NBT_PARSER
make_sure_field_parsed(FIELD_BIOMES);
#endif
if (biomes.size() == nbt::biomes::BIOME_DATA_OLD_VERSION_SIZE) {
return biomes[(z / 2) * 16 + (x / 2)]; // NOLINT
}
if (biomes.size() == nbt::biomes::BIOME_DATA_NEW_VERSION_SIZE) {
return biomes[(y / 64) * 256 + (z / 4) * 4 + (x / 4)]; // NOLINT
}
return 0;
}
auto chunk::get_block(int32_t x, int32_t y, int32_t z) -> std::string {
if (x < 0 || 15 < x || y < 0 || 255 < y || z < 0 || 15 < z) { // NOLINT
return "";
}
#if !USE_V3_NBT_PARSER
make_sure_field_parsed(FIELD_DATA_VERSION);
#endif
unsigned char section_no = y / nbt::biomes::PALETTE_Y_MAX;
y %= nbt::biomes::PALETTE_Y_MAX;
std::vector<std::string> *palette = palettes[section_no];
if (palette == nullptr || palette->empty()) {
return "minecraft:air";
}
unsigned int bits = 4;
if (palette->size() - 1 > 15) { // NOLINT
bits = palette->size() - 1;
/* calculate next squared number, in squared numbers larger than
BITS. if BITS is already squared in this step, calculate next
one. */
bits = bits | (bits >> 1);
bits = bits | (bits >> 2);
bits = bits | (bits >> 4);
bits = bits | (bits >> 8); // NOLINT
bits = bits | (bits >> 16); // NOLINT
bits += 1;
bits = static_cast<int>(log2(bits));
}
int index = y * 16 * 16 + z * 16 + x; // NOLINT
#if !USE_V3_NBT_PARSER
make_sure_field_parsed(FIELD_SECTIONS);
#endif
std::vector<std::uint64_t> *states = block_states[section_no];
int state;
bool stretches =
data_version < nbt::biomes::NEED_STRETCH_DATA_VERSION_THRESHOLD;
if (stretches) {
state = index * bits / 64; // NOLINT
} else {
state = index / (64 / bits); // NOLINT
}
if (static_cast<std::uint64_t>(state) >= states->size()) {
return "minecraft:air";
}
std::uint64_t data = (*states)[state];
std::uint64_t shifted_data;
if (stretches) {
shifted_data = data >> ((bits * index) % 64); // NOLINT
} else {
shifted_data = data >> (index % (64 / bits) * bits); // NOLINT
}
if (stretches && 64 - ((bits * index) % 64) < bits) { // NOLINT
data = (*states)[state + 1];
int leftover = (bits - ((state + 1) * 64 % bits)) % bits; // NOLINT
shifted_data =
((data & (static_cast<std::int64_t>(pow(2, leftover)) - 1))
<< (bits - leftover)) |
shifted_data;
}
std::int64_t palette_id =
shifted_data & (static_cast<std::int64_t>(pow(2, bits)) - 1);
if (palette_id <= 0 ||
(*palette).size() <= static_cast<std::size_t>(palette_id)) {
return "minecraft:air";
}
return (*palette)[palette_id];
}
auto chunk::get_max_height() -> int {
#if !USE_V3_NBT_PARSER
make_sure_field_parsed(FIELD_SECTIONS);
#endif
for (int y = nbt::biomes::SECTIONS_Y_DIV_COUNT - 1; y >= 0; --y) {
if (palettes[y] != nullptr) {
return (y + 1) * nbt::biomes::BLOCK_PER_SECTION - 1;
}
}
return 0;
}
#if USE_BLOCK_LIGHT_DATA
[[nodiscard]] auto chunk::get_block_light(std::int32_t x, std::int32_t y,
std::int32_t z) -> std::uint8_t {
if (y < 0 || 255 < y) {
return 0;
}
auto block_light = block_lights_[y / nbt::biomes::BLOCK_STATES_COUNT];
if (block_light.empty()) {
return 0;
}
return block_light[(y % nbt::biomes::BLOCK_STATES_COUNT) * 16 * 16 +
z * 16 + x];
}
#endif
} // namespace pixel_terrain::anvil
| 35.536458 | 80 | 0.47462 | [
"vector"
] |
6ac332eec69ab1f45a6b2a5f54fc12a35ff165f6 | 7,528 | cpp | C++ | assets/objects/robots/Sumobot.cpp | artfulbytes/sumobot_simulator | f2784d2ff506759019d7d5e840bd7aed591a0add | [
"MIT"
] | null | null | null | assets/objects/robots/Sumobot.cpp | artfulbytes/sumobot_simulator | f2784d2ff506759019d7d5e840bd7aed591a0add | [
"MIT"
] | null | null | null | assets/objects/robots/Sumobot.cpp | artfulbytes/sumobot_simulator | f2784d2ff506759019d7d5e840bd7aed591a0add | [
"MIT"
] | null | null | null | #include "robots/Sumobot.h"
#include <iostream>
namespace {
const std::unordered_map<Sumobot::Blueprint, Sumobot::Specification> sumobotBlueprints
({
{ Sumobot::Blueprint::FourWheel,
{
0.07f, 0.1f, /* Body width, length */
0.42f, /* Body mass */
0.015f, 0.03f, /* Wheel width, diameter */
0.02f, /* Wheel mass */
0.2f, /* Coloumb friction coefficient */
25.0f, /* Wheel sideway friction constant */
0.019f, /* Motor voltage in constant */
0.006f, /* Angular speed constant */
6.0f, /* Motor max voltage */
SimpleBotBody::Shape::Rectangle,
SimpleBotBody::TextureType::SumobotCircuited,
WheelMotor::TextureType::Green,
{
{ Sumobot::WheelMotorIndex::FrontLeft, {-(0.07f + 0.015f) / 2, 0.1f / 5} },
{ Sumobot::WheelMotorIndex::FrontRight, { (0.07f + 0.015f) / 2, 0.1f / 5} },
{ Sumobot::WheelMotorIndex::BackLeft, {-(0.07f + 0.015f) / 2, -0.1f / 4} },
{ Sumobot::WheelMotorIndex::BackRight, { (0.07f + 0.015f) / 2, -0.1f / 4} },
},
{
{ Sumobot::RangeSensorIndex::Left, {-0.035f, 0.00f}, { 4.71f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::FrontLeft, {-0.025f, 0.05f}, { 6.08f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::Front, { 0.000f, 0.05f}, { 0.0f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::FrontRight, { 0.025f, 0.05f}, { 0.20f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::Right, { 0.035f, 0.00f}, { 1.57f, 0.0f, 0.8f }},
},
{
{ Sumobot::LineDetectorIndex::FrontLeft, {-0.035f, 0.05f} },
{ Sumobot::LineDetectorIndex::FrontRight, { 0.035f, 0.05f} },
{ Sumobot::LineDetectorIndex::BackLeft, {-0.035f, -0.05f} },
{ Sumobot::LineDetectorIndex::BackRight, { 0.035f, -0.05f} },
}
}
},
{ Sumobot::Blueprint::TwoWheelRectangle,
{
0.06f, 0.08f, /* Body width, length */
0.4f, /* Body mass */
0.02f, 0.04f, /* Wheel width, diameter */
0.05f, /* Wheel mass */
0.2f, /* Coloumb friction coefficient */
50.0f, /* Wheel sideway friction constant */
0.00628f, /* Motor voltage in constant */
0.00178f, /* Angular speed constant */
6.0f, /* Motor max voltage */
SimpleBotBody::Shape::Rectangle,
SimpleBotBody::TextureType::SumobotPlated,
WheelMotor::TextureType::Orange,
{
{ Sumobot::WheelMotorIndex::Left, {-(0.06f + 0.02f) / 2, -0.1f / 5} },
{ Sumobot::WheelMotorIndex::Right, { (0.06f + 0.02f) / 2, -0.1f / 5} },
},
{
{ Sumobot::RangeSensorIndex::Left, {-0.03f, 0.01f}, { 4.71f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::FrontLeft, {-0.025f, 0.03f}, { 6.08f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::Front, { 0.000f, 0.03f}, { 0.0f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::FrontRight, { 0.025f, 0.03f}, { 0.20f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::Right, { 0.03f, 0.01f}, { 1.57f, 0.0f, 0.8f }},
},
{
{ Sumobot::LineDetectorIndex::FrontLeft, {-0.029f, 0.04f} },
{ Sumobot::LineDetectorIndex::FrontRight, { 0.029f, 0.04f} },
{ Sumobot::LineDetectorIndex::BackLeft, {-0.029f, -0.04f} },
{ Sumobot::LineDetectorIndex::BackRight, { 0.029f, -0.04f} },
}
}
},
{ Sumobot::Blueprint::TwoWheelRoundBlack,
{
0.075f, 0.08f, /* Body width, length */
0.42f, /* Body mass */
0.0125f, 0.0225f, /* Wheel width, diameter */
0.02f, /* Wheel mass */
0.1f, /* Coloumb friction coefficient */
100.0f, /* Wheel sideway friction constant */
0.00500f, /* Motor voltage in constant */
0.00178f, /* Angular speed constant */
6.0f, /* Motor max voltage */
SimpleBotBody::Shape::Circle,
SimpleBotBody::TextureType::SumobotRoundBlack,
WheelMotor::TextureType::Red,
{
{ Sumobot::WheelMotorIndex::Left, {-(0.075f + 0.0125f) / 2, 0.0f} },
{ Sumobot::WheelMotorIndex::Right, { (0.075f + 0.0125f) / 2, 0.0f} },
},
{
{ Sumobot::RangeSensorIndex::FrontLeft, {-0.025f, 0.03f}, { 6.08f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::Front, { 0.000f, 0.04f}, { 0.0f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::FrontRight, { 0.025f, 0.03f}, { 0.20f, 0.0f, 0.8f }},
},
{
{ Sumobot::LineDetectorIndex::FrontLeft, {-0.0275f, 0.0275f} },
{ Sumobot::LineDetectorIndex::FrontRight, { 0.0275f, 0.0275f} },
{ Sumobot::LineDetectorIndex::BackLeft, {-0.0275f, -0.0275f} },
{ Sumobot::LineDetectorIndex::BackRight, { 0.0275f, -0.0275f} },
}
}
},
{ Sumobot::Blueprint::TwoWheelRoundRed,
{
0.075f, 0.08f, /* Body width, length */
0.42f, /* Body mass */
0.0125f, 0.0225f, /* Wheel width, diameter */
0.02f, /* Wheel mass */
0.1f, /* Coloumb friction coefficient */
100.0f, /* Wheel sideway friction constant */
0.00500f, /* Motor voltage in constant */
0.00178f, /* Angular speed constant */
6.0f, /* Motor max voltage */
SimpleBotBody::Shape::Circle,
SimpleBotBody::TextureType::SumobotRoundRed,
WheelMotor::TextureType::Green,
{
{ Sumobot::WheelMotorIndex::Left, {-(0.075f + 0.0125f) / 2, 0.0f} },
{ Sumobot::WheelMotorIndex::Right, { (0.075f + 0.0125f) / 2, 0.0f} },
},
{
{ Sumobot::RangeSensorIndex::FrontLeft, {-0.025f, 0.03f}, { 6.08f, 0.0f, 0.8f }},
{ Sumobot::RangeSensorIndex::FrontRight, { 0.025f, 0.03f}, { 0.20f, 0.0f, 0.8f }},
},
{
{ Sumobot::LineDetectorIndex::FrontLeft, {-0.0275f, 0.0275f} },
{ Sumobot::LineDetectorIndex::FrontRight, { 0.0275f, 0.0275f} },
{ Sumobot::LineDetectorIndex::BackLeft, {-0.0275f, -0.0275f} },
{ Sumobot::LineDetectorIndex::BackRight, { 0.0275f, -0.0275f} },
}
}
},
});
}
const Sumobot::Specification &Sumobot::getBlueprintSpec(Sumobot::Blueprint blueprint)
{
auto blueprintItr = sumobotBlueprints.find(blueprint);
if (blueprintItr == sumobotBlueprints.end()) {
std::cout << "Blueprint not found!" << std::endl;
assert(0);
}
return blueprintItr->second;
}
Sumobot::Sumobot(Scene *scene, const Sumobot::Specification &spec,
const glm::vec2 &startPosition, const float startRotation) :
BaseBot(scene, spec, startPosition, startRotation)
{
}
Sumobot::~Sumobot()
{
}
| 47.345912 | 98 | 0.488177 | [
"shape"
] |
6ac56e48138e2b0323be8018247893172885b484 | 2,934 | hpp | C++ | src/NumericalAlgorithms/Interpolation/AddTemporalIdsToInterpolationTarget.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/NumericalAlgorithms/Interpolation/AddTemporalIdsToInterpolationTarget.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | src/NumericalAlgorithms/Interpolation/AddTemporalIdsToInterpolationTarget.hpp | marissawalker/spectre | afc8205e2f697de5e8e4f05e881499e05c9fd8a0 | [
"MIT"
] | null | null | null | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <algorithm>
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataBox/DataBoxTag.hpp"
#include "DataStructures/Variables.hpp"
#include "Domain/Tags.hpp"
#include "NumericalAlgorithms/Interpolation/Tags.hpp"
#include "Parallel/ConstGlobalCache.hpp"
#include "Parallel/Invoke.hpp"
#include "Utilities/TaggedTuple.hpp"
namespace intrp {
namespace Actions {
/// \ingroup ActionsGroup
/// \brief Adds `temporal_id`s on which this InterpolationTarget
/// should be triggered.
///
/// Uses:
/// - DataBox:
/// - `Tags::TemporalIds<Metavariables>`
///
/// DataBox changes:
/// - Adds: nothing
/// - Removes: nothing
/// - Modifies:
/// - `Tags::TemporalIds<Metavariables>`
template <typename InterpolationTargetTag>
struct AddTemporalIdsToInterpolationTarget {
template <typename DbTags, typename... InboxTags, typename Metavariables,
typename ArrayIndex, typename ActionList,
typename ParallelComponent,
Requires<tmpl::list_contains_v<
DbTags, typename Tags::TemporalIds<Metavariables>>> = nullptr>
static void apply(db::DataBox<DbTags>& box,
const tuples::TaggedTuple<InboxTags...>& /*inboxes*/,
Parallel::ConstGlobalCache<Metavariables>& cache,
const ArrayIndex& /*array_index*/,
const ActionList /*meta*/,
const ParallelComponent* const /*meta*/,
std::vector<typename Metavariables::temporal_id>&&
temporal_ids) noexcept {
const bool begin_interpolation =
db::get<Tags::TemporalIds<Metavariables>>(box).empty();
db::mutate<Tags::TemporalIds<Metavariables>>(
make_not_null(&box), [&temporal_ids](
const gsl::not_null<db::item_type<
Tags::TemporalIds<Metavariables>>*>
ids) noexcept {
ids->insert(ids->end(), std::make_move_iterator(temporal_ids.begin()),
std::make_move_iterator(temporal_ids.end()));
});
// Begin interpolation if it is not already in progress
// (i.e. waiting for data), and if there are temporal_ids to
// interpolate. If there's an interpolation in progress, then a
// later interpolation will be started as soon as the earlier one
// finishes.
const auto& ids = db::get<Tags::TemporalIds<Metavariables>>(box);
if (begin_interpolation and not ids.empty()) {
auto& my_proxy =
Parallel::get_parallel_component<ParallelComponent>(cache);
Parallel::simple_action<
typename InterpolationTargetTag::compute_target_points>(my_proxy,
ids.front());
}
}
};
} // namespace Actions
} // namespace intrp
| 38.103896 | 80 | 0.630539 | [
"vector"
] |
6ac5ba176208bdf6ec8573bbc4946adcf184ebb7 | 4,775 | hpp | C++ | ClassData.hpp | KawakamiYuta/cpp2uml | 8e8a5cda18095cbb1d5c36e340f873c8579f87f0 | [
"MIT"
] | 3 | 2019-04-05T18:40:05.000Z | 2021-03-08T10:51:18.000Z | ClassData.hpp | KawakamiYuta/cpp2uml | 8e8a5cda18095cbb1d5c36e340f873c8579f87f0 | [
"MIT"
] | 1 | 2020-08-26T02:21:25.000Z | 2020-08-26T02:21:25.000Z | ClassData.hpp | KawakamiYuta/cpp2uml | 8e8a5cda18095cbb1d5c36e340f873c8579f87f0 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Yuta Kawakami.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#ifndef CLASSDAT_HPP
#define CLASSDAT_HPP
#include <algorithm>
#include <regex>
#include <map>
#include "DotFile.hpp"
static std::string replaceStr(const std::string& target,const std::string& replace,const std::string& to);
struct FunctionDesc
{
std::string access;
std::string type;
std::string name;
std::vector<std::string> param;
std::string show()
{
std::string mark = (access == "public")? "+":(access == "protected")?"#": "-";
return mark + name + "():" + replaceStr(replaceStr(type,"<","\\<"),">","\\>");
}
};
struct MemberDataDesc
{
std::string access;
std::string type;
std::string name;
bool isClassType;
std::string show()
{
std::string mark = (access == "public")? "+":(access == "protected")?"#": "-";
return mark + name + ":" + replaceStr(replaceStr(type,"<","\\<"),">","\\>");
}
};
struct Record
{
static std::map<std::string,Record*> recordDB;
std::vector<std::string> mBase;
std::string name;
std::vector<MemberDataDesc> data;
std::vector<FunctionDesc> method;
Record(const std::string& prmName):name(prmName){}
static void maybeAddClass(const std::string& prmName)
{
auto itr = recordDB.find(prmName);
if(itr == recordDB.end()) {
recordDB[prmName] = new Record(prmName);
}
}
static bool EquRecord(MemberDataDesc a,MemberDataDesc b)
{
return a.name == b.name;
}
static void printAsDot() {
static DotFile Df("out.dot");
for (auto&& elm: recordDB) {
auto it_data = std::unique(elm.second->data.begin(),elm.second->data.end(),EquRecord);
elm.second->data.resize(std::distance(elm.second->data.begin(),it_data));
auto it_method = std::unique(elm.second->method.begin(), elm.second->method.end(),
[](FunctionDesc& a,FunctionDesc& b) -> bool {
return a.name == b.name;});
elm.second->method.resize(std::distance(elm.second->method.begin(),it_method));
std::stringstream d;
d << elm.second->name << " [ label = \"{" << elm.second->name << "|";
for (auto&& base : elm.second->mBase) {
Df.append("edge [arrowhead = \"empty\"]\n");
Df.append(elm.second->name + " -> " + base + "\n");
}
for (auto&& data : elm.second->data) {
if(data.isClassType) {
Df.append("edge [arrowhead = \"open\"]\n");
Df.append(elm.second->name + " -> " + data.type + "\n");
}
else {
d << data.show() << "\\l";
}
}
d << "|";
for (auto&& method : elm.second->method) {
d << method.show() << "\\l";
}
d << "}\"]" << std::endl;
Df.append(d.str());
}
}
static bool isTargetClassType(const std::string& belong)
{
auto itr = recordDB.find(belong);
return (itr != recordDB.end())? true:false;
}
static void addField(const std::string& belong,const std::string& name,
const std::string& type = "",const std::string& access = "",bool isClassType = false)
{
MemberDataDesc desc = {access,type,name,isClassType};
recordDB[belong]->data.push_back(desc);
}
static void addBase(const std::string& aBelong,const std::string& aBase)
{
::printf("add Base:%s\n",aBase.c_str());
recordDB[aBelong]->mBase.push_back(aBase);
}
static void addMethod(const std::string& belong,const std::string& name,
const std::string& type,const std::string& access) {
FunctionDesc desc = {access,type,name};
recordDB[belong]->method.push_back(desc);
}
};
static std::string replaceStr(const std::string& target,const std::string& replace,const std::string& to)
{
std::string str = target;
std::string::size_type pos = str.find(replace);
while(pos != std::string::npos) {
str.replace(pos,replace.size(),to);
pos = str.find(replace,pos + to.size());
}
return str;
}
#endif
| 31.20915 | 106 | 0.662827 | [
"vector"
] |
6ad3e9d5844abdd357db855a93a5a12c38e9a085 | 2,591 | cpp | C++ | logdevice/server/RealTimeRecordBuffer.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | 1,831 | 2018-09-12T15:41:52.000Z | 2022-01-05T02:38:03.000Z | logdevice/server/RealTimeRecordBuffer.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | 183 | 2018-09-12T16:14:59.000Z | 2021-12-07T15:49:43.000Z | logdevice/server/RealTimeRecordBuffer.cpp | mickvav/LogDevice | 24a8b6abe4576418eceb72974083aa22d7844705 | [
"BSD-3-Clause"
] | 228 | 2018-09-12T15:41:51.000Z | 2022-01-05T08:12:09.000Z | /**
* Copyright (c) 2018-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/server/RealTimeRecordBuffer.h"
#include <folly/Format.h>
#include "logdevice/common/ZeroCopiedRecord.h"
#include "logdevice/common/debug.h"
#include "logdevice/common/stats/Stats.h"
namespace facebook { namespace logdevice {
ReleasedRecords::~ReleasedRecords() {
if (buffer_) {
buffer_->deletedReleasedRecords(this);
}
}
size_t ReleasedRecords::computeBytesEstimate(const ZeroCopiedRecord* entries) {
// Assuming the control block consists of a reference count and pointer to
// deleter.
size_t size = sizeof(ReleasedRecords) + sizeof(size_t) + sizeof(void*);
for (; entries != nullptr; entries = entries->next_.get()) {
size += entries->getBytesEstimate();
}
return size;
}
std::string ReleasedRecords::toString() const {
return folly::sformat("{} [{}-{}], bytes {}",
facebook::logdevice::toString(logid_),
lsn_to_string(begin_lsn_),
lsn_to_string(end_lsn_),
bytes_estimate_);
}
bool RealTimeRecordBuffer::appendReleasedRecords(
std::unique_ptr<ReleasedRecords> records) {
// NOTE: called on the thread that's doing the release, NOT on the Worker
// where this object "lives".
ld_check(records);
ld_assert(!shutdown_.load());
// We need to INSERT before we ADD TO released_records_bytes_. That's
// because, when we check for eviction, we first look at r_r_bytes_, and if
// that's too big, we need to be able to find the records to evict.
// If this would put us over the max, don't add.
const auto size_of_these_records = records->getBytesEstimate();
if (released_records_bytes_.load() + size_of_these_records > max_bytes_) {
// We destroy the ReleasedRecords here.
return true;
}
released_records_.insertHead(records.release());
auto new_size = released_records_bytes_.fetch_add(size_of_these_records);
return new_size > eviction_threshold_bytes_;
}
size_t RealTimeRecordBuffer::shutdown() {
shutdown_.store(true);
size_t count = 0;
sweep([&count](std::unique_ptr<ReleasedRecords> /* recs */) {
++count;
// The ReleasedRecords will be deleted when recs goes out of scope.
});
return count;
}
RealTimeRecordBuffer::~RealTimeRecordBuffer() {
ld_check(shutdown_.load());
ld_check(logids_.empty());
}
}} // namespace facebook::logdevice
| 30.845238 | 79 | 0.701274 | [
"object"
] |
6ad8bc2e2cb4bd11bdcf804e4c13d85e033083c5 | 1,456 | hh | C++ | src/pks/shallow_water/ShallowWaterBoundaryFunction.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/pks/shallow_water/ShallowWaterBoundaryFunction.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/pks/shallow_water/ShallowWaterBoundaryFunction.hh | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /*
Shallow water PK
Copyright 2010-201x held jointly by LANS/LANL, LBNL, and PNNL.
Amanzi is released under the three-clause BSD License.
The terms of use and "as is" disclaimer for this license are
provided in the top-level COPYRIGHT file.
Author: Svetlana Tokareva (tokareva@lanl.gov)
*/
#ifndef AMANZI_SHALLOW_WATER_BOUNDARY_FUNCTION_HH_
#define AMANZI_SHALLOW_WATER_BOUNDARY_FUNCTION_HH_
#include <string>
#include <vector>
#include "Epetra_Vector.h"
#include "Teuchos_ParameterList.hpp"
#include "Teuchos_RCP.hpp"
#include "Mesh.hh"
#include "WhetStoneDefs.hh"
#include "PK_DomainFunction.hh"
namespace Amanzi {
namespace ShallowWater {
class ShallowWaterBoundaryFunction : public PK_DomainFunction {
public:
ShallowWaterBoundaryFunction() : bc_name_("undefined") {};
ShallowWaterBoundaryFunction(const Teuchos::ParameterList& plist);
// modifiers and access
void set_bc_name(const std::string& name) { bc_name_ = name; }
std::string get_bc_name() { return bc_name_; }
void set_type(WhetStone::DOF_Type type) { type_ = type; }
WhetStone::DOF_Type type() { return type_; }
std::vector<double> bc_value(int f) { return value_[f]; }
bool bc_find(int f) { return value_.find(f) != value_.end(); }
private:
std::string bc_name_;
WhetStone::DOF_Type type_; // type of dofs related to this bc
std::vector<std::string> regions_;
};
} // namespace ShallowWater
} // namespace Amanzi
#endif
| 25.54386 | 68 | 0.736951 | [
"mesh",
"vector"
] |
6ae506ebb5a039dacba89950a8640f56b90f23d7 | 2,361 | cpp | C++ | tools/Vitis-AI-Runtime/VART/vart/util/test/test_thread_pool.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | 1 | 2022-02-17T22:13:23.000Z | 2022-02-17T22:13:23.000Z | tools/Vitis-AI-Runtime/VART/vart/util/test/test_thread_pool.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | tools/Vitis-AI-Runtime/VART/vart/util/test/test_thread_pool.cpp | hito0512/Vitis-AI | 996459fb96cb077ed2f7e789d515893b1cccbc95 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 xilinx 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 <glog/logging.h>
#include <cstring>
#include <iostream>
#include "vitis/ai/env_config.hpp"
#include "vitis/ai/thread_pool.hpp"
DEF_ENV_PARAM(NUM_OF_THREADS, "1")
DEF_ENV_PARAM(NUM_OF_REQUESTS, "625000")
using namespace std;
int foo(int a, int b) {
if (0)
LOG_IF(INFO, true) << "a " << a << " " //
<< "b " << b << " " //
;
std::this_thread::sleep_for(std::chrono::milliseconds(2));
return a + b;
}
int main1(int argc, char* argv[]) {
auto p = vitis::ai::ThreadPool::create(ENV_PARAM(NUM_OF_THREADS));
int a = 1;
int b = 1;
auto all = vector<std::future<int>>();
for (auto i = 0; i < ENV_PARAM(NUM_OF_REQUESTS); ++i) {
p->async(foo, a + i, b);
// all.emplace_back();
}
for (auto& f : all) {
LOG_IF(INFO, true) << "hello " << f.get() << endl;
}
return foo(a, b);
}
void foo2(std::promise<int>* p, int a, int b) {
LOG_IF(INFO, true) << "a " << a << " " //
<< "b " << b << " ";
p->set_value(a + b);
delete p;
}
int main2(int argc, char* argv[]) {
auto p = vitis::ai::ThreadPool::create(ENV_PARAM(NUM_OF_THREADS));
auto all = vector<std::future<int>>();
int a = 1;
int b = 1;
for (int i = 0; i < 10; ++i) {
std::promise<int> promise;
all.emplace_back(promise.get_future());
p->async(foo2, new std::promise<int>(std::move(promise)), a + i, b);
}
for (auto& f : all) {
LOG_IF(INFO, true) << "hello " << f.get() << endl;
}
return foo(a, b);
}
int main(int argc, char* argv[]) {
if (argc < 2) {
cout << "usage " << argv[0] << " <test-case>: main1 main2";
return 0;
}
if (strcmp(argv[1], "main1") == 0) {
main1(argc, argv);
} else if (strcmp(argv[1], "main2") == 0) {
main2(argc, argv);
}
return 0;
}
| 28.445783 | 75 | 0.59424 | [
"vector"
] |
6ae5bff43cffd0e60bfa2b85d75ca723b89bdd6a | 5,811 | cpp | C++ | qt-creator-4.14/src/libs/utils/settingsselector.cpp | peng1ei/qtcreator-plugin | ca4f9c6c7ddd899bcdbac7a6a4c5e383495e7a65 | [
"MIT"
] | 1 | 2021-12-28T23:27:04.000Z | 2021-12-28T23:27:04.000Z | qt-creator-4.14/src/libs/utils/settingsselector.cpp | peng1ei/qtcreator-plugin | ca4f9c6c7ddd899bcdbac7a6a4c5e383495e7a65 | [
"MIT"
] | null | null | null | qt-creator-4.14/src/libs/utils/settingsselector.cpp | peng1ei/qtcreator-plugin | ca4f9c6c7ddd899bcdbac7a6a4c5e383495e7a65 | [
"MIT"
] | 1 | 2021-12-29T11:25:37.000Z | 2021-12-29T11:25:37.000Z | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "settingsselector.h"
#include <QComboBox>
#include <QHBoxLayout>
#include <QInputDialog>
#include <QLabel>
#include <QMessageBox>
#include <QPushButton>
namespace Utils {
// --------------------------------------------------------------------------
// SettingsSelector
// --------------------------------------------------------------------------
SettingsSelector::SettingsSelector(QWidget *parent) :
QWidget(parent)
{
auto layout = new QHBoxLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSpacing(6);
m_configurationCombo = new QComboBox(this);
m_configurationCombo->setSizeAdjustPolicy(QComboBox::AdjustToContents);
m_configurationCombo->setMinimumContentsLength(80);
m_addButton = new QPushButton(tr("Add"), this);
m_removeButton = new QPushButton(tr("Remove"), this);
m_renameButton = new QPushButton(tr("Rename"), this);
m_label = new QLabel(this);
m_label->setMinimumWidth(200);
m_label->setBuddy(m_configurationCombo);
layout->addWidget(m_label);
layout->addWidget(m_configurationCombo);
layout->addWidget(m_addButton);
layout->addWidget(m_removeButton);
layout->addWidget(m_renameButton);
layout->addSpacerItem(new QSpacerItem(0, 0));
updateButtonState();
connect(m_addButton, &QAbstractButton::clicked, this, &SettingsSelector::add);
connect(m_removeButton, &QAbstractButton::clicked,
this, &SettingsSelector::removeButtonClicked);
connect(m_renameButton, &QAbstractButton::clicked,
this, &SettingsSelector::renameButtonClicked);
connect(m_configurationCombo,
QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &SettingsSelector::currentChanged);
}
SettingsSelector::~SettingsSelector() = default;
void SettingsSelector::setConfigurationModel(QAbstractItemModel *model)
{
if (m_configurationCombo->model()) {
disconnect(m_configurationCombo->model(), &QAbstractItemModel::rowsInserted,
this, &SettingsSelector::updateButtonState);
disconnect(m_configurationCombo->model(), &QAbstractItemModel::rowsRemoved,
this, &SettingsSelector::updateButtonState);
}
m_configurationCombo->setModel(model);
connect(model, &QAbstractItemModel::rowsInserted, this, &SettingsSelector::updateButtonState);
connect(model, &QAbstractItemModel::rowsRemoved, this, &SettingsSelector::updateButtonState);
updateButtonState();
}
QAbstractItemModel *SettingsSelector::configurationModel() const
{
return m_configurationCombo->model();
}
void SettingsSelector::setLabelText(const QString &text)
{
m_label->setText(text);
}
QString SettingsSelector::labelText() const
{
return m_label->text();
}
void SettingsSelector::setCurrentIndex(int index)
{
m_configurationCombo->setCurrentIndex(index);
}
void SettingsSelector::setAddMenu(QMenu *menu)
{
m_addButton->setMenu(menu);
}
QMenu *SettingsSelector::addMenu() const
{
return m_addButton->menu();
}
int SettingsSelector::currentIndex() const
{
return m_configurationCombo->currentIndex();
}
void SettingsSelector::removeButtonClicked()
{
int pos = currentIndex();
if (pos < 0)
return;
const QString title = tr("Remove");
const QString message = tr("Do you really want to delete the configuration <b>%1</b>?")
.arg(m_configurationCombo->currentText());
QMessageBox msgBox(QMessageBox::Question, title, message, QMessageBox::Yes|QMessageBox::No, this);
msgBox.setDefaultButton(QMessageBox::No);
msgBox.setEscapeButton(QMessageBox::No);
if (msgBox.exec() == QMessageBox::No)
return;
emit remove(pos);
}
void SettingsSelector::renameButtonClicked()
{
int pos = currentIndex();
if (pos < 0)
return;
QAbstractItemModel *model = m_configurationCombo->model();
int row = m_configurationCombo->currentIndex();
QModelIndex idx = model->index(row, 0);
QString baseName = model->data(idx, Qt::EditRole).toString();
bool ok;
const QString message = tr("New name for configuration <b>%1</b>:").arg(baseName);
QString name = QInputDialog::getText(this, tr("Rename..."), message,
QLineEdit::Normal, baseName, &ok);
if (!ok)
return;
emit rename(pos, name);
}
void SettingsSelector::updateButtonState()
{
bool haveItems = m_configurationCombo->count() > 0;
m_addButton->setEnabled(true);
m_removeButton->setEnabled(haveItems);
m_renameButton->setEnabled(haveItems);
}
} // namespace Utils
| 32.283333 | 102 | 0.673894 | [
"model"
] |
6aecfb9a8e6198e121bddc2272fba0193e5de901 | 5,314 | hpp | C++ | src/applicationui.hpp | spinclick/ViBrowserBB10 | 32a86d442d9482baed052ce900e5cdd6aa51cafa | [
"Unlicense"
] | 1 | 2020-03-15T08:20:40.000Z | 2020-03-15T08:20:40.000Z | src/applicationui.hpp | spinclick/ViBrowserBB10 | 32a86d442d9482baed052ce900e5cdd6aa51cafa | [
"Unlicense"
] | 1 | 2021-08-03T12:11:57.000Z | 2021-08-03T12:11:57.000Z | src/applicationui.hpp | BerryTrucks/ViBrowserBB10 | 8d7270d05475109bf82e00e07f6cb8a466fe9be4 | [
"Unlicense"
] | 2 | 2019-02-15T19:39:57.000Z | 2021-08-03T12:05:02.000Z | /*
* Copyright (c) 2011-2015 BlackBerry Limited.
*
* 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 ApplicationUI_HPP_
#define ApplicationUI_HPP_
#include <QObject>
#include <QUrl>
#include <QList>
#include <QHash>
#include <QVariantMap>
#include <bb/cascades/KeyEvent>
#include <bb/cascades/KeyListener>
#include <bb/cascades/controls/webview.h>
#include <bb/cascades/controls/scrollview.h>
#include <bb/cascades/controls/page.h>
#include <bb/cascades/controls/textfield.h>
#include <bb/cascades/Label>
#include <bb/cascades/WebFindFlag>
#include <bb/cascades/AbstractTextControl>
#include <bb/cascades/WebLoadStatus>
#include <bb/cascades/WebLoadRequest>
#include <bb/cascades/WebFindFlag>
#include <bb/system/Clipboard.hpp>
#include <bb/system/SystemToast.hpp>
#include <bb/data/SqlDataAccess>
namespace bb
{
namespace cascades
{
class LocaleHandler;
}
}
//Forward Declarations
class QTranslator;
class ViBrowserTab;
using namespace bb::cascades;
/*!
* @brief Application UI object
*
* Use this object to create and init app UI, to create context objects, to register the new meta types etc.
*/
struct URLRecord {
QString url;
QString title;
QString domain;
};
class ApplicationUI : public QObject
{
Q_OBJECT
public:
ApplicationUI();
virtual ~ApplicationUI() {};
ViBrowserTab *currentTab;
Page *root;
QList<char> keyStack;
QList<ViBrowserTab*> tabStack;
QList<URLRecord> history;
QList<URLRecord> bookmarks;
bb::data::SqlDataAccess *db;
QHash<QString, void(*)(ApplicationUI*)> keyBindings;
bool ignorekeys;
QString hintFilter;
QString hintJS;
QString searchString;
QStringList hintLines;
int tabIndex;
QList<QString> sortedKeyBinds;
//Config
struct Config {
float PixelRatioModifier;
bool JavascriptEnabled;
bool ImagesEnabled;
bool CookiesEnabled;
bool DesktopMode;
QString SearchEngineString;
QString HomePage;
} config;
bb::system::SystemToast *toaster;
bb::system::Clipboard *clipboard;
void scrollRight(float percent, ScrollView *scrollview);
void scrollDown(float percent, ScrollView *scrollview);
void tabDel(int move);
void switchTab(Page *page, int offset);
void tabNew(QString urlBarContent, Page *page);
void copyURL(QUrl currentURL, bb::system::Clipboard *clipboard);
void zoomIn(float percent, ScrollView *scrollview);
void zoomReset(ScrollView *scrollview);
void goClipURL(WebView *webview, bb::system::Clipboard *clip);
void goPageForward(WebView *webview);
void goPageBack(WebView *webview);
void goPathUp(WebView *webview);
void pageRefresh(WebView *webview);
void searchText(QString searchString, WebView *webview, WebFindFlag::Types flags);
void checkHints(QStringList hintLines, QList<char> keyStack, WebView *webview);
void updateTabSelection(Label *tabselectcounter, int tabindex, int numtabs);
void exitApp();
void viewSource(WebView *webview);
void openBar(TextField* somebar, QString content);
//hints
void startHintMode(WebView *webview);
void stopHintMode(WebView *webview);
//misc
void initKeyBindings();
void initSortedKeyBinds();
void initHintJS();
void initConfig();
void initSQLDB();
void updateTabCounter();
void disconnectInputBar();
TextField* getVisibleBar();
void setCommandConfig(QString option);
void printSettingsToHtml();
void printUrlRecordToHtml(QList<URLRecord>);
void configParser();
void configWriter();
void updateConfig();
void remapKey(QString ls, QString rs);
void clearHistory();
void showSqlAsPage(QVariant qvblob, QString title);
void addHistory();
void addBookmark();
private slots:
void SL_onKeyPressedHandler(bb::cascades::KeyEvent* keyevent);
void SL_onKeyLongPressedHandler(bb::cascades::KeyEvent* keyevent);
//for bars
void SL_selectHint(bb::cascades::AbstractTextControl* control);
void SL_goURL(bb::cascades::AbstractTextControl* control);
void SL_runCommand(bb::cascades::AbstractTextControl* control);
void SL_searchPageText(bb::cascades::AbstractTextControl* control);
void SL_searchEngineQuery(bb::cascades::AbstractTextControl* control);
void SL_onBarKeyPressed(bb::cascades::KeyEvent* keyevent);
//void SL_toggleInputBar(bool focused);
void SL_updateUrl(QUrl newUrl);
void SL_receiveHintsFromJS(QVariantMap message);
void SL_menuAbout();
void SL_menuHelp();
void SL_pageLoad(bb::cascades::WebLoadRequest* request);
void SL_updateHintFilter(QString newFilter);
void SL_stopHintMode(bool on);
};
//void sortBindsByLength(QList<QString> *keys);
#endif /* ApplicationUI_HPP_ */
| 28.265957 | 108 | 0.722808 | [
"object"
] |
6af42c52476f5adbbda371816108b2ea7893586b | 1,028 | cpp | C++ | vox.geometry/point_generators/grid_point_generator2.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 28 | 2021-11-23T11:52:55.000Z | 2022-03-04T01:48:52.000Z | vox.geometry/point_generators/grid_point_generator2.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | null | null | null | vox.geometry/point_generators/grid_point_generator2.cpp | yangfengzzz/DigitalVox3 | c3277007d7cae90cf3f55930bf86119c93662493 | [
"MIT"
] | 3 | 2022-01-02T12:23:04.000Z | 2022-01-07T04:21:26.000Z | // Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include "grid_point_generator2.h"
#include "../common.h"
namespace vox {
namespace geometry {
void GridPointGenerator2::forEachPoint(const BoundingBox2D &boundingBox, double spacing,
const std::function<bool(const Vector2D &)> &callback) const {
Vector2D position;
double boxWidth = boundingBox.width();
double boxHeight = boundingBox.height();
bool shouldQuit = false;
for (int j = 0; j * spacing <= boxHeight && !shouldQuit; ++j) {
position.y = j * spacing + boundingBox.lowerCorner.y;
for (int i = 0; i * spacing <= boxWidth && !shouldQuit; ++i) {
position.x = i * spacing + boundingBox.lowerCorner.x;
if (!callback(position)) {
shouldQuit = true;
break;
}
}
}
}
} // namespace vox
} // namespace geometry
| 29.371429 | 101 | 0.654669 | [
"geometry"
] |
6af6198ed350d516df37751ee2a0e0ee87412333 | 764 | cpp | C++ | leetcode/1429. First Unique Number/s1.cpp | joycse06/LeetCode-1 | ad105bd8c5de4a659c2bbe6b19f400b926c82d93 | [
"Fair"
] | 1 | 2021-02-11T01:23:10.000Z | 2021-02-11T01:23:10.000Z | leetcode/1429. First Unique Number/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 1 | 2021-08-08T18:44:24.000Z | 2021-08-08T18:44:24.000Z | leetcode/1429. First Unique Number/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 1 | 2021-03-25T17:11:14.000Z | 2021-03-25T17:11:14.000Z | // OJ: https://leetcode.com/problems/first-unique-number/
// Author: github.com/lzl124631x
// Time:
// FirstUnique: O(N)
// showFirstUnique: O(1)
// add: O(1)
// Space: O(N)
class FirstUnique {
list<int> data;
typedef list<int>::iterator iter;
unordered_map<int, iter> m;
unordered_set<int> s;
public:
FirstUnique(vector<int>& nums) {
for (int n : nums) add(n);
}
int showFirstUnique() {
return data.size() ? data.front() : -1;
}
void add(int value) {
if (s.count(value)) return;
if (m.count(value)) {
data.erase(m[value]);
s.insert(value);
} else {
data.push_back(value);
m[value] = prev(data.end());
}
}
};
| 23.151515 | 57 | 0.530105 | [
"vector"
] |
6afe038efceafd0d5650ebf462de866554fa0353 | 15,470 | cc | C++ | addons/geometry/tests/numericalTestFunctions.cc | Dangzilla/rbdl-casadi | 3f4e8c4eae8a1053a1c123980746022e46770811 | [
"Zlib"
] | 258 | 2019-09-17T02:24:30.000Z | 2022-03-29T07:38:47.000Z | addons/geometry/tests/numericalTestFunctions.cc | Dangzilla/rbdl-casadi | 3f4e8c4eae8a1053a1c123980746022e46770811 | [
"Zlib"
] | 43 | 2019-11-11T14:04:39.000Z | 2022-03-25T09:22:40.000Z | addons/geometry/tests/numericalTestFunctions.cc | Dangzilla/rbdl-casadi | 3f4e8c4eae8a1053a1c123980746022e46770811 | [
"Zlib"
] | 101 | 2019-09-30T00:44:53.000Z | 2022-03-26T11:19:36.000Z | /* -------------------------------------------------------------------------- *
* OpenSim: testSmoothSegmentedFunctionFactory.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matthew Millard *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
Update:
This is a port of the original code so that it will work with
the multibody code RBDL written by Martin Felis.
This also includes additional curves (the Anderson2007 curves)
which are not presently in OpenSim.
Author:
Matthew Millard
Date:
Nov 2015
*/
/*
Below is a basic bench mark simulation for the SmoothSegmentedFunctionFactory
class, a class that enables the easy generation of C2 continuous curves
that define the various characteristic curves required in a muscle model
*/
// Author: Matthew Millard
//==============================================================================
// INCLUDES
//==============================================================================
#include "numericalTestFunctions.h"
#include <UnitTest++.h>
#include <rbdl/rbdl_math.h>
#include <ctime>
#include <string>
#include <stdio.h>
#include <exception>
#include <cassert>
#include <fstream>
using namespace RigidBodyDynamics::Addons::Geometry;
using namespace std;
void printMatrixToFile(
const RigidBodyDynamics::Math::VectorNd& col0,
const RigidBodyDynamics::Math::MatrixNd& data,
string& filename)
{
ofstream datafile;
datafile.open(filename.c_str());
for(int i = 0; i < data.rows(); i++){
datafile << col0[i] << ",";
for(int j = 0; j < data.cols(); j++){
if(j<data.cols()-1)
datafile << data(i,j) << ",";
else
datafile << data(i,j) << "\n";
}
}
datafile.close();
}
void printMatrixToFile(
const RigidBodyDynamics::Math::MatrixNd& data,
string& filename)
{
ofstream datafile;
datafile.open(filename.c_str());
for(int i = 0; i < data.rows(); i++){
for(int j = 0; j < data.cols(); j++){
if(j<data.cols()-1)
datafile << data(i,j) << ",";
else
datafile << data(i,j) << "\n";
}
}
datafile.close();
}
RigidBodyDynamics::Math::VectorNd
calcCentralDifference( RigidBodyDynamics::Math::VectorNd& x,
RigidBodyDynamics::Math::VectorNd& y,
bool extrap_endpoints){
RigidBodyDynamics::Math::VectorNd dy(x.size());
double dx1,dx2;
double dy1,dy2;
int size = x.size();
for(int i=1; i<size-1; i++){
dx1 = x[i] - x[i-1];
dx2 = x[i+1] - x[i];
dy1 = y[i] - y[i-1];
dy2 = y[i+1] - y[i];
dy[i]= 0.5*dy1/dx1 + 0.5*dy2/dx2;
}
if(extrap_endpoints == true){
dy1 = dy[2] - dy[1];
dx1 = x[2] - x[1];
dy[0] = dy[1] + (dy1/dx1)*(x[0]-x[1]);
dy2 = dy[size-2] - dy[size-3];
dx2 = x[size-2] - x[size-3];
dy[size-1] = dy[size-2] + (dy2/dx2)*(x[size-1]-x[size-2]);
}
return dy;
}
RigidBodyDynamics::Math::VectorNd
calcCentralDifference( RigidBodyDynamics::Math::VectorNd& x,
SmoothSegmentedFunction& mcf,
double tol, int order){
RigidBodyDynamics::Math::VectorNd dyV(x.size());
RigidBodyDynamics::Math::VectorNd yV(x.size());
double y = 0;
double dy = 0;
double dyNUM = 0;
double err= 0;
double h = 0;
double xL = 0;
double xR = 0;
double c3 = 0;
double fL = 0;
double fR = 0;
double rootEPS = sqrt(EPSILON);
double y_C3min = 1e-10;
double y_C3max = 1e1;
for(int i=0; i<x.size(); i++){
yV[i] = mcf.calcDerivative(x[i],order-1);
}
for(int i=0; i< x.size(); i++){
c3 = abs(mcf.calcDerivative(x[i],order+2));
//singularity prevention
if(abs(c3) < y_C3min)
c3 = y_C3min;
//Compute h
y = abs(mcf.calcDerivative(x[i], order-1));
//preventing 0 from being assigned to y
if(y < y_C3min)
y = y_C3min;
//Dumb check
if(y/c3 < y_C3min){
c3 = 1;
y = y_C3min;
}
if(y/c3 > y_C3max){
c3 = 1;
y = y_C3max;
}
h = pow( ( (EPSILON*y*2.0)/(c3) ) , 1.0/3.0);
//Now check that h to the left and right are at least similar
//If not, take the smallest one.
xL = x[i]-h/2;
xR = x[i]+h/2;
fL = mcf.calcDerivative(xL, order-1);
fR = mcf.calcDerivative(xR, order-1);
//Just for convenience checking ...
dyNUM = (fR-fL)/h;
dy = mcf.calcDerivative(x[i],order);
err = abs(dy-dyNUM);
/*if(err > tol && abs(dy) > rootEPS && order <= 2){
err = err/abs(dy);
if(err > tol)
cout << "rel tol exceeded" << endl;
}*/
dyV[i] = dyNUM;
}
return dyV;
}
bool isFunctionContinuous( RigidBodyDynamics::Math::VectorNd& xV,
SmoothSegmentedFunction& yV,
int order,
double minValueSecondDerivative,
double taylorErrorMult)
{
bool flag_continuous = true;
double xL = 0; // left shoulder point
double xR = 0; // right shoulder point
double yL = 0; // left shoulder point function value
double yR = 0; // right shoulder point function value
double dydxL = 0; // left shoulder point derivative value
double dydxR = 0; // right shoulder point derivative value
double xVal = 0; //x value to test
double yVal = 0; //Y(x) value to test
double yValEL = 0; //Extrapolation to yVal from the left
double yValER = 0; //Extrapolation to yVal from the right
double errL = 0;
double errR = 0;
double errLMX = 0;
double errRMX = 0;
for(int i =1; i < xV.size()-1; i++){
xVal = xV[i];
yVal = yV.calcDerivative(xVal, order);
xL = 0.5*(xV[i]+xV[i-1]);
xR = 0.5*(xV[i]+xV[i+1]);
yL = yV.calcDerivative(xL,order);
yR = yV.calcDerivative(xR,order);
dydxL = yV.calcDerivative(xL,order+1);
dydxR = yV.calcDerivative(xR,order+1);
yValEL = yL + dydxL*(xVal-xL);
yValER = yR - dydxR*(xR-xVal);
errL = abs(yValEL-yVal);
errR = abs(yValER-yVal);
errLMX = abs(yV.calcDerivative(xL,order+2)*0.5*(xVal-xL)*(xVal-xL));
errRMX = abs(yV.calcDerivative(xR,order+2)*0.5*(xR-xVal)*(xR-xVal));
errLMX*=taylorErrorMult;
errRMX*=taylorErrorMult;
if(errLMX < minValueSecondDerivative)
errLMX = minValueSecondDerivative;
if(errRMX < minValueSecondDerivative)
errRMX = minValueSecondDerivative; // to accomodate numerical
//error in errL
if(errL > errLMX || errR > errRMX){
flag_continuous = false;
}
}
return flag_continuous;
}
bool isVectorMonotonic( RigidBodyDynamics::Math::VectorNd& y,
int multEPS)
{
double dir = y[y.size()-1]-y[0];
bool isMonotonic = true;
if(dir < 0){
for(int i =1; i <y.size(); i++){
if(y[i] > y[i-1]+EPSILON*multEPS){
isMonotonic = false;
//printf("Monotonicity broken at idx %i, since %fe-16 > %fe-16\n",
// i,y(i)*1e16,y(i-1)*1e16);
printf("Monotonicity broken at idx %i, since "
"y(i)-y(i-1) < tol, (%f*EPSILON < EPSILON*%i) \n",
i,((y[i]-y[i-1])/EPSILON), multEPS);
}
}
}
if(dir > 0){
for(int i =1; i <y.size(); i++){
if(y[i] < y[i-1]-EPSILON*multEPS){
isMonotonic = false;
printf("Monotonicity broken at idx %i, since "
"y(i)-y(i-1) < -tol, (%f*EPSILON < -EPSILON*%i) \n",
i,((y[i]-y[i-1])/EPSILON), multEPS);
}
}
}
if(dir == 0){
isMonotonic = false;
}
return isMonotonic;
}
RigidBodyDynamics::Math::VectorNd calcTrapzIntegral(
RigidBodyDynamics::Math::VectorNd& x,
RigidBodyDynamics::Math::VectorNd& y,
bool flag_TrueIntForward_FalseIntBackward)
{
RigidBodyDynamics::Math::VectorNd inty
= RigidBodyDynamics::Math::VectorNd::Zero(y.size());
//inty = 0;
int startIdx = 1;
int endIdx = y.size()-1;
if(flag_TrueIntForward_FalseIntBackward == true){
double width = 0;
for(int i = 1; i <= endIdx; i=i+1){
width = abs(x[i]-x[i-1]);
inty[i] = inty[i-1] + width*(0.5)*(y[i]+y[i-1]);
}
}else{
double width = 0;
for(int i = endIdx-1; i >= 0; i=i-1){
width = abs(x[i]-x[i+1]);
inty[i] = inty[i+1] + width*(0.5)*(y[i]+y[i+1]);
}
}
return inty;
}
double calcMaximumVectorError(RigidBodyDynamics::Math::VectorNd& a,
RigidBodyDynamics::Math::VectorNd& b)
{
double error = 0;
double cerror=0;
for(int i = 0; i< a.size(); i++)
{
cerror = abs(a[i]-b[i]);
if(cerror > error){
error = cerror;
}
}
return error;
}
bool isCurveC2Continuous(SmoothSegmentedFunction& mcf,
RigidBodyDynamics::Math::MatrixNd& mcfSample,
double continuityTol)
{
//cout << " TEST: C2 Continuity " << endl;
int multC0 = 5;
int multC1 = 50;
int multC2 = 200;
RigidBodyDynamics::Math::VectorNd fcnSample =
RigidBodyDynamics::Math::VectorNd::Zero(mcfSample.rows());
for(int i=0; i < mcfSample.rows(); i++){
fcnSample[i] = mcfSample(i,0);
}
bool c0 = isFunctionContinuous(fcnSample, mcf, 0, continuityTol, multC0);
bool c1 = isFunctionContinuous(fcnSample, mcf, 1, continuityTol, multC1);
bool c2 = isFunctionContinuous(fcnSample, mcf, 2, continuityTol, multC2);
return (c0 && c1 && c2);
//printf( " passed: C2 continuity established to a multiple\n"
// " of the next Taylor series error term.\n "
// " C0,C1, and C2 multiples: %i,%i and %i\n",
// multC0,multC1,multC2);
//cout << endl;
}
bool isCurveMontonic(RigidBodyDynamics::Math::MatrixNd mcfSample)
{
//cout << " TEST: Monotonicity " << endl;
int multEps = 10;
RigidBodyDynamics::Math::VectorNd fcnSample =
RigidBodyDynamics::Math::VectorNd::Zero(mcfSample.rows());
for(int i=0; i < mcfSample.rows(); i++){
fcnSample[i] = mcfSample(i,1);
}
bool monotonic = isVectorMonotonic(fcnSample,10);
return monotonic;
//printf(" passed: curve is monotonic to %i*EPSILON",multEps);
//cout << endl;
}
bool areCurveDerivativesCloseToNumericDerivatives(
SmoothSegmentedFunction& mcf,
RigidBodyDynamics::Math::MatrixNd& mcfSample,
double tol)
{
//cout << " TEST: Derivative correctness " << endl;
int maxDer = 4;//mcf.getMaxDerivativeOrder() - 2;
RigidBodyDynamics::Math::MatrixNd numSample(mcfSample.rows(),maxDer);
RigidBodyDynamics::Math::MatrixNd relError(mcfSample.rows(),maxDer);
RigidBodyDynamics::Math::VectorNd domainX =
RigidBodyDynamics::Math::VectorNd::Zero(mcfSample.rows());
for(int j=0; j<mcfSample.rows(); j++)
domainX[j] = mcfSample(j,0);
for(int i=0; i < maxDer; i++){
//Compute the relative error
numSample.col(i)=calcCentralDifference(domainX,mcf,tol,i+1);
for(int j=0; j<mcfSample.rows();++j ){
relError(j,i)= mcfSample(j,i+2)-numSample(j,i);
}
//compute a relative error where possible
for(int j=0; j < relError.rows(); j++){
if(abs(mcfSample(j,i+2)) > tol){
relError(j,i) = relError(j,i)/mcfSample(j,i+2);
}
}
}
RigidBodyDynamics::Math::VectorNd errRelMax =
RigidBodyDynamics::Math::VectorNd::Zero(6);
RigidBodyDynamics::Math::VectorNd errAbsMax =
RigidBodyDynamics::Math::VectorNd::Zero(6);
double absTol = 5*tol;
bool flagError12=false;
RigidBodyDynamics::Math::VectorNd tolExceeded12V =
RigidBodyDynamics::Math::VectorNd::Zero(mcfSample.rows());
int tolExceeded12 = 0;
int tolExceeded34 = 0;
for(int j=0;j<maxDer;j++){
for(int i=0; i<mcfSample.rows(); i++){
if(relError(i,j) > tol && mcfSample(i,j+2) > tol){
if(j <= 1){
tolExceeded12++;
tolExceeded12V[i]=1;
flagError12=true;
}
if(j>=2)
tolExceeded34++;
}
if(mcfSample(i,j+2) > tol)
if(errRelMax[j] < abs(relError(i,j)))
errRelMax[j] = abs(relError(i,j));
//This is a harder test: here we're comparing absolute error
//so the tolerance margin is a little higher
if(relError(i,j) > absTol && mcfSample(i,j+2) <= tol){
if(j <= 1){
tolExceeded12++;
tolExceeded12V[i]=1;
flagError12=true;
}
if(j>=2)
tolExceeded34++;
}
if(mcfSample(i,j+2) < tol)
if(errAbsMax[j] < abs(relError(i,j)))
errAbsMax[j] = abs(relError(i,j));
}
/*
if(flagError12 == true){
printf("Derivative %i Rel Error Exceeded:\n",j);
printf("x dx_relErr dx_calcVal dx_sample"
" dx2_relErr dx2_calcVal dx2_sample\n");
for(int i=0; i<mcfSample.rows(); i++){
if(tolExceeded12V(i) == 1){
printf("%f %f %f %f %f %f %f",
mcfSample(i,0),relError(i,0),mcfSample(i,2),numSample(i,0),
relError(i,1),mcfSample(i,3),numSample(i,1));
}
}
}
flagError12=false;*/
//tolExceeded12V =
//RigidBodyDynamics::Math::VectorNd::Zero(mcfSample.rows());
}
return (tolExceeded12 == 0);
}
| 28.915888 | 81 | 0.529282 | [
"geometry",
"model"
] |
139360c5bcdff09c387927b4338946cfbb039bb8 | 46,944 | cpp | C++ | level_zero/core/test/unit_tests/sources/cmdqueue/test_cmdqueue_2.cpp | WeixiZhu94/intel-opencl-runtime | 9ff1307b4b665a52d59c3d37c9c29e6952d32c93 | [
"Intel",
"MIT"
] | null | null | null | level_zero/core/test/unit_tests/sources/cmdqueue/test_cmdqueue_2.cpp | WeixiZhu94/intel-opencl-runtime | 9ff1307b4b665a52d59c3d37c9c29e6952d32c93 | [
"Intel",
"MIT"
] | null | null | null | level_zero/core/test/unit_tests/sources/cmdqueue/test_cmdqueue_2.cpp | WeixiZhu94/intel-opencl-runtime | 9ff1307b4b665a52d59c3d37c9c29e6952d32c93 | [
"Intel",
"MIT"
] | null | null | null | /*
* Copyright (C) 2021-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/command_stream/scratch_space_controller_xehp_and_later.h"
#include "shared/test/common/cmd_parse/gen_cmd_parse.h"
#include "shared/test/common/libult/ult_command_stream_receiver.h"
#include "shared/test/common/mocks/mock_command_stream_receiver.h"
#include "shared/test/common/mocks/mock_memory_manager.h"
#include "shared/test/common/mocks/mock_memory_operations_handler.h"
#include "shared/test/common/mocks/ult_device_factory.h"
#include "shared/test/common/test_macros/mock_method_macros.h"
#include "shared/test/common/test_macros/test.h"
#include "level_zero/core/test/unit_tests/fixtures/aub_csr_fixture.h"
#include "level_zero/core/test/unit_tests/fixtures/device_fixture.h"
#include "level_zero/core/test/unit_tests/mocks/mock_cmdlist.h"
#include "level_zero/core/test/unit_tests/mocks/mock_cmdqueue.h"
#include "level_zero/core/test/unit_tests/mocks/mock_kernel.h"
#include "test_traits_common.h"
namespace L0 {
namespace ult {
using ContextCreateCommandQueueTest = Test<ContextFixture>;
TEST_F(ContextCreateCommandQueueTest, givenCallToContextCreateCommandQueueThenCallSucceeds) {
ze_command_queue_desc_t desc = {};
desc.ordinal = 0u;
ze_command_queue_handle_t commandQueue = {};
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
EXPECT_NE(nullptr, commandQueue);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
HWTEST_F(ContextCreateCommandQueueTest, givenEveryPossibleGroupIndexWhenCreatingCommandQueueThenCommandQueueIsCreated) {
ze_command_queue_handle_t commandQueue = {};
auto &engineGroups = neoDevice->getRegularEngineGroups();
for (uint32_t ordinal = 0; ordinal < engineGroups.size(); ordinal++) {
for (uint32_t index = 0; index < engineGroups[ordinal].engines.size(); index++) {
ze_command_queue_desc_t desc = {};
desc.ordinal = ordinal;
desc.index = index;
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
EXPECT_NE(nullptr, commandQueue);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
}
}
HWTEST_F(ContextCreateCommandQueueTest, givenOrdinalBiggerThanAvailableEnginesWhenCreatingCommandQueueThenInvalidArgumentErrorIsReturned) {
ze_command_queue_handle_t commandQueue = {};
auto &engineGroups = neoDevice->getRegularEngineGroups();
ze_command_queue_desc_t desc = {};
desc.ordinal = static_cast<uint32_t>(engineGroups.size());
desc.index = 0;
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, res);
EXPECT_EQ(nullptr, commandQueue);
desc.ordinal = 0;
desc.index = 0x1000;
res = context->createCommandQueue(device, &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, res);
EXPECT_EQ(nullptr, commandQueue);
}
HWTEST_F(ContextCreateCommandQueueTest, givenRootDeviceAndImplicitScalingDisabledWhenCreatingCommandQueueThenValidateQueueOrdinalUsingSubDeviceEngines) {
NEO::UltDeviceFactory deviceFactory{1, 2};
auto &rootDevice = *deviceFactory.rootDevices[0];
auto &subDevice0 = *deviceFactory.subDevices[0];
rootDevice.regularEngineGroups.resize(1);
subDevice0.getRegularEngineGroups().push_back(NEO::Device::EngineGroupT{});
subDevice0.getRegularEngineGroups().back().engineGroupType = EngineGroupType::Compute;
subDevice0.getRegularEngineGroups().back().engines.resize(1);
subDevice0.getRegularEngineGroups().back().engines[0].commandStreamReceiver = &rootDevice.getGpgpuCommandStreamReceiver();
auto ordinal = static_cast<uint32_t>(subDevice0.getRegularEngineGroups().size() - 1);
Mock<L0::DeviceImp> l0RootDevice(&rootDevice, rootDevice.getExecutionEnvironment());
l0RootDevice.driverHandle = driverHandle.get();
ze_command_queue_handle_t commandQueue = nullptr;
ze_command_queue_desc_t desc = {ZE_STRUCTURE_TYPE_COMMAND_QUEUE_DESC};
desc.ordinal = ordinal;
desc.index = 0;
l0RootDevice.implicitScalingCapable = true;
ze_result_t res = context->createCommandQueue(l0RootDevice.toHandle(), &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, res);
EXPECT_EQ(nullptr, commandQueue);
l0RootDevice.implicitScalingCapable = false;
res = context->createCommandQueue(l0RootDevice.toHandle(), &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
EXPECT_NE(nullptr, commandQueue);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
using AubCsrTest = Test<AubCsrFixture>;
HWTEST_TEMPLATED_F(AubCsrTest, givenAubCsrWhenCallingExecuteCommandListsThenPollForCompletionIsCalled) {
auto csr = neoDevice->getDefaultEngine().commandStreamReceiver;
ze_result_t returnValue;
ze_command_queue_desc_t desc = {};
ze_command_queue_handle_t commandQueue = {};
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
ASSERT_EQ(ZE_RESULT_SUCCESS, res);
ASSERT_NE(nullptr, commandQueue);
auto aub_csr = static_cast<NEO::UltAubCommandStreamReceiver<FamilyType> *>(csr);
CommandQueue *queue = static_cast<CommandQueue *>(L0::CommandQueue::fromHandle(commandQueue));
queue->setCommandQueuePreemptionMode(PreemptionMode::Disabled);
EXPECT_EQ(aub_csr->pollForCompletionCalled, 0u);
std::unique_ptr<L0::CommandList> commandList(L0::CommandList::create(productFamily, device, NEO::EngineGroupType::Compute, 0u, returnValue));
ASSERT_NE(nullptr, commandList);
auto commandListHandle = commandList->toHandle();
queue->executeCommandLists(1, &commandListHandle, nullptr, false);
EXPECT_EQ(aub_csr->pollForCompletionCalled, 1u);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
using CommandQueueSynchronizeTest = Test<ContextFixture>;
using MultiTileCommandQueueSynchronizeTest = Test<SingleRootMultiSubDeviceFixture>;
template <typename GfxFamily>
struct SynchronizeCsr : public NEO::UltCommandStreamReceiver<GfxFamily> {
SynchronizeCsr(const NEO::ExecutionEnvironment &executionEnvironment, const DeviceBitfield deviceBitfield)
: NEO::UltCommandStreamReceiver<GfxFamily>(const_cast<NEO::ExecutionEnvironment &>(executionEnvironment), 0, deviceBitfield) {
CommandStreamReceiver::tagAddress = &tagAddressData[0];
memset(const_cast<uint32_t *>(CommandStreamReceiver::tagAddress), 0xFFFFFFFF, tagSize * sizeof(uint32_t));
}
WaitStatus waitForCompletionWithTimeout(bool enableTimeout, int64_t timeoutMs, uint32_t taskCountToWait) override {
enableTimeoutSet = enableTimeout;
waitForComplitionCalledTimes++;
partitionCountSet = this->activePartitions;
return waitForCompletionWithTimeoutResult;
}
WaitStatus waitForTaskCountWithKmdNotifyFallback(uint32_t taskCountToWait, FlushStamp flushStampToWait, bool quickKmdSleep, bool forcePowerSavingMode) override {
waitForTaskCountWithKmdNotifyFallbackCalled++;
return NEO::UltCommandStreamReceiver<GfxFamily>::waitForTaskCountWithKmdNotifyFallback(taskCountToWait, flushStampToWait, quickKmdSleep, forcePowerSavingMode);
}
static constexpr size_t tagSize = 128;
static volatile uint32_t tagAddressData[tagSize];
uint32_t waitForComplitionCalledTimes = 0;
uint32_t waitForTaskCountWithKmdNotifyFallbackCalled = 0;
uint32_t partitionCountSet = 0;
bool enableTimeoutSet = false;
WaitStatus waitForCompletionWithTimeoutResult = WaitStatus::Ready;
};
template <typename GfxFamily>
volatile uint32_t SynchronizeCsr<GfxFamily>::tagAddressData[SynchronizeCsr<GfxFamily>::tagSize];
HWTEST_F(CommandQueueSynchronizeTest, givenCallToSynchronizeThenCorrectEnableTimeoutAndTimeoutValuesAreUsed) {
auto csr = std::unique_ptr<SynchronizeCsr<FamilyType>>(new SynchronizeCsr<FamilyType>(*device->getNEODevice()->getExecutionEnvironment(),
device->getNEODevice()->getDeviceBitfield()));
ze_command_queue_desc_t desc = {};
ze_command_queue_handle_t commandQueue = {};
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
EXPECT_NE(nullptr, commandQueue);
CommandQueue *queue = reinterpret_cast<CommandQueue *>(L0::CommandQueue::fromHandle(commandQueue));
queue->csr = csr.get();
uint64_t timeout = 10;
int64_t timeoutMicrosecondsExpected = timeout;
queue->synchronize(timeout);
EXPECT_EQ(1u, csr->waitForComplitionCalledTimes);
EXPECT_EQ(0u, csr->waitForTaskCountWithKmdNotifyFallbackCalled);
EXPECT_TRUE(csr->enableTimeoutSet);
timeout = std::numeric_limits<uint64_t>::max();
timeoutMicrosecondsExpected = NEO::TimeoutControls::maxTimeout;
queue->synchronize(timeout);
EXPECT_EQ(2u, csr->waitForComplitionCalledTimes);
EXPECT_EQ(0u, csr->waitForTaskCountWithKmdNotifyFallbackCalled);
EXPECT_FALSE(csr->enableTimeoutSet);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
HWTEST_F(CommandQueueSynchronizeTest, givenGpuHangWhenCallingSynchronizeThenErrorIsPropagated) {
auto csr = std::unique_ptr<SynchronizeCsr<FamilyType>>(new SynchronizeCsr<FamilyType>(*device->getNEODevice()->getExecutionEnvironment(),
device->getNEODevice()->getDeviceBitfield()));
csr->waitForCompletionWithTimeoutResult = NEO::WaitStatus::GpuHang;
ze_command_queue_desc_t desc{};
ze_command_queue_handle_t commandQueue{};
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
ASSERT_EQ(ZE_RESULT_SUCCESS, res);
ASSERT_NE(nullptr, commandQueue);
auto queue = whitebox_cast(L0::CommandQueue::fromHandle(commandQueue));
queue->csr = csr.get();
constexpr auto timeout{std::numeric_limits<uint64_t>::max()};
const auto synchronizationResult{queue->synchronize(timeout)};
EXPECT_EQ(ZE_RESULT_ERROR_DEVICE_LOST, synchronizationResult);
EXPECT_EQ(1u, csr->waitForComplitionCalledTimes);
EXPECT_EQ(0u, csr->waitForTaskCountWithKmdNotifyFallbackCalled);
EXPECT_FALSE(csr->enableTimeoutSet);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
HWTEST_F(CommandQueueSynchronizeTest, givenDebugOverrideEnabledAndGpuHangWhenCallingSynchronizeThenErrorIsPropagated) {
DebugManagerStateRestore restore;
NEO::DebugManager.flags.OverrideUseKmdWaitFunction.set(1);
auto csr = std::unique_ptr<SynchronizeCsr<FamilyType>>(new SynchronizeCsr<FamilyType>(*device->getNEODevice()->getExecutionEnvironment(),
device->getNEODevice()->getDeviceBitfield()));
csr->waitForCompletionWithTimeoutResult = NEO::WaitStatus::GpuHang;
ze_command_queue_desc_t desc{};
ze_command_queue_handle_t commandQueue{};
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
ASSERT_EQ(ZE_RESULT_SUCCESS, res);
ASSERT_NE(nullptr, commandQueue);
auto queue = whitebox_cast(L0::CommandQueue::fromHandle(commandQueue));
queue->csr = csr.get();
constexpr auto timeout{std::numeric_limits<uint64_t>::max()};
const auto synchronizationResult{queue->synchronize(timeout)};
EXPECT_EQ(ZE_RESULT_ERROR_DEVICE_LOST, synchronizationResult);
EXPECT_EQ(1u, csr->waitForComplitionCalledTimes);
EXPECT_EQ(1u, csr->waitForTaskCountWithKmdNotifyFallbackCalled);
EXPECT_FALSE(csr->enableTimeoutSet);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
HWTEST_F(CommandQueueSynchronizeTest, givenDebugOverrideEnabledWhenCallToSynchronizeThenCorrectEnableTimeoutAndTimeoutValuesAreUsed) {
DebugManagerStateRestore restore;
NEO::DebugManager.flags.OverrideUseKmdWaitFunction.set(1);
auto csr = std::unique_ptr<SynchronizeCsr<FamilyType>>(new SynchronizeCsr<FamilyType>(*device->getNEODevice()->getExecutionEnvironment(),
device->getNEODevice()->getDeviceBitfield()));
ze_command_queue_desc_t desc = {};
ze_command_queue_handle_t commandQueue = {};
ze_result_t res = context->createCommandQueue(device, &desc, &commandQueue);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
EXPECT_NE(nullptr, commandQueue);
CommandQueue *queue = reinterpret_cast<CommandQueue *>(L0::CommandQueue::fromHandle(commandQueue));
queue->csr = csr.get();
uint64_t timeout = 10;
bool enableTimeoutExpected = true;
int64_t timeoutMicrosecondsExpected = timeout;
queue->synchronize(timeout);
EXPECT_EQ(1u, csr->waitForComplitionCalledTimes);
EXPECT_EQ(0u, csr->waitForTaskCountWithKmdNotifyFallbackCalled);
EXPECT_TRUE(csr->enableTimeoutSet);
timeout = std::numeric_limits<uint64_t>::max();
enableTimeoutExpected = false;
timeoutMicrosecondsExpected = NEO::TimeoutControls::maxTimeout;
queue->synchronize(timeout);
EXPECT_EQ(2u, csr->waitForComplitionCalledTimes);
EXPECT_EQ(1u, csr->waitForTaskCountWithKmdNotifyFallbackCalled);
EXPECT_FALSE(csr->enableTimeoutSet);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
HWTEST2_F(MultiTileCommandQueueSynchronizeTest, givenMultiplePartitionCountWhenCallingSynchronizeThenExpectTheSameNumberCsrSynchronizeCalls, IsAtLeastXeHpCore) {
const ze_command_queue_desc_t desc{};
ze_result_t returnValue;
auto csr = reinterpret_cast<NEO::UltCommandStreamReceiver<FamilyType> *>(neoDevice->getDefaultEngine().commandStreamReceiver);
if (device->getNEODevice()->getPreemptionMode() == PreemptionMode::MidThread || device->getNEODevice()->isDebuggerActive()) {
csr->createPreemptionAllocation();
}
EXPECT_NE(0u, csr->getPostSyncWriteOffset());
volatile uint32_t *tagAddress = csr->getTagAddress();
for (uint32_t i = 0; i < 2; i++) {
*tagAddress = 0xFF;
tagAddress = ptrOffset(tagAddress, csr->getPostSyncWriteOffset());
}
csr->activePartitions = 2u;
auto commandQueue = whitebox_cast(CommandQueue::create(productFamily,
device,
neoDevice->getDefaultEngine().commandStreamReceiver,
&desc,
false,
false,
returnValue));
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
ASSERT_NE(nullptr, commandQueue);
EXPECT_EQ(2u, commandQueue->activeSubDevices);
auto commandList = std::unique_ptr<CommandList>(whitebox_cast(CommandList::create(productFamily, device, NEO::EngineGroupType::RenderCompute, 0u, returnValue)));
ASSERT_NE(nullptr, commandList);
commandList->partitionCount = 2;
ze_command_list_handle_t cmdListHandle = commandList->toHandle();
returnValue = commandQueue->executeCommandLists(1, &cmdListHandle, nullptr, false);
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
uint64_t timeout = std::numeric_limits<uint64_t>::max();
commandQueue->synchronize(timeout);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
HWTEST2_F(MultiTileCommandQueueSynchronizeTest, givenCsrHasMultipleActivePartitionWhenExecutingCmdListOnNewCmdQueueThenExpectCmdPartitionCountMatchCsrActivePartitions, IsAtLeastXeHpCore) {
const ze_command_queue_desc_t desc{};
ze_result_t returnValue;
auto csr = reinterpret_cast<NEO::UltCommandStreamReceiver<FamilyType> *>(neoDevice->getDefaultEngine().commandStreamReceiver);
if (device->getNEODevice()->getPreemptionMode() == PreemptionMode::MidThread || device->getNEODevice()->isDebuggerActive()) {
csr->createPreemptionAllocation();
}
EXPECT_NE(0u, csr->getPostSyncWriteOffset());
volatile uint32_t *tagAddress = csr->getTagAddress();
for (uint32_t i = 0; i < 2; i++) {
*tagAddress = 0xFF;
tagAddress = ptrOffset(tagAddress, csr->getPostSyncWriteOffset());
}
csr->activePartitions = 2u;
auto commandQueue = whitebox_cast(CommandQueue::create(productFamily,
device,
neoDevice->getDefaultEngine().commandStreamReceiver,
&desc,
false,
false,
returnValue));
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
ASSERT_NE(nullptr, commandQueue);
EXPECT_EQ(2u, commandQueue->activeSubDevices);
auto commandList = std::unique_ptr<CommandList>(whitebox_cast(CommandList::create(productFamily, device, NEO::EngineGroupType::RenderCompute, 0u, returnValue)));
ASSERT_NE(nullptr, commandList);
ze_command_list_handle_t cmdListHandle = commandList->toHandle();
commandQueue->executeCommandLists(1, &cmdListHandle, nullptr, false);
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
EXPECT_EQ(2u, commandQueue->partitionCount);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
HWTEST_F(CommandQueueSynchronizeTest, givenSingleTileCsrWhenExecutingMultiTileCommandListThenExpectErrorOnExecute) {
const ze_command_queue_desc_t desc{};
ze_result_t returnValue;
auto commandQueue = whitebox_cast(CommandQueue::create(productFamily,
device,
neoDevice->getDefaultEngine().commandStreamReceiver,
&desc,
false,
false,
returnValue));
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
ASSERT_NE(nullptr, commandQueue);
EXPECT_EQ(1u, commandQueue->activeSubDevices);
auto commandList = std::unique_ptr<CommandList>(whitebox_cast(CommandList::create(productFamily, device, NEO::EngineGroupType::RenderCompute, 0u, returnValue)));
ASSERT_NE(nullptr, commandList);
commandList->partitionCount = 2;
ze_command_list_handle_t cmdListHandle = commandList->toHandle();
returnValue = commandQueue->executeCommandLists(1, &cmdListHandle, nullptr, false);
EXPECT_EQ(returnValue, ZE_RESULT_ERROR_INVALID_COMMAND_LIST_TYPE);
L0::CommandQueue::fromHandle(commandQueue)->destroy();
}
template <typename GfxFamily>
struct TestCmdQueueCsr : public NEO::UltCommandStreamReceiver<GfxFamily> {
TestCmdQueueCsr(const NEO::ExecutionEnvironment &executionEnvironment, const DeviceBitfield deviceBitfield)
: NEO::UltCommandStreamReceiver<GfxFamily>(const_cast<NEO::ExecutionEnvironment &>(executionEnvironment), 0, deviceBitfield) {
}
ADDMETHOD_NOBASE(waitForCompletionWithTimeout, NEO::WaitStatus, NEO::WaitStatus::NotReady, (bool enableTimeout, int64_t timeoutMs, uint32_t taskCountToWait));
};
HWTEST_F(CommandQueueSynchronizeTest, givenSinglePartitionCountWhenWaitFunctionFailsThenReturnNotReady) {
auto csr = std::unique_ptr<TestCmdQueueCsr<FamilyType>>(new TestCmdQueueCsr<FamilyType>(*device->getNEODevice()->getExecutionEnvironment(),
device->getNEODevice()->getDeviceBitfield()));
csr->setupContext(*device->getNEODevice()->getDefaultEngine().osContext);
const ze_command_queue_desc_t desc{};
ze_result_t returnValue;
auto commandQueue = whitebox_cast(CommandQueue::create(productFamily,
device,
csr.get(),
&desc,
false,
false,
returnValue));
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
ASSERT_NE(nullptr, commandQueue);
uint64_t timeout = std::numeric_limits<uint64_t>::max();
returnValue = commandQueue->synchronize(timeout);
EXPECT_EQ(returnValue, ZE_RESULT_NOT_READY);
commandQueue->destroy();
EXPECT_EQ(1u, csr->waitForCompletionWithTimeoutCalled);
}
using CommandQueuePowerHintTest = Test<ContextFixture>;
HWTEST_F(CommandQueuePowerHintTest, givenDriverHandleWithPowerHintAndOsContextPowerHintUnsetThenSuccessIsReturned) {
auto csr = std::unique_ptr<TestCmdQueueCsr<FamilyType>>(new TestCmdQueueCsr<FamilyType>(*device->getNEODevice()->getExecutionEnvironment(),
device->getNEODevice()->getDeviceBitfield()));
csr->setupContext(*device->getNEODevice()->getDefaultEngine().osContext);
DriverHandleImp *driverHandleImp = static_cast<DriverHandleImp *>(device->getDriverHandle());
driverHandleImp->powerHint = 1;
const ze_command_queue_desc_t desc{};
ze_result_t returnValue;
auto commandQueue = whitebox_cast(CommandQueue::create(productFamily,
device,
csr.get(),
&desc,
false,
false,
returnValue));
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
ASSERT_NE(nullptr, commandQueue);
commandQueue->destroy();
}
HWTEST_F(CommandQueuePowerHintTest, givenDriverHandleWithPowerHintAndOsContextPowerHintAlreadySetThenSuccessIsReturned) {
auto csr = std::unique_ptr<TestCmdQueueCsr<FamilyType>>(new TestCmdQueueCsr<FamilyType>(*device->getNEODevice()->getExecutionEnvironment(),
device->getNEODevice()->getDeviceBitfield()));
csr->setupContext(*device->getNEODevice()->getDefaultEngine().osContext);
DriverHandleImp *driverHandleImp = static_cast<DriverHandleImp *>(device->getDriverHandle());
driverHandleImp->powerHint = 1;
auto &osContext = csr->getOsContext();
osContext.setUmdPowerHintValue(1);
const ze_command_queue_desc_t desc{};
ze_result_t returnValue;
auto commandQueue = whitebox_cast(CommandQueue::create(productFamily,
device,
csr.get(),
&desc,
false,
false,
returnValue));
EXPECT_EQ(returnValue, ZE_RESULT_SUCCESS);
ASSERT_NE(nullptr, commandQueue);
commandQueue->destroy();
}
struct MemoryManagerCommandQueueCreateNegativeTest : public NEO::MockMemoryManager {
MemoryManagerCommandQueueCreateNegativeTest(NEO::ExecutionEnvironment &executionEnvironment) : NEO::MockMemoryManager(const_cast<NEO::ExecutionEnvironment &>(executionEnvironment)) {}
NEO::GraphicsAllocation *allocateGraphicsMemoryWithProperties(const NEO::AllocationProperties &properties) override {
if (forceFailureInPrimaryAllocation) {
return nullptr;
}
return NEO::MemoryManager::allocateGraphicsMemoryWithProperties(properties);
}
bool forceFailureInPrimaryAllocation = false;
};
struct CommandQueueCreateNegativeTest : public ::testing::Test {
void SetUp() override {
executionEnvironment = new NEO::ExecutionEnvironment();
executionEnvironment->prepareRootDeviceEnvironments(numRootDevices);
for (uint32_t i = 0; i < numRootDevices; i++) {
executionEnvironment->rootDeviceEnvironments[i]->setHwInfo(NEO::defaultHwInfo.get());
}
memoryManager = new MemoryManagerCommandQueueCreateNegativeTest(*executionEnvironment);
executionEnvironment->memoryManager.reset(memoryManager);
std::vector<std::unique_ptr<NEO::Device>> devices;
for (uint32_t i = 0; i < numRootDevices; i++) {
neoDevice = NEO::MockDevice::create<NEO::MockDevice>(executionEnvironment, i);
devices.push_back(std::unique_ptr<NEO::Device>(neoDevice));
}
driverHandle = std::make_unique<Mock<L0::DriverHandleImp>>();
driverHandle->initialize(std::move(devices));
device = driverHandle->devices[0];
}
void TearDown() override {
}
NEO::ExecutionEnvironment *executionEnvironment = nullptr;
std::unique_ptr<Mock<L0::DriverHandleImp>> driverHandle;
NEO::MockDevice *neoDevice = nullptr;
L0::Device *device = nullptr;
MemoryManagerCommandQueueCreateNegativeTest *memoryManager = nullptr;
const uint32_t numRootDevices = 1u;
};
TEST_F(CommandQueueCreateNegativeTest, whenDeviceAllocationFailsDuringCommandQueueCreateThenAppropriateValueIsReturned) {
const ze_command_queue_desc_t desc = {};
auto csr = std::unique_ptr<NEO::CommandStreamReceiver>(neoDevice->createCommandStreamReceiver());
csr->setupContext(*neoDevice->getDefaultEngine().osContext);
memoryManager->forceFailureInPrimaryAllocation = true;
ze_result_t returnValue;
L0::CommandQueue *commandQueue = CommandQueue::create(productFamily,
device,
csr.get(),
&desc,
false,
false,
returnValue);
EXPECT_EQ(ZE_RESULT_ERROR_OUT_OF_DEVICE_MEMORY, returnValue);
ASSERT_EQ(nullptr, commandQueue);
}
struct CommandQueueInitTests : public ::testing::Test {
class MyMemoryManager : public OsAgnosticMemoryManager {
public:
using OsAgnosticMemoryManager::OsAgnosticMemoryManager;
NEO::GraphicsAllocation *allocateGraphicsMemoryWithProperties(const AllocationProperties &properties) override {
storedAllocationProperties.push_back(properties);
return OsAgnosticMemoryManager::allocateGraphicsMemoryWithProperties(properties);
}
std::vector<AllocationProperties> storedAllocationProperties;
};
void SetUp() override {
DebugManager.flags.CreateMultipleSubDevices.set(numSubDevices);
auto executionEnvironment = new NEO::ExecutionEnvironment();
executionEnvironment->prepareRootDeviceEnvironments(numRootDevices);
executionEnvironment->rootDeviceEnvironments[0]->setHwInfo(NEO::defaultHwInfo.get());
memoryManager = new MyMemoryManager(*executionEnvironment);
executionEnvironment->memoryManager.reset(memoryManager);
neoDevice = NEO::MockDevice::create<NEO::MockDevice>(executionEnvironment, 0);
std::vector<std::unique_ptr<NEO::Device>> devices;
devices.push_back(std::unique_ptr<NEO::Device>(neoDevice));
driverHandle = std::make_unique<Mock<L0::DriverHandleImp>>();
driverHandle->initialize(std::move(devices));
device = driverHandle->devices[0];
}
VariableBackup<bool> mockDeviceFlagBackup{&NEO::MockDevice::createSingleDevice, false};
DebugManagerStateRestore restore;
NEO::MockDevice *neoDevice = nullptr;
std::unique_ptr<Mock<L0::DriverHandleImp>> driverHandle;
L0::Device *device = nullptr;
MyMemoryManager *memoryManager = nullptr;
const uint32_t numRootDevices = 1;
const uint32_t numSubDevices = 4;
};
TEST_F(CommandQueueInitTests, givenMultipleSubDevicesWhenInitializingThenAllocateForAllSubDevices) {
ze_command_queue_desc_t desc = {};
auto csr = std::unique_ptr<NEO::CommandStreamReceiver>(neoDevice->createCommandStreamReceiver());
csr->setupContext(*neoDevice->getDefaultEngine().osContext);
ze_result_t returnValue;
L0::CommandQueue *commandQueue = CommandQueue::create(productFamily, device, csr.get(), &desc, false, false, returnValue);
EXPECT_NE(nullptr, commandQueue);
const uint64_t expectedBitfield = maxNBitValue(numSubDevices);
uint32_t cmdBufferAllocationsFound = 0;
for (auto &allocationProperties : memoryManager->storedAllocationProperties) {
if (allocationProperties.allocationType == NEO::GraphicsAllocation::AllocationType::COMMAND_BUFFER) {
cmdBufferAllocationsFound++;
EXPECT_EQ(expectedBitfield, allocationProperties.subDevicesBitfield.to_ulong());
EXPECT_EQ(1u, allocationProperties.flags.multiOsContextCapable);
}
}
EXPECT_EQ(static_cast<uint32_t>(CommandQueueImp::CommandBufferManager::BUFFER_ALLOCATION::COUNT), cmdBufferAllocationsFound);
commandQueue->destroy();
}
TEST_F(CommandQueueInitTests, whenDestroyCommandQueueThenStoreCommandBuffersAsReusableAllocations) {
ze_command_queue_desc_t desc = {};
auto csr = std::unique_ptr<NEO::CommandStreamReceiver>(neoDevice->createCommandStreamReceiver());
csr->setupContext(*neoDevice->getDefaultEngine().osContext);
ze_result_t returnValue;
L0::CommandQueue *commandQueue = CommandQueue::create(productFamily, device, csr.get(), &desc, false, false, returnValue);
EXPECT_NE(nullptr, commandQueue);
auto deviceImp = static_cast<DeviceImp *>(device);
EXPECT_TRUE(deviceImp->allocationsForReuse->peekIsEmpty());
commandQueue->destroy();
EXPECT_FALSE(deviceImp->allocationsForReuse->peekIsEmpty());
}
struct DeviceWithDualStorage : Test<DeviceFixture> {
void SetUp() override {
NEO::MockCompilerEnableGuard mock(true);
DebugManager.flags.EnableLocalMemory.set(1);
DebugManager.flags.AllocateSharedAllocationsWithCpuAndGpuStorage.set(1);
DeviceFixture::SetUp();
}
void TearDown() override {
DeviceFixture::TearDown();
}
DebugManagerStateRestore restorer;
};
HWTEST2_F(DeviceWithDualStorage, givenCmdListWithAppendedKernelAndUsmTransferAndBlitterDisabledWhenExecuteCmdListThenCfeStateOnceProgrammed, IsAtLeastXeHpCore) {
using CFE_STATE = typename FamilyType::CFE_STATE;
neoDevice->executionEnvironment->rootDeviceEnvironments[0]->memoryOperationsInterface = std::make_unique<MockMemoryOperationsHandler>();
ze_result_t res = ZE_RESULT_SUCCESS;
const ze_command_queue_desc_t desc = {};
auto commandQueue = whitebox_cast(CommandQueue::create(productFamily,
device,
neoDevice->getInternalEngine().commandStreamReceiver,
&desc,
false,
false,
res));
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
ASSERT_NE(nullptr, commandQueue);
auto commandList = std::unique_ptr<CommandList>(whitebox_cast(CommandList::create(productFamily, device, NEO::EngineGroupType::RenderCompute, 0u, res)));
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
ASSERT_NE(nullptr, commandList);
Mock<Kernel> kernel;
kernel.immutableData.device = device;
size_t size = 10;
size_t alignment = 1u;
void *ptr = nullptr;
ze_device_mem_alloc_desc_t deviceDesc = {};
ze_host_mem_alloc_desc_t hostDesc = {};
res = context->allocSharedMem(device->toHandle(),
&deviceDesc,
&hostDesc,
size, alignment, &ptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, res);
auto gpuAlloc = device->getDriverHandle()->getSvmAllocsManager()->getSVMAllocs()->get(ptr)->gpuAllocations.getGraphicsAllocation(device->getRootDeviceIndex());
kernel.residencyContainer.push_back(gpuAlloc);
ze_group_count_t dispatchFunctionArguments{1, 1, 1};
commandList->appendLaunchKernel(kernel.toHandle(), &dispatchFunctionArguments, nullptr, 0, nullptr);
auto deviceImp = static_cast<DeviceImp *>(device);
auto pageFaultCmdQueue = whitebox_cast(deviceImp->pageFaultCommandList->cmdQImmediate);
auto sizeBefore = commandQueue->commandStream->getUsed();
auto pageFaultSizeBefore = pageFaultCmdQueue->commandStream->getUsed();
auto handle = commandList->toHandle();
commandQueue->executeCommandLists(1, &handle, nullptr, true);
auto sizeAfter = commandQueue->commandStream->getUsed();
auto pageFaultSizeAfter = pageFaultCmdQueue->commandStream->getUsed();
EXPECT_LT(sizeBefore, sizeAfter);
EXPECT_LT(pageFaultSizeBefore, pageFaultSizeAfter);
GenCmdList commands;
CmdParse<FamilyType>::parseCommandBuffer(commands, ptrOffset(commandQueue->commandStream->getCpuBase(), 0),
sizeAfter);
auto count = findAll<CFE_STATE *>(commands.begin(), commands.end()).size();
EXPECT_EQ(0u, count);
CmdParse<FamilyType>::parseCommandBuffer(commands, ptrOffset(pageFaultCmdQueue->commandStream->getCpuBase(), 0),
pageFaultSizeAfter);
count = findAll<CFE_STATE *>(commands.begin(), commands.end()).size();
EXPECT_EQ(1u, count);
res = context->freeMem(ptr);
ASSERT_EQ(ZE_RESULT_SUCCESS, res);
commandQueue->destroy();
}
using CommandQueueScratchTests = Test<DeviceFixture>;
using Platforms = IsAtLeastProduct<IGFX_XE_HP_SDV>;
HWTEST2_F(CommandQueueScratchTests, givenCommandQueueWhenHandleScratchSpaceThenProperScratchSlotIsSetAndScratchAllocationReturned, Platforms) {
class MockScratchSpaceControllerXeHPAndLater : public NEO::ScratchSpaceControllerXeHPAndLater {
public:
uint32_t scratchSlot = 0u;
bool programHeapsCalled = false;
NEO::GraphicsAllocation *scratchAllocation = nullptr;
MockScratchSpaceControllerXeHPAndLater(uint32_t rootDeviceIndex,
NEO::ExecutionEnvironment &environment,
InternalAllocationStorage &allocationStorage) : NEO::ScratchSpaceControllerXeHPAndLater(rootDeviceIndex, environment, allocationStorage) {}
void programHeaps(HeapContainer &heapContainer,
uint32_t scratchSlot,
uint32_t requiredPerThreadScratchSize,
uint32_t requiredPerThreadPrivateScratchSize,
uint32_t currentTaskCount,
OsContext &osContext,
bool &stateBaseAddressDirty,
bool &vfeStateDirty) override {
this->scratchSlot = scratchSlot;
programHeapsCalled = true;
}
NEO::GraphicsAllocation *getScratchSpaceAllocation() override {
return scratchAllocation;
}
protected:
};
MockCommandStreamReceiver csr(*neoDevice->getExecutionEnvironment(), 0, neoDevice->getDeviceBitfield());
csr.initializeTagAllocation();
csr.setupContext(*neoDevice->getDefaultEngine().osContext);
NEO::ExecutionEnvironment *execEnv = static_cast<NEO::ExecutionEnvironment *>(device->getExecEnvironment());
std::unique_ptr<ScratchSpaceController> scratchController = std::make_unique<MockScratchSpaceControllerXeHPAndLater>(device->getRootDeviceIndex(),
*execEnv,
*csr.getInternalAllocationStorage());
const ze_command_queue_desc_t desc = {};
std::unique_ptr<L0::CommandQueue> commandQueue = std::make_unique<MockCommandQueueHw<gfxCoreFamily>>(device, &csr, &desc);
auto commandQueueHw = static_cast<MockCommandQueueHw<gfxCoreFamily> *>(commandQueue.get());
NEO::ResidencyContainer residencyContainer;
NEO::HeapContainer heapContainer;
void *surfaceHeap = alignedMalloc(0x1000, 0x1000);
NEO::GraphicsAllocation graphicsAllocationHeap(0, NEO::GraphicsAllocation::AllocationType::BUFFER, surfaceHeap, 0u, 0u, 1u, MemoryPool::System4KBPages, 1u);
heapContainer.push_back(&graphicsAllocationHeap);
bool gsbaStateDirty = false;
bool frontEndStateDirty = false;
NEO::GraphicsAllocation graphicsAllocation(1u, NEO::GraphicsAllocation::AllocationType::BUFFER, nullptr, 0u, 0u, 0u, MemoryPool::System4KBPages, 0u);
auto scratch = static_cast<MockScratchSpaceControllerXeHPAndLater *>(scratchController.get());
scratch->scratchAllocation = &graphicsAllocation;
commandQueueHw->handleScratchSpace(heapContainer, scratchController.get(), gsbaStateDirty, frontEndStateDirty, 0x1000, 0u);
EXPECT_TRUE(scratch->programHeapsCalled);
EXPECT_GT(csr.makeResidentCalledTimes, 0u);
alignedFree(surfaceHeap);
}
HWTEST2_F(CommandQueueScratchTests, givenCommandQueueWhenHandleScratchSpaceAndHeapContainerIsZeroSizeThenNoFunctionIsCalled, Platforms) {
class MockScratchSpaceControllerXeHPAndLater : public NEO::ScratchSpaceControllerXeHPAndLater {
public:
using NEO::ScratchSpaceControllerXeHPAndLater::scratchAllocation;
bool programHeapsCalled = false;
MockScratchSpaceControllerXeHPAndLater(uint32_t rootDeviceIndex,
NEO::ExecutionEnvironment &environment,
InternalAllocationStorage &allocationStorage) : NEO::ScratchSpaceControllerXeHPAndLater(rootDeviceIndex, environment, allocationStorage) {}
void programHeaps(HeapContainer &heapContainer,
uint32_t scratchSlot,
uint32_t requiredPerThreadScratchSize,
uint32_t requiredPerThreadPrivateScratchSize,
uint32_t currentTaskCount,
OsContext &osContext,
bool &stateBaseAddressDirty,
bool &vfeStateDirty) override {
programHeapsCalled = true;
}
protected:
};
MockCommandStreamReceiver csr(*neoDevice->getExecutionEnvironment(), 0, neoDevice->getDeviceBitfield());
csr.initializeTagAllocation();
csr.setupContext(*neoDevice->getDefaultEngine().osContext);
NEO::ExecutionEnvironment *execEnv = static_cast<NEO::ExecutionEnvironment *>(device->getExecEnvironment());
std::unique_ptr<ScratchSpaceController> scratchController = std::make_unique<MockScratchSpaceControllerXeHPAndLater>(device->getRootDeviceIndex(),
*execEnv,
*csr.getInternalAllocationStorage());
const ze_command_queue_desc_t desc = {};
std::unique_ptr<L0::CommandQueue> commandQueue = std::make_unique<MockCommandQueueHw<gfxCoreFamily>>(device, &csr, &desc);
auto commandQueueHw = static_cast<MockCommandQueueHw<gfxCoreFamily> *>(commandQueue.get());
NEO::ResidencyContainer residencyContainer;
NEO::HeapContainer heapContainer;
bool gsbaStateDirty = false;
bool frontEndStateDirty = false;
NEO::GraphicsAllocation graphicsAllocation(1u, NEO::GraphicsAllocation::AllocationType::BUFFER, nullptr, 0u, 0u, 0u, MemoryPool::System4KBPages, 0u);
auto scratch = static_cast<MockScratchSpaceControllerXeHPAndLater *>(scratchController.get());
scratch->scratchAllocation = &graphicsAllocation;
commandQueueHw->handleScratchSpace(heapContainer, scratchController.get(), gsbaStateDirty, frontEndStateDirty, 0x1000, 0u);
EXPECT_FALSE(scratch->programHeapsCalled);
scratch->scratchAllocation = nullptr;
}
HWTEST2_F(CommandQueueScratchTests, givenCommandQueueWhenBindlessEnabledThenHandleScratchSpaceCallsProgramBindlessSurfaceStateForScratch, Platforms) {
DebugManagerStateRestore restorer;
DebugManager.flags.UseBindlessMode.set(1);
class MockScratchSpaceControllerXeHPAndLater : public NEO::ScratchSpaceControllerXeHPAndLater {
public:
bool programHeapsCalled = false;
NEO::MockGraphicsAllocation alloc;
MockScratchSpaceControllerXeHPAndLater(uint32_t rootDeviceIndex,
NEO::ExecutionEnvironment &environment,
InternalAllocationStorage &allocationStorage) : NEO::ScratchSpaceControllerXeHPAndLater(rootDeviceIndex, environment, allocationStorage) {}
void programBindlessSurfaceStateForScratch(BindlessHeapsHelper *heapsHelper,
uint32_t requiredPerThreadScratchSize,
uint32_t requiredPerThreadPrivateScratchSize,
uint32_t currentTaskCount,
OsContext &osContext,
bool &stateBaseAddressDirty,
bool &vfeStateDirty,
NEO::CommandStreamReceiver *csr) override {
programHeapsCalled = true;
}
NEO::GraphicsAllocation *getScratchSpaceAllocation() override {
return &alloc;
}
protected:
};
MockCsrHw2<FamilyType> csr(*neoDevice->getExecutionEnvironment(), 0, neoDevice->getDeviceBitfield());
csr.initializeTagAllocation();
csr.setupContext(*neoDevice->getDefaultEngine().osContext);
NEO::ExecutionEnvironment *execEnv = static_cast<NEO::ExecutionEnvironment *>(device->getExecEnvironment());
std::unique_ptr<ScratchSpaceController> scratchController = std::make_unique<MockScratchSpaceControllerXeHPAndLater>(device->getRootDeviceIndex(),
*execEnv,
*csr.getInternalAllocationStorage());
const ze_command_queue_desc_t desc = {};
std::unique_ptr<L0::CommandQueue> commandQueue = std::make_unique<MockCommandQueueHw<gfxCoreFamily>>(device, &csr, &desc);
auto commandQueueHw = static_cast<MockCommandQueueHw<gfxCoreFamily> *>(commandQueue.get());
bool gsbaStateDirty = false;
bool frontEndStateDirty = false;
NEO::ResidencyContainer residency;
NEO::HeapContainer heapContainer;
// scratch part
commandQueueHw->handleScratchSpace(heapContainer, scratchController.get(), gsbaStateDirty, frontEndStateDirty, 0x1000, 0u);
EXPECT_TRUE(static_cast<MockScratchSpaceControllerXeHPAndLater *>(scratchController.get())->programHeapsCalled);
// private part
static_cast<MockScratchSpaceControllerXeHPAndLater *>(scratchController.get())->programHeapsCalled = false;
commandQueueHw->handleScratchSpace(heapContainer, scratchController.get(), gsbaStateDirty, frontEndStateDirty, 0x0, 0x1000);
EXPECT_TRUE(static_cast<MockScratchSpaceControllerXeHPAndLater *>(scratchController.get())->programHeapsCalled);
}
HWTEST2_F(CommandQueueScratchTests, whenPatchCommandsIsCalledThenCommandsAreCorrectlyPatched, IsAtLeastXeHpCore) {
using CFE_STATE = typename FamilyType::CFE_STATE;
ze_command_queue_desc_t desc = {};
NEO::CommandStreamReceiver *csr = nullptr;
device->getCsrForOrdinalAndIndex(&csr, 0u, 0u);
auto commandQueue = std::make_unique<MockCommandQueueHw<gfxCoreFamily>>(device, csr, &desc);
auto commandList = std::make_unique<WhiteBox<::L0::CommandListCoreFamily<gfxCoreFamily>>>();
EXPECT_NO_THROW(commandQueue->patchCommands(*commandList, 0));
commandList->commandsToPatch.push_back({});
EXPECT_ANY_THROW(commandQueue->patchCommands(*commandList, 0));
commandList->commandsToPatch.clear();
CFE_STATE destinationCfeStates[4];
int32_t initialScratchAddress = 0x123400;
for (size_t i = 0; i < 4; i++) {
auto sourceCfeState = new CFE_STATE;
*sourceCfeState = FamilyType::cmdInitCfeState;
if constexpr (TestTraits<gfxCoreFamily>::numberOfWalkersInCfeStateSupported) {
sourceCfeState->setNumberOfWalkers(2);
}
sourceCfeState->setMaximumNumberOfThreads(16);
sourceCfeState->setScratchSpaceBuffer(initialScratchAddress);
destinationCfeStates[i] = FamilyType::cmdInitCfeState;
if constexpr (TestTraits<gfxCoreFamily>::numberOfWalkersInCfeStateSupported) {
EXPECT_NE(destinationCfeStates[i].getNumberOfWalkers(), sourceCfeState->getNumberOfWalkers());
}
EXPECT_NE(destinationCfeStates[i].getMaximumNumberOfThreads(), sourceCfeState->getMaximumNumberOfThreads());
CommandList::CommandToPatch commandToPatch;
commandToPatch.pDestination = &destinationCfeStates[i];
commandToPatch.pCommand = sourceCfeState;
commandToPatch.type = CommandList::CommandToPatch::CommandType::FrontEndState;
commandList->commandsToPatch.push_back(commandToPatch);
}
uint64_t patchedScratchAddress = 0xABCD00;
commandQueue->patchCommands(*commandList, patchedScratchAddress);
for (size_t i = 0; i < 4; i++) {
EXPECT_EQ(patchedScratchAddress, destinationCfeStates[i].getScratchSpaceBuffer());
auto &sourceCfeState = *reinterpret_cast<CFE_STATE *>(commandList->commandsToPatch[i].pCommand);
if constexpr (TestTraits<gfxCoreFamily>::numberOfWalkersInCfeStateSupported) {
EXPECT_EQ(destinationCfeStates[i].getNumberOfWalkers(), sourceCfeState.getNumberOfWalkers());
}
EXPECT_EQ(destinationCfeStates[i].getMaximumNumberOfThreads(), sourceCfeState.getMaximumNumberOfThreads());
EXPECT_EQ(destinationCfeStates[i].getScratchSpaceBuffer(), sourceCfeState.getScratchSpaceBuffer());
}
}
} // namespace ult
} // namespace L0
| 50.153846 | 188 | 0.67998 | [
"vector"
] |
1395b676332e3860b9545720afeddd7e73c375c6 | 493 | hpp | C++ | cpp/src/samchon/templates/external/base/ExternalSystemBase.hpp | wydingez/truck-packer | c59d2ec322b08ac9ba773616a886a575d2af6461 | [
"BSD-3-Clause"
] | 111 | 2016-04-08T14:10:15.000Z | 2020-12-21T12:25:10.000Z | cpp/src/samchon/templates/external/base/ExternalSystemBase.hpp | wydingez/truck-packer | c59d2ec322b08ac9ba773616a886a575d2af6461 | [
"BSD-3-Clause"
] | 16 | 2016-05-27T05:41:56.000Z | 2020-06-23T14:55:00.000Z | cpp/src/samchon/templates/external/base/ExternalSystemBase.hpp | wydingez/truck-packer | c59d2ec322b08ac9ba773616a886a575d2af6461 | [
"BSD-3-Clause"
] | 49 | 2016-10-27T09:45:35.000Z | 2020-12-21T12:25:13.000Z | #pragma once
#include <samchon/API.hpp>
#include <samchon/templates/external/base/ExternalSystemArrayBase.hpp>
namespace samchon
{
namespace templates
{
namespace external
{
namespace base
{
class ExternalSystemBase
{
protected:
ExternalSystemArrayBase *system_array_;
public:
/**
* Get parent {@link ExternalSystemArray} object.
*/
template <typename SystemArray>
auto getSystemArray() const -> SystemArray*
{
return (SystemArray*)system_array_;
};
};
};
};
};
}; | 15.40625 | 70 | 0.726166 | [
"object"
] |
13989c352eff6e9fcea40e5116cab66c45e2af51 | 15,302 | cpp | C++ | third_party/skia_m63/third_party/externals/angle2/src/tests/gl_tests/ClearTest.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | null | null | null | third_party/skia_m63/third_party/externals/angle2/src/tests/gl_tests/ClearTest.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | null | null | null | third_party/skia_m63/third_party/externals/angle2/src/tests/gl_tests/ClearTest.cpp | kniefliu/WindowsSamples | c841268ef4a0f1c6f89b8e95bf68058ea2548394 | [
"MIT"
] | null | null | null | //
// Copyright 2015 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "test_utils/ANGLETest.h"
#include "random_utils.h"
using namespace angle;
namespace
{
Vector4 RandomVec4(int seed, float minValue, float maxValue)
{
RNG rng(seed);
srand(seed);
return Vector4(
rng.randomFloatBetween(minValue, maxValue), rng.randomFloatBetween(minValue, maxValue),
rng.randomFloatBetween(minValue, maxValue), rng.randomFloatBetween(minValue, maxValue));
}
GLColor Vec4ToColor(const Vector4 &vec)
{
GLColor color;
color.R = static_cast<uint8_t>(vec.x() * 255.0f);
color.G = static_cast<uint8_t>(vec.y() * 255.0f);
color.B = static_cast<uint8_t>(vec.z() * 255.0f);
color.A = static_cast<uint8_t>(vec.w() * 255.0f);
return color;
};
class ClearTestBase : public ANGLETest
{
protected:
ClearTestBase() : mProgram(0)
{
setWindowWidth(128);
setWindowHeight(128);
setConfigRedBits(8);
setConfigGreenBits(8);
setConfigBlueBits(8);
setConfigAlphaBits(8);
setConfigDepthBits(24);
}
void SetUp() override
{
ANGLETest::SetUp();
mFBOs.resize(2, 0);
glGenFramebuffers(2, mFBOs.data());
ASSERT_GL_NO_ERROR();
}
void TearDown() override
{
glDeleteProgram(mProgram);
if (!mFBOs.empty())
{
glDeleteFramebuffers(static_cast<GLsizei>(mFBOs.size()), mFBOs.data());
}
if (!mTextures.empty())
{
glDeleteTextures(static_cast<GLsizei>(mTextures.size()), mTextures.data());
}
ANGLETest::TearDown();
}
void setupDefaultProgram()
{
const std::string vertexShaderSource =
R"(precision highp float;
attribute vec4 position;
void main()
{
gl_Position = position;
})";
const std::string fragmentShaderSource =
R"(precision highp float;
void main()
{
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
})";
mProgram = CompileProgram(vertexShaderSource, fragmentShaderSource);
ASSERT_NE(0u, mProgram);
}
GLuint mProgram;
std::vector<GLuint> mFBOs;
std::vector<GLuint> mTextures;
};
class ClearTest : public ClearTestBase {};
class ClearTestES3 : public ClearTestBase {};
// Test clearing the default framebuffer
TEST_P(ClearTest, DefaultFramebuffer)
{
glClearColor(0.25f, 0.5f, 0.5f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT);
EXPECT_PIXEL_NEAR(0, 0, 64, 128, 128, 128, 1.0);
}
// Test clearing a RGBA8 Framebuffer
TEST_P(ClearTest, RGBA8Framebuffer)
{
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, getWindowWidth(), getWindowHeight(), 0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT);
EXPECT_PIXEL_NEAR(0, 0, 128, 128, 128, 128, 1.0);
}
TEST_P(ClearTest, ClearIssue)
{
// TODO(geofflang): Figure out why this is broken on Intel OpenGL
if (IsIntel() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE)
{
std::cout << "Test skipped on Intel OpenGL." << std::endl;
return;
}
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glClearColor(0.0, 1.0, 0.0, 1.0);
glClearDepthf(0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
EXPECT_GL_NO_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
GLuint rbo;
glGenRenderbuffers(1, &rbo);
glBindRenderbuffer(GL_RENDERBUFFER, rbo);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB565, 16, 16);
EXPECT_GL_NO_ERROR();
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo);
EXPECT_GL_NO_ERROR();
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
glClearDepthf(1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
EXPECT_GL_NO_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
setupDefaultProgram();
drawQuad(mProgram, "position", 0.5f);
EXPECT_PIXEL_EQ(0, 0, 0, 255, 0, 255);
}
// Requires ES3
// This tests a bug where in a masked clear when calling "ClearBuffer", we would
// mistakenly clear every channel (including the masked-out ones)
TEST_P(ClearTestES3, MaskedClearBufferBug)
{
unsigned char pixelData[] = { 255, 255, 255, 255 };
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
GLuint textures[2];
glGenTextures(2, &textures[0]);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelData);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[0], 0);
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelData);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, textures[1], 0);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_EQ(0, 0, 255, 255, 255, 255);
float clearValue[] = { 0, 0.5f, 0.5f, 1.0f };
GLenum drawBuffers[] = { GL_NONE, GL_COLOR_ATTACHMENT1 };
glDrawBuffers(2, drawBuffers);
glColorMask(GL_TRUE, GL_TRUE, GL_FALSE, GL_TRUE);
glClearBufferfv(GL_COLOR, 1, clearValue);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_EQ(0, 0, 255, 255, 255, 255);
glReadBuffer(GL_COLOR_ATTACHMENT1);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_NEAR(0, 0, 0, 127, 255, 255, 1);
glDeleteTextures(2, textures);
}
TEST_P(ClearTestES3, BadFBOSerialBug)
{
// First make a simple framebuffer, and clear it to green
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
GLuint textures[2];
glGenTextures(2, &textures[0]);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, getWindowWidth(), getWindowHeight());
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[0], 0);
GLenum drawBuffers[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, drawBuffers);
float clearValues1[] = { 0.0f, 1.0f, 0.0f, 1.0f };
glClearBufferfv(GL_COLOR, 0, clearValues1);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_EQ(0, 0, 0, 255, 0, 255);
// Next make a second framebuffer, and draw it to red
// (Triggers bad applied render target serial)
GLuint fbo2;
glGenFramebuffers(1, &fbo2);
ASSERT_GL_NO_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, fbo2);
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, getWindowWidth(), getWindowHeight());
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[1], 0);
glDrawBuffers(1, drawBuffers);
setupDefaultProgram();
drawQuad(mProgram, "position", 0.5f);
ASSERT_GL_NO_ERROR();
EXPECT_PIXEL_EQ(0, 0, 255, 0, 0, 255);
// Check that the first framebuffer is still green.
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
EXPECT_PIXEL_EQ(0, 0, 0, 255, 0, 255);
glDeleteTextures(2, textures);
glDeleteFramebuffers(1, &fbo2);
}
// Test that SRGB framebuffers clear to the linearized clear color
TEST_P(ClearTestES3, SRGBClear)
{
// TODO(jmadill): figure out why this fails
if (IsIntel() && GetParam() == ES3_OPENGL())
{
std::cout << "Test skipped on Intel due to failures." << std::endl;
return;
}
// First make a simple framebuffer, and clear it
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_SRGB8_ALPHA8, getWindowWidth(), getWindowHeight());
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT);
EXPECT_PIXEL_NEAR(0, 0, 188, 188, 188, 128, 1.0);
}
// Test that framebuffers with mixed SRGB/Linear attachments clear to the correct color for each
// attachment
TEST_P(ClearTestES3, MixedSRGBClear)
{
// TODO(cwallez) figure out why it is broken on Intel on Mac
#if defined(ANGLE_PLATFORM_APPLE)
if (IsIntel() && getPlatformRenderer() == EGL_PLATFORM_ANGLE_TYPE_OPENGL_ANGLE)
{
std::cout << "Test skipped on Intel on Mac." << std::endl;
return;
}
#endif
// TODO(jmadill): figure out why this fails
if (IsIntel() && GetParam() == ES3_OPENGL())
{
std::cout << "Test skipped on Intel due to failures." << std::endl;
return;
}
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
GLuint textures[2];
glGenTextures(2, &textures[0]);
glBindTexture(GL_TEXTURE_2D, textures[0]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_SRGB8_ALPHA8, getWindowWidth(), getWindowHeight());
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[0], 0);
glBindTexture(GL_TEXTURE_2D, textures[1]);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, getWindowWidth(), getWindowHeight());
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, textures[1], 0);
GLenum drawBuffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
glDrawBuffers(2, drawBuffers);
// Clear both textures
glClearColor(0.5f, 0.5f, 0.5f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, 0, 0);
// Check value of texture0
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[0], 0);
EXPECT_PIXEL_NEAR(0, 0, 188, 188, 188, 128, 1.0);
// Check value of texture1
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, textures[1], 0);
EXPECT_PIXEL_NEAR(0, 0, 128, 128, 128, 128, 1.0);
}
// This test covers a D3D11 bug where calling ClearRenderTargetView sometimes wouldn't sync
// before a draw call. The test draws small quads to a larger FBO (the default back buffer).
// Before each blit to the back buffer it clears the quad to a certain color using
// ClearBufferfv to give a solid color. The sync problem goes away if we insert a call to
// flush or finish after ClearBufferfv or each draw.
TEST_P(ClearTestES3, RepeatedClear)
{
if (IsD3D11() && IsIntel())
{
// Note that there's been a bug affecting this test on NVIDIA drivers as well, until fall
// 2016 driver releases.
std::cout << "Test skipped on Intel D3D11." << std::endl;
return;
}
const std::string &vertexSource =
"#version 300 es\n"
"in highp vec2 position;\n"
"out highp vec2 v_coord;\n"
"void main(void)\n"
"{\n"
" gl_Position = vec4(position, 0, 1);\n"
" vec2 texCoord = (position * 0.5) + 0.5;\n"
" v_coord = texCoord;\n"
"}\n";
const std::string &fragmentSource =
"#version 300 es\n"
"in highp vec2 v_coord;\n"
"out highp vec4 color;\n"
"uniform sampler2D tex;\n"
"void main()\n"
"{\n"
" color = texture(tex, v_coord);\n"
"}\n";
mProgram = CompileProgram(vertexSource, fragmentSource);
ASSERT_NE(0u, mProgram);
mTextures.resize(1, 0);
glGenTextures(1, mTextures.data());
GLenum format = GL_RGBA8;
const int numRowsCols = 3;
const int cellSize = 32;
const int fboSize = cellSize;
const int backFBOSize = cellSize * numRowsCols;
const float fmtValueMin = 0.0f;
const float fmtValueMax = 1.0f;
glBindTexture(GL_TEXTURE_2D, mTextures[0]);
glTexStorage2D(GL_TEXTURE_2D, 1, format, fboSize, fboSize);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
ASSERT_GL_NO_ERROR();
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTextures[0], 0);
ASSERT_GL_NO_ERROR();
ASSERT_GLENUM_EQ(GL_FRAMEBUFFER_COMPLETE, glCheckFramebufferStatus(GL_FRAMEBUFFER));
// larger fbo bound -- clear to transparent black
glUseProgram(mProgram);
GLint uniLoc = glGetUniformLocation(mProgram, "tex");
ASSERT_NE(-1, uniLoc);
glUniform1i(uniLoc, 0);
glBindTexture(GL_TEXTURE_2D, mTextures[0]);
GLint positionLocation = glGetAttribLocation(mProgram, "position");
ASSERT_NE(-1, positionLocation);
glUseProgram(mProgram);
for (int cellY = 0; cellY < numRowsCols; cellY++)
{
for (int cellX = 0; cellX < numRowsCols; cellX++)
{
int seed = cellX + cellY * numRowsCols;
const Vector4 color = RandomVec4(seed, fmtValueMin, fmtValueMax);
glBindFramebuffer(GL_FRAMEBUFFER, mFBOs[0]);
glClearBufferfv(GL_COLOR, 0, color.data());
glBindFramebuffer(GL_FRAMEBUFFER, 0);
// Method 1: Set viewport and draw full-viewport quad
glViewport(cellX * cellSize, cellY * cellSize, cellSize, cellSize);
drawQuad(mProgram, "position", 0.5f);
// Uncommenting the glFinish call seems to make the test pass.
// glFinish();
}
}
std::vector<GLColor> pixelData(backFBOSize * backFBOSize);
glReadPixels(0, 0, backFBOSize, backFBOSize, GL_RGBA, GL_UNSIGNED_BYTE, pixelData.data());
for (int cellY = 0; cellY < numRowsCols; cellY++)
{
for (int cellX = 0; cellX < numRowsCols; cellX++)
{
int seed = cellX + cellY * numRowsCols;
const Vector4 color = RandomVec4(seed, fmtValueMin, fmtValueMax);
GLColor expectedColor = Vec4ToColor(color);
int testN = cellX * cellSize + cellY * backFBOSize * cellSize + backFBOSize + 1;
GLColor actualColor = pixelData[testN];
EXPECT_NEAR(expectedColor.R, actualColor.R, 1);
EXPECT_NEAR(expectedColor.G, actualColor.G, 1);
EXPECT_NEAR(expectedColor.B, actualColor.B, 1);
EXPECT_NEAR(expectedColor.A, actualColor.A, 1);
}
}
ASSERT_GL_NO_ERROR();
}
// Use this to select which configurations (e.g. which renderer, which GLES major version) these tests should be run against.
ANGLE_INSTANTIATE_TEST(ClearTest,
ES2_D3D9(),
ES2_D3D11(),
ES3_D3D11(),
ES2_OPENGL(),
ES3_OPENGL(),
ES2_OPENGLES(),
ES3_OPENGLES());
ANGLE_INSTANTIATE_TEST(ClearTestES3, ES3_D3D11(), ES3_OPENGL(), ES3_OPENGLES());
} // anonymous namespace
| 31.94572 | 125 | 0.663639 | [
"render",
"vector",
"solid"
] |
13a0c130030cae2dd3a6a4eed2c95757d7ebf053 | 27,138 | cc | C++ | src/vnsw/agent/services/dhcp_handler_base.cc | zhongyangni/controller | 439032d46767dd033ba55c1e5c34e7f2213da8b3 | [
"Apache-2.0"
] | 1 | 2019-01-11T06:16:10.000Z | 2019-01-11T06:16:10.000Z | src/vnsw/agent/services/dhcp_handler_base.cc | zhongyangni/controller | 439032d46767dd033ba55c1e5c34e7f2213da8b3 | [
"Apache-2.0"
] | null | null | null | src/vnsw/agent/services/dhcp_handler_base.cc | zhongyangni/controller | 439032d46767dd033ba55c1e5c34e7f2213da8b3 | [
"Apache-2.0"
] | 1 | 2020-06-08T11:50:36.000Z | 2020-06-08T11:50:36.000Z | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include <stdint.h>
#include "vr_defs.h"
#include "cmn/agent_cmn.h"
#include "pkt/pkt_init.h"
#include "oper/vn.h"
#include "services/dhcp_proto.h"
#include "services/dhcpv6_proto.h"
#include "services/services_types.h"
#include "services/services_init.h"
#include "services/dns_proto.h"
#include "services/services_sandesh.h"
#include "bind/bind_util.h"
#include <boost/assign/list_of.hpp>
#include <bind/bind_util.h>
using namespace boost::assign;
DhcpHandlerBase::DhcpHandlerBase(Agent *agent, boost::shared_ptr<PktInfo> info,
boost::asio::io_service &io)
: ProtoHandler(agent, info, io), vm_itf_(NULL), vm_itf_index_(-1),
option_(NULL), flags_(), dns_enable_(true),
host_routes_level_(Invalid) {
ipam_type_.ipam_dns_method = "none";
}
DhcpHandlerBase::~DhcpHandlerBase() {
}
// Add option taking no data (length = 0)
uint16_t DhcpHandlerBase::AddNoDataOption(uint32_t option, uint16_t opt_len) {
option_->WriteData(option, 0, NULL, &opt_len);
return opt_len;
}
// Add option taking a byte from input
uint16_t DhcpHandlerBase::AddByteOption(uint32_t option, uint16_t opt_len,
const std::string &input) {
std::stringstream value(input);
uint32_t data = 0;
value >> data;
if (value.bad() || value.fail() || data > 0xFF) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
} else {
uint8_t byte = (uint8_t)data;
option_->WriteData(option, 1, &byte, &opt_len);
}
return opt_len;
}
// Add option taking array of bytes from input
uint16_t DhcpHandlerBase::AddByteArrayOption(uint32_t option, uint16_t opt_len,
const std::string &input) {
option_->WriteData(option, 0, NULL, &opt_len);
std::stringstream value(input);
bool done = false;
uint32_t byte = 0;
value >> byte;
while (!value.bad() && !value.fail() && byte <= 0xFF) {
option_->AppendData(1, &byte, &opt_len);
if (value.eof()) {
done = true;
break;
}
value >> byte;
}
// if atleast one byte is not added or in case of error, ignore this option
if (!option_->GetLen() || !done) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
return opt_len;
}
// Add option taking a byte followed by a string, from input
uint16_t DhcpHandlerBase::AddByteStringOption(uint32_t option, uint16_t opt_len,
const std::string &input) {
std::stringstream value(input);
uint32_t data = 0;
value >> data;
if (value.fail() || value.bad() || data > 0xFF) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len;
}
uint8_t byte = (uint8_t)data;
std::string str;
value >> str;
option_->WriteData(option, 1, &byte, &opt_len);
option_->AppendData(str.length(), str.c_str(), &opt_len);
return opt_len;
}
// Add option taking a byte followed by one or more IPs, from input
uint16_t DhcpHandlerBase::AddByteIPOption(uint32_t option, uint16_t opt_len,
const std::string &input) {
std::stringstream value(input);
uint32_t data = 0;
value >> data;
uint8_t byte = (uint8_t)data;
if (value.fail() || value.bad() || data > 0xFF) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len;
}
option_->WriteData(option, 1, &byte, &opt_len);
while (value.good()) {
std::string ipstr;
value >> ipstr;
opt_len = AddIP(opt_len, ipstr);
}
// if atleast one IP is not added, ignore this option
if (option_->GetLen() == 1) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
return opt_len;
}
// Add option taking string from input
uint16_t DhcpHandlerBase::AddStringOption(uint32_t option, uint16_t opt_len,
const std::string &input) {
option_->WriteData(option, input.length(), input.c_str(), &opt_len);
return opt_len;
}
// Add option taking integer from input
uint16_t DhcpHandlerBase::AddIntegerOption(uint32_t option, uint16_t opt_len,
const std::string &input) {
std::stringstream value(input);
uint32_t data = 0;
value >> data;
if (value.bad() || value.fail()) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
} else {
data = htonl(data);
option_->WriteData(option, 4, &data, &opt_len);
}
return opt_len;
}
// Add option taking array of short from input
uint16_t DhcpHandlerBase::AddShortArrayOption(uint32_t option, uint16_t opt_len,
const std::string &input,
bool array) {
option_->WriteData(option, 0, NULL, &opt_len);
std::stringstream value(input);
uint16_t data = 0;
value >> data;
while (!value.bad() && !value.fail()) {
data = htons(data);
option_->AppendData(2, &data, &opt_len);
if (!array || value.eof()) break;
value >> data;
}
// if atleast one short is not added, ignore this option
if (!option_->GetLen() || !value.eof()) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
return opt_len;
}
// Check for exceptions in handling IP options
bool DhcpHandlerBase::IsValidIpOption(uint32_t option, const std::string &ipstr,
bool is_v4) {
boost::system::error_code ec;
if (is_v4) {
if (option == DHCP_OPTION_DNS) {
return IsValidDnsOption(option, ipstr);
} else {
uint32_t ip = Ip4Address::from_string(ipstr, ec).to_ulong();
if(!ec.value() && !ip) {
return false;
}
}
} else {
if (option == DHCPV6_OPTION_DNS_SERVERS) {
return IsValidDnsOption(option, ipstr);
} else {
IpAddress ip = IpAddress::from_string(ipstr, ec);
if (!ec.value() && ip.is_unspecified()) {
return false;
}
}
}
return true;
}
bool DhcpHandlerBase::IsValidDnsOption(uint32_t option,
const std::string &ipstr) {
boost::system::error_code ec;
IpAddress ip = IpAddress::from_string(ipstr, ec);
if (!ec.value()) {
// when DNS server is present in DHCP option, disable vrouter
// proxying for DNS requests from VMs.
dns_enable_ = false;
if (ip.is_unspecified()) {
// Do not send the option when DNS servers have 0.0.0.0 or ::
// Set option flag so that they are not added later
set_flag(option);
return false;
}
}
return true;
}
// Add option taking number of Ipv4 addresses
uint16_t DhcpHandlerBase::AddIpv4Option(uint32_t option, uint16_t opt_len,
const std::string &input,
uint8_t min_count,
uint8_t max_count,
uint8_t multiples) {
option_->WriteData(option, 0, NULL, &opt_len);
std::stringstream value(input);
while (value.good()) {
std::string ipstr;
value >> ipstr;
if (!IsValidIpOption(option, ipstr, true)) {
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
opt_len = AddIP(opt_len, ipstr);
}
if (option == DHCP_OPTION_ROUTER) {
// Add our gw as well
if (!config_.gw_addr.is_unspecified()) {
opt_len = AddIP(opt_len, config_.gw_addr.to_string());
}
}
// check that atleast min_count IP addresses are added
if (min_count && option_->GetLen() < min_count * 4) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
// if specified, check that we dont add more than max_count IP addresses
if (max_count && option_->GetLen() > max_count * 4) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
// if specified, check that we add in multiples of IP addresses
if (multiples && option_->GetLen() % (multiples * 4)) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
return opt_len;
}
// Add option taking number of Ipv6 addresses
uint16_t DhcpHandlerBase::AddIpv6Option(uint32_t option, uint16_t opt_len,
const std::string &input, bool list) {
option_->WriteData(option, 0, NULL, &opt_len);
std::stringstream value(input);
while (value.good()) {
std::string ipstr;
value >> ipstr;
if (!IsValidIpOption(option, ipstr, false)) {
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
opt_len = AddIP(opt_len, ipstr);
if (!list) break;
}
// check that atleast one IP address is added
if (option_->GetLen() < 16) {
DHCPV6_TRACE(Error, "Invalid DHCP option " << option << " for VM " <<
config_.ip_addr.to_string() << "; data missing");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
return opt_len;
}
// Add option taking compressed name
uint16_t DhcpHandlerBase::AddCompressedNameOption(uint32_t option,
uint16_t opt_len,
const std::string &input,
bool list) {
option_->WriteData(option, 0, NULL, &opt_len);
std::stringstream value(input);
while (value.good()) {
std::string str;
value >> str;
if (str.size()) {
opt_len = AddCompressedName(opt_len, str);
if (!list) break;
}
}
if (!option_->GetLen()) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
return opt_len;
}
// Add option taking a byte followed by a compressed name
uint16_t DhcpHandlerBase::AddByteCompressedNameOption(uint32_t option,
uint16_t opt_len,
const std::string &input) {
option_->WriteData(option, 0, NULL, &opt_len);
std::stringstream value(input);
uint32_t data = 0;
value >> data;
if (value.bad() || value.fail() || data > 0xFF) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
} else {
uint8_t byte = (uint8_t)data;
option_->WriteData(option, 1, &byte, &opt_len);
}
std::string str;
value >> str;
if (value.bad() || value.fail() || !str.size()) {
DHCP_BASE_TRACE("Invalid DHCP option " << option << " data : " <<
input << "is invalid");
return opt_len - option_->GetLen() - option_->GetFixedLen();
}
return AddCompressedName(opt_len, str);
}
uint16_t DhcpHandlerBase::AddCompressedName(uint16_t opt_len,
const std::string &input) {
uint8_t name[input.size() * 2 + 2];
uint16_t len = 0;
BindUtil::AddName(name, input, 0, 0, len);
option_->AppendData(len, name, &opt_len);
return opt_len;
}
// Add an DNS server addresses from IPAM to the option
// Option code and len are added already; add only the addresses
uint16_t DhcpHandlerBase::AddDnsServers(uint16_t opt_len) {
if (ipam_type_.ipam_dns_method == "default-dns-server" ||
ipam_type_.ipam_dns_method == "virtual-dns-server" ||
ipam_type_.ipam_dns_method == "none" ||
ipam_type_.ipam_dns_method == "") {
if (!config_.dns_addr.is_unspecified()) {
opt_len = AddIP(opt_len, config_.dns_addr.to_string());
}
} else if (ipam_type_.ipam_dns_method == "tenant-dns-server") {
for (unsigned int i = 0; i < ipam_type_.ipam_dns_server.
tenant_dns_server_address.ip_address.size(); ++i) {
opt_len = AddIP(opt_len, ipam_type_.ipam_dns_server.
tenant_dns_server_address.ip_address[i]);
}
}
return opt_len;
}
// Read the list of <subnet/plen, gw> from input and store them
// for later processing in AddClasslessRouteOption
void DhcpHandlerBase::ReadClasslessRoute(uint32_t option, uint16_t opt_len,
const std::string &input) {
std::stringstream value(input);
while (value.good()) {
std::string snetstr;
value >> snetstr;
OperDhcpOptions::HostRoute host_route;
boost::system::error_code ec = Ip4PrefixParse(snetstr, &host_route.prefix_,
(int *)&host_route.plen_);
if (ec || host_route.plen_ > 32 || !value.good()) {
DHCP_BASE_TRACE("Invalid Classless route DHCP option -"
"has to be list of <subnet/plen gw>");
break;
}
value >> snetstr;
host_route.gw_ = Ip4Address::from_string(snetstr, ec);
if (ec) {
host_route.gw_ = Ip4Address();
}
host_routes_.push_back(host_route);
}
}
// Add host route options coming via config. Config priority is
// 1) options at VM interface level (host routes specifically set)
// 2) options at VM interface level (classless routes from --extra-dhcp-opts)
// 3) options at subnet level (host routes at subnet level - neutron config)
// 4) options at subnet level (classless routes from dhcp options)
// 5) options at IPAM level (host routes from IPAM)
// 6) options at IPAM level (classless routes from IPAM dhcp options)
// Add the options defined at the highest level in priority
uint16_t DhcpHandlerBase::AddClasslessRouteOption(uint16_t opt_len) {
std::vector<OperDhcpOptions::HostRoute> host_routes;
do {
// Port specific host route options
// TODO: should we remove host routes at port level from schema ?
if (vm_itf_->oper_dhcp_options().are_host_routes_set()) {
host_routes = vm_itf_->oper_dhcp_options().host_routes();
break;
}
// Host routes from port specific DHCP options (neutron configuration)
if (host_routes_level_ == InterfaceLevel && host_routes_.size()) {
host_routes.swap(host_routes_);
break;
}
if (vm_itf_->vn()) {
Ip4Address ip = config_.ip_addr.to_v4();
const std::vector<VnIpam> &vn_ipam = vm_itf_->vn()->GetVnIpam();
uint32_t index;
for (index = 0; index < vn_ipam.size(); ++index) {
if (vn_ipam[index].IsSubnetMember(ip)) {
break;
}
}
if (index < vn_ipam.size()) {
// Subnet level host route options
// Preference to host routes at subnet (neutron configuration)
if (vn_ipam[index].oper_dhcp_options.are_host_routes_set()) {
host_routes = vn_ipam[index].oper_dhcp_options.host_routes();
break;
}
// Host route options from subnet level DHCP options
if (host_routes_level_ == SubnetLevel && host_routes_.size()) {
host_routes.swap(host_routes_);
break;
}
}
// TODO: should remove host routes at VN level from schema ?
vm_itf_->vn()->GetVnHostRoutes(ipam_name_, &host_routes);
if (host_routes.size() > 0)
break;
}
// IPAM level host route options
OperDhcpOptions oper_dhcp_options;
oper_dhcp_options.update_host_routes(ipam_type_.host_routes.route);
host_routes = oper_dhcp_options.host_routes();
// Host route options from IPAM level DHCP options
if (!host_routes.size() && host_routes_.size()) {
host_routes.swap(host_routes_);
break;
}
} while (false);
if (host_routes.size()) {
option_->SetCode(DHCP_OPTION_CLASSLESS_ROUTE);
uint8_t *ptr = option_->GetData();
uint8_t len = 0;
for (uint32_t i = 0; i < host_routes.size(); ++i) {
uint32_t prefix = host_routes[i].prefix_.to_ulong();
uint32_t plen = host_routes[i].plen_;
uint32_t gw = host_routes[i].gw_.to_ulong();
*ptr++ = plen;
len++;
for (unsigned int j = 0; plen && j <= (plen - 1) / 8; ++j) {
*ptr++ = (prefix >> 8 * (3 - j)) & 0xFF;
len++;
}
// if GW is not specified, set it to subnet's GW
if (gw)
*(uint32_t *)ptr = htonl(gw);
else
*(uint32_t *)ptr = htonl(config_.gw_addr.to_v4().to_ulong());
ptr += sizeof(uint32_t);
len += sizeof(uint32_t);
}
option_->SetLen(len);
opt_len += 2 + len;
set_flag(DHCP_OPTION_CLASSLESS_ROUTE);
}
return opt_len;
}
uint16_t DhcpHandlerBase::AddDhcpOptions(
uint16_t opt_len,
std::vector<autogen::DhcpOptionType> &options,
DhcpOptionLevel level) {
for (unsigned int i = 0; i < options.size(); ++i) {
// get the option code
uint32_t option = OptionCode(options[i].dhcp_option_name);
if (!option) {
DHCP_BASE_TRACE("Invalid DHCP option " <<
options[i].dhcp_option_name);
continue;
}
// if option is already set in the response (from higher level), ignore
if (is_flag_set(option))
continue;
uint16_t old_opt_len = opt_len;
DhcpOptionCategory category = OptionCategory(option);
option_->SetNextOptionPtr(opt_len);
// if dhcp_option_value_bytes is set, use that for supported categories
std::string &opt_value = options[i].dhcp_option_value;
if (!options[i].dhcp_option_value_bytes.empty() &&
CanOverrideWithBytes(category)) {
category = ByteArray;
opt_value = options[i].dhcp_option_value_bytes;
}
switch(category) {
case None:
break;
case NoData:
opt_len = AddNoDataOption(option, opt_len);
break;
case Bool:
case Byte:
opt_len = AddByteOption(option, opt_len,
options[i].dhcp_option_value);
break;
case ByteArray:
opt_len = AddByteArrayOption(option, opt_len, opt_value);
break;
case ByteString:
opt_len = AddByteStringOption(option, opt_len,
options[i].dhcp_option_value);
break;
case ByteOneIPPlus:
opt_len = AddByteIPOption(option, opt_len,
options[i].dhcp_option_value);
break;
case String:
opt_len = AddStringOption(option, opt_len,
options[i].dhcp_option_value);
break;
case Int32bit:
case Uint32bit:
opt_len = AddIntegerOption(option, opt_len,
options[i].dhcp_option_value);
break;
case Uint16bit:
opt_len = AddShortArrayOption(option, opt_len,
options[i].dhcp_option_value,
false);
break;
case Uint16bitArray:
opt_len = AddShortArrayOption(option, opt_len,
options[i].dhcp_option_value,
true);
break;
case OneIPv4:
opt_len = AddIpv4Option(option, opt_len,
options[i].dhcp_option_value, 1, 1, 0);
break;
case ZeroIPv4Plus:
opt_len = AddIpv4Option(option, opt_len,
options[i].dhcp_option_value, 0, 0, 0);
break;
case OneIPv4Plus:
if (option == DHCP_OPTION_ROUTER) {
// Router option is added later
routers_ = options[i].dhcp_option_value;
set_flag(DHCP_OPTION_ROUTER);
} else {
opt_len = AddIpv4Option(option, opt_len,
options[i].dhcp_option_value,
1, 0, 0);
}
break;
case TwoIPv4Plus:
opt_len = AddIpv4Option(option, opt_len,
options[i].dhcp_option_value, 2, 0, 2);
break;
case OneIPv6:
opt_len = AddIpv6Option(option, opt_len,
options[i].dhcp_option_value,
false);
break;
case OneIPv6Plus:
opt_len = AddIpv6Option(option, opt_len,
options[i].dhcp_option_value,
true);
break;
case ClasslessRoute:
ReadClasslessRoute(option, opt_len,
options[i].dhcp_option_value);
if (host_routes_.size()) {
// set flag & level for classless route so that we dont
// update these at other level (subnet or ipam)
set_flag(DHCP_OPTION_CLASSLESS_ROUTE);
host_routes_level_ = level;
}
break;
case NameCompression:
opt_len = AddCompressedNameOption(option, opt_len,
options[i].dhcp_option_value,
false);
break;
case NameCompressionArray:
opt_len = AddCompressedNameOption(option, opt_len,
options[i].dhcp_option_value,
true);
break;
case ByteNameCompression:
opt_len = AddByteCompressedNameOption(option, opt_len,
options[i].dhcp_option_value);
break;
default:
DHCP_BASE_TRACE("Invalid DHCP option " <<
options[i].dhcp_option_name);
break;
}
if (opt_len != old_opt_len)
set_flag(option);
}
return opt_len;
}
// Add the option defined at the highest level in priority
// Take all options defined at VM interface level, take those from subnet which
// are not configured at interface, then take those from ipam which are not
// configured at interface or subnet.
uint16_t DhcpHandlerBase::AddConfigDhcpOptions(uint16_t opt_len, bool is_v6) {
std::vector<autogen::DhcpOptionType> options;
if (vm_itf_->GetInterfaceDhcpOptions(&options))
opt_len = AddDhcpOptions(opt_len, options, InterfaceLevel);
if (vm_itf_->GetSubnetDhcpOptions(&options, is_v6))
opt_len = AddDhcpOptions(opt_len, options, SubnetLevel);
if (vm_itf_->GetIpamDhcpOptions(&options, is_v6))
opt_len = AddDhcpOptions(opt_len, options, IpamLevel);
return opt_len;
}
void DhcpHandlerBase::FindDomainName(const IpAddress &vm_addr) {
if (config_.lease_time != (uint32_t) -1 ||
config_.valid_time != (uint32_t) -1)
return;
if (!vm_itf_->vn() ||
!vm_itf_->vn()->GetIpamData(vm_addr, &ipam_name_, &ipam_type_)) {
DHCP_BASE_TRACE("Ipam data not found");
return;
}
if (ipam_type_.ipam_dns_method != "virtual-dns-server" ||
!agent()->domain_config_table()->GetVDns(ipam_type_.ipam_dns_server.
virtual_dns_server_name,
&vdns_type_))
return;
if (config_.domain_name_.size() &&
config_.domain_name_ != vdns_type_.domain_name) {
DHCP_BASE_TRACE("Client domain " << config_.domain_name_ <<
" doesnt match with configured domain " <<
vdns_type_.domain_name);
}
std::size_t pos;
if (config_.client_name_.size() &&
((pos = config_.client_name_.find('.', 0)) != std::string::npos) &&
(config_.client_name_.substr(pos + 1) != vdns_type_.domain_name)) {
DHCP_BASE_TRACE("Client domain doesnt match with configured domain "
<< vdns_type_.domain_name << "; Client name = "
<< config_.client_name_);
config_.client_name_.replace(config_.client_name_.begin() + pos + 1,
config_.client_name_.end(),
vdns_type_.domain_name);
}
config_.domain_name_ = vdns_type_.domain_name;
}
bool DhcpHandlerBase::CanOverrideWithBytes(DhcpOptionCategory category) {
if (category == ByteArray ||
category == ByteString ||
category == String ||
category == NameCompression ||
category == NameCompressionArray ||
category == ByteNameCompression)
return true;
return false;
}
| 37.07377 | 83 | 0.543445 | [
"vector"
] |
13a1ac41806a41161c236f521025f75ec17f11fd | 6,419 | cxx | C++ | applications/rtkscatterglarecorrection/rtkscatterglarecorrection.cxx | ldqcarbon/RTK | 88df8ed953805aca3c5a73c22cb940164e7cc296 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | applications/rtkscatterglarecorrection/rtkscatterglarecorrection.cxx | ldqcarbon/RTK | 88df8ed953805aca3c5a73c22cb940164e7cc296 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | applications/rtkscatterglarecorrection/rtkscatterglarecorrection.cxx | ldqcarbon/RTK | 88df8ed953805aca3c5a73c22cb940164e7cc296 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
*
* Copyright RTK Consortium
*
* 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.txt
*
* 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 "rtkscatterglarecorrection_ggo.h"
#include "rtkMacro.h"
#include "rtkGgoFunctions.h"
#include <itkExtractImageFilter.h>
#include "rtkScatterGlareCorrectionImageFilter.h"
#include "rtkProjectionsReader.h"
#include <itkPasteImageFilter.h>
#include <rtkConstantImageSource.h>
#include <itkImageFileWriter.h>
#include <itkMultiplyImageFilter.h>
#include <vector>
#include <algorithm>
#include <string>
int main(int argc, char *argv[])
{
GGO(rtkscatterglarecorrection, args_info);
typedef float InputPixelType;
const unsigned int Dimension = 3;
typedef itk::Image< InputPixelType, Dimension > InputImageType;
typedef itk::RegularExpressionSeriesFileNames RegexpType;
RegexpType::Pointer names = RegexpType::New();
names->SetDirectory(args_info.path_arg);
names->SetNumericSort(args_info.nsort_flag);
names->SetRegularExpression(args_info.regexp_arg);
typedef rtk::ProjectionsReader< InputImageType > ReaderType; // Warning: preprocess images
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileNames( names->GetFileNames() );
reader->UpdateOutputInformation();
typedef itk::ExtractImageFilter< InputImageType, InputImageType > ExtractFilterType;
ExtractFilterType::Pointer extract = ExtractFilterType::New();
extract->InPlaceOff();
extract->SetDirectionCollapseToSubmatrix();
extract->SetInput( reader->GetOutput() );
ExtractFilterType::InputImageRegionType subsetRegion = reader->GetOutput()->GetLargestPossibleRegion();
InputImageType::SizeType extractSize = subsetRegion.GetSize();
extractSize[2] = 1;
InputImageType::IndexType start = subsetRegion.GetIndex();
extract->SetExtractionRegion(subsetRegion);
std::vector<float> coef;
if (args_info.coefficients_given == 2) {
coef.push_back(args_info.coefficients_arg[0]);
coef.push_back(args_info.coefficients_arg[1]);
}
else {
coef.push_back(0.0787f);
coef.push_back(106.244f);
}
typedef rtk::ScatterGlareCorrectionImageFilter<InputImageType, InputImageType, float> ScatterCorrectionType;
ScatterCorrectionType::Pointer SFilter = ScatterCorrectionType::New();
SFilter->SetInput(extract->GetOutput());
SFilter->SetTruncationCorrection(1.0);
SFilter->SetCoefficients(coef);
SFilter->UpdateOutputInformation();
typedef rtk::ConstantImageSource<InputImageType> ConstantImageSourceType;
ConstantImageSourceType::Pointer constantSource = ConstantImageSourceType::New();
constantSource->SetInformationFromImage(SFilter->GetOutput());
constantSource->SetSize(SFilter->GetOutput()->GetLargestPossibleRegion().GetSize());
constantSource->UpdateOutputInformation();
ConstantImageSourceType::Pointer constantSourceIn = ConstantImageSourceType::New();
constantSourceIn->SetInformationFromImage(SFilter->GetOutput());
constantSourceIn->SetSize(SFilter->GetOutput()->GetLargestPossibleRegion().GetSize());
constantSourceIn->UpdateOutputInformation();
typedef itk::PasteImageFilter <InputImageType, InputImageType > PasteImageFilterType;
PasteImageFilterType::Pointer paste = PasteImageFilterType::New();
paste->SetSourceImage(SFilter->GetOutput());
paste->SetDestinationImage(constantSource->GetOutput());
PasteImageFilterType::Pointer pasteIn = PasteImageFilterType::New();
pasteIn->SetSourceImage(extract->GetOutput());
pasteIn->SetDestinationImage(constantSourceIn->GetOutput());
int istep = 1;
unsigned int imin = 1;
unsigned int imax = (unsigned int)subsetRegion.GetSize()[2];
if (args_info.range_given)
{
if ((args_info.range_arg[0] <= args_info.range_arg[2])
&& (istep <= (args_info.range_arg[2] - args_info.range_arg[0])))
{
imin = args_info.range_arg[0];
istep = args_info.range_arg[1];
imax = std::min(unsigned(args_info.range_arg[2]), imax);
}
}
InputImageType::Pointer pimg;
InputImageType::Pointer pimgIn;
int frameoutidx = 0;
for (unsigned int frame = (imin-1); frame < imax; frame += istep, ++frameoutidx)
{
if (frame > 0) // After the first frame, use the output of paste as input
{
pimg = paste->GetOutput();
pimg->DisconnectPipeline();
paste->SetDestinationImage(pimg);
pimgIn = pasteIn->GetOutput();
pimgIn->DisconnectPipeline();
pasteIn->SetDestinationImage(pimgIn);
}
start[2] = frame;
InputImageType::RegionType desiredRegion(start, extractSize);
extract->SetExtractionRegion(desiredRegion);
SFilter->SetInput(extract->GetOutput());
SFilter->UpdateLargestPossibleRegion();
// Set extraction regions and indices
InputImageType::RegionType pasteRegion = SFilter->GetOutput()->GetLargestPossibleRegion();
pasteRegion.SetSize(Dimension - 1, 1);
pasteRegion.SetIndex(Dimension - 1, frame);
paste->SetDestinationIndex(pasteRegion.GetIndex());
paste->SetSourceRegion(SFilter->GetOutput()->GetLargestPossibleRegion());
paste->SetSourceImage(SFilter->GetOutput());
paste->UpdateLargestPossibleRegion();
pasteIn->SetDestinationIndex(pasteRegion.GetIndex());
pasteIn->SetSourceRegion(extract->GetOutput()->GetLargestPossibleRegion());
pasteIn->SetSourceImage(extract->GetOutput());
pasteIn->UpdateLargestPossibleRegion();
}
typedef itk::ImageFileWriter<InputImageType> FileWriterType;
FileWriterType::Pointer writer = FileWriterType::New();
if (args_info.output_given) {
writer->SetFileName(args_info.output_arg);
writer->SetInput(paste->GetOutput());
writer->Update();
writer->SetFileName("input.mhd");
writer->SetInput(pasteIn->GetOutput());
writer->Update();
}
return EXIT_SUCCESS;
}
| 36.890805 | 112 | 0.722698 | [
"vector"
] |
13a417e2867c2ec3d596a50ae027606f48ae4d59 | 804 | hpp | C++ | src/commands/command_dispatcher.hpp | MateuszMyalski/socket-terminal | 1eb06ee93b5063334690fbdd73ee21ec4552666e | [
"MIT"
] | null | null | null | src/commands/command_dispatcher.hpp | MateuszMyalski/socket-terminal | 1eb06ee93b5063334690fbdd73ee21ec4552666e | [
"MIT"
] | null | null | null | src/commands/command_dispatcher.hpp | MateuszMyalski/socket-terminal | 1eb06ee93b5063334690fbdd73ee21ec4552666e | [
"MIT"
] | null | null | null | #ifndef COMMANDS_COMMAND_DISPATCHER_HPP
#define COMMANDS_COMMAND_DISPATCHER_HPP
#include <map>
#include <string>
#include <vector>
#include "command.hpp"
namespace Commands {
constexpr char escape_char = '\\';
class CommandDispatcher {
private:
CommandsMap registered_cmds;
void* ctx;
public:
CommandDispatcher(void* ctx);
~CommandDispatcher() = default;
void register_command(const std::string& name,
std::shared_ptr<Command> command);
void register_multiple_command(const CommandsMap& command_map);
bool run(const std::string& querry);
void parse_querry(const std::string& querry,
std::vector<std::string>& args);
bool dispatch(const std::vector<std::string>& args);
};
}
#endif | 26.8 | 68 | 0.664179 | [
"vector"
] |
13ad158ffded54702cb434a2d2aac3d2844541ef | 273 | hpp | C++ | PlatformerGame/Bullet.hpp | Yoon-SeokJin/PlatformerGame | 3ef407df54cfb7419b27971a5738fd571df51073 | [
"MIT"
] | null | null | null | PlatformerGame/Bullet.hpp | Yoon-SeokJin/PlatformerGame | 3ef407df54cfb7419b27971a5738fd571df51073 | [
"MIT"
] | null | null | null | PlatformerGame/Bullet.hpp | Yoon-SeokJin/PlatformerGame | 3ef407df54cfb7419b27971a5738fd571df51073 | [
"MIT"
] | null | null | null | #pragma once
#include "Room.hpp"
#include "Vec2.hpp"
#include "Block.hpp"
class Bullet : public Object {
public:
Bullet(const Vec2<double>& pos, int rotate);
void step() override;
private:
int bullet_rotate;
int life = 10800;
Vec2<double> velocity;
}; | 18.2 | 48 | 0.673993 | [
"object"
] |
13ada223dbd53977961f728fc6be2e180ba2c5e6 | 4,931 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/IfcTextureMap.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | 1 | 2018-10-23T09:43:07.000Z | 2018-10-23T09:43:07.000Z | IfcPlusPlus/src/ifcpp/IFC4/IfcTextureMap.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | IfcPlusPlus/src/ifcpp/IFC4/IfcTextureMap.cpp | linsipese/ifcppstudy | e09f05d276b5e129fcb6be65800472979cd4c800 | [
"MIT"
] | null | null | null | /* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* OpenSceneGraph Public License for more details.
*/
#include <sstream>
#include <limits>
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/model/IfcPPAttributeObject.h"
#include "ifcpp/model/IfcPPGuid.h"
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/IfcPPEntityEnums.h"
#include "include/IfcFace.h"
#include "include/IfcSurfaceTexture.h"
#include "include/IfcTextureMap.h"
#include "include/IfcTextureVertex.h"
// ENTITY IfcTextureMap
IfcTextureMap::IfcTextureMap() { m_entity_enum = IFCTEXTUREMAP; }
IfcTextureMap::IfcTextureMap( int id ) { m_id = id; m_entity_enum = IFCTEXTUREMAP; }
IfcTextureMap::~IfcTextureMap() {}
shared_ptr<IfcPPObject> IfcTextureMap::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcTextureMap> copy_self( new IfcTextureMap() );
for( size_t ii=0; ii<m_Maps.size(); ++ii )
{
auto item_ii = m_Maps[ii];
if( item_ii )
{
copy_self->m_Maps.push_back( dynamic_pointer_cast<IfcSurfaceTexture>(item_ii->getDeepCopy(options) ) );
}
}
for( size_t ii=0; ii<m_Vertices.size(); ++ii )
{
auto item_ii = m_Vertices[ii];
if( item_ii )
{
copy_self->m_Vertices.push_back( dynamic_pointer_cast<IfcTextureVertex>(item_ii->getDeepCopy(options) ) );
}
}
if( m_MappedTo ) { copy_self->m_MappedTo = dynamic_pointer_cast<IfcFace>( m_MappedTo->getDeepCopy(options) ); }
return copy_self;
}
void IfcTextureMap::getStepLine( std::stringstream& stream ) const
{
stream << "#" << m_id << "= IFCTEXTUREMAP" << "(";
writeEntityList( stream, m_Maps );
stream << ",";
writeEntityList( stream, m_Vertices );
stream << ",";
if( m_MappedTo ) { stream << "#" << m_MappedTo->m_id; } else { stream << "$"; }
stream << ");";
}
void IfcTextureMap::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_id; }
void IfcTextureMap::readStepArguments( const std::vector<std::wstring>& args, const boost::unordered_map<int,shared_ptr<IfcPPEntity> >& map )
{
const int num_args = (int)args.size();
if( num_args != 3 ){ std::stringstream err; err << "Wrong parameter count for entity IfcTextureMap, expecting 3, having " << num_args << ". Entity ID: " << m_id << std::endl; throw IfcPPException( err.str().c_str() ); }
readEntityReferenceList( args[0], m_Maps, map );
readEntityReferenceList( args[1], m_Vertices, map );
readEntityReference( args[2], m_MappedTo, map );
}
void IfcTextureMap::getAttributes( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes )
{
IfcTextureCoordinate::getAttributes( vec_attributes );
if( m_Vertices.size() > 0 )
{
shared_ptr<IfcPPAttributeObjectVector> Vertices_vec_object( new IfcPPAttributeObjectVector() );
std::copy( m_Vertices.begin(), m_Vertices.end(), std::back_inserter( Vertices_vec_object->m_vec ) );
vec_attributes.push_back( std::make_pair( "Vertices", Vertices_vec_object ) );
}
vec_attributes.push_back( std::make_pair( "MappedTo", m_MappedTo ) );
}
void IfcTextureMap::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<IfcPPObject> > >& vec_attributes_inverse )
{
IfcTextureCoordinate::getAttributesInverse( vec_attributes_inverse );
}
void IfcTextureMap::setInverseCounterparts( shared_ptr<IfcPPEntity> ptr_self_entity )
{
IfcTextureCoordinate::setInverseCounterparts( ptr_self_entity );
shared_ptr<IfcTextureMap> ptr_self = dynamic_pointer_cast<IfcTextureMap>( ptr_self_entity );
if( !ptr_self ) { throw IfcPPException( "IfcTextureMap::setInverseCounterparts: type mismatch" ); }
if( m_MappedTo )
{
m_MappedTo->m_HasTextureMaps_inverse.push_back( ptr_self );
}
}
void IfcTextureMap::unlinkFromInverseCounterparts()
{
IfcTextureCoordinate::unlinkFromInverseCounterparts();
if( m_MappedTo )
{
std::vector<weak_ptr<IfcTextureMap> >& HasTextureMaps_inverse = m_MappedTo->m_HasTextureMaps_inverse;
for( auto it_HasTextureMaps_inverse = HasTextureMaps_inverse.begin(); it_HasTextureMaps_inverse != HasTextureMaps_inverse.end(); )
{
shared_ptr<IfcTextureMap> self_candidate( *it_HasTextureMaps_inverse );
if( self_candidate.get() == this )
{
it_HasTextureMaps_inverse= HasTextureMaps_inverse.erase( it_HasTextureMaps_inverse );
}
else
{
++it_HasTextureMaps_inverse;
}
}
}
}
| 42.145299 | 221 | 0.726425 | [
"vector",
"model"
] |
13adf961c03b76c38f8c6f28c8f77cdfdc8cd0b3 | 1,699 | cpp | C++ | jixun/shuxiangguan/D.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | 3 | 2017-09-17T09:12:50.000Z | 2018-04-06T01:18:17.000Z | jixun/shuxiangguan/D.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | jixun/shuxiangguan/D.cpp | swwind/code | 25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0 | [
"WTFPL"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
#define N 200020
#define fs first
#define sc second
#define mod 1000000007
using namespace std;
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
return f?x:-x;
}
int n = read();
int dep[N], fa[N];
vector <int> mp[N];
void dfs(int x, int f, int d) {
dep[x] = d; fa[x] = f;
for (auto y : mp[x])
if (y != f) dfs(y, x, d + 1);
}
pair<int, int> get_center() {
dfs(1, 0, 0);
dfs(max_element(dep + 1, dep + n + 1) - dep, 0, 0);
int ct = max_element(dep + 1, dep + n + 1) - dep;
int ht = dep[ct];
for (int i = 0; i < ht / 2; i++)
ct = fa[ct];
return make_pair(ct, (ht & 1) ? fa[ct] : ct);
}
ll hsh[N];
ll get_hash(int x, int f) {
hsh[x] = 17;
for (auto y : mp[x])
if (y != f) get_hash(y, x);
sort(mp[x].begin(), mp[x].end(), [&] (int a, int b) {
return hsh[a] < hsh[b];
});
for (auto y : mp[x]) {
if (y == f)
continue;
hsh[x] = (hsh[x] + hsh[y]) ^ (hsh[x] * hsh[y]);
hsh[x] %= mod;
}
return hsh[x] = hsh[x] * hsh[x] % mod;
}
int get_ans(int x, int f) {
int ret = mp[x].size() < 4;
int lst = -1;
for (auto y : mp[x]) {
if (y == f)
continue;
if (lst == -1 || hsh[lst] != hsh[y])
ret += get_ans(y, x);
lst = y;
}
return ret;
}
int main(int argc, char const *argv[]) {
for (int i = 1; i < n; i++) {
int x = read(), y = read();
mp[x].push_back(y);
mp[y].push_back(x);
}
auto ctr = get_center();
get_hash(ctr.fs, ctr.sc);
get_hash(ctr.sc, ctr.fs);
int res = get_ans(ctr.fs, ctr.sc) + get_ans(ctr.sc, ctr.fs);
if (hsh[ctr.fs] == hsh[ctr.sc]) res >>= 1;
printf("%d\n", res);
return 0;
}
| 23.273973 | 61 | 0.528546 | [
"vector"
] |
13ae017692cc7e892c25661c46f8d525ff895d29 | 3,520 | cpp | C++ | camera/gst-camera/gst-camera.cpp | zhangyldanny/gstCamera | 13d62d3e7304bb9bd2d70bbe80f6a31a997507b3 | [
"MIT"
] | null | null | null | camera/gst-camera/gst-camera.cpp | zhangyldanny/gstCamera | 13d62d3e7304bb9bd2d70bbe80f6a31a997507b3 | [
"MIT"
] | 1 | 2019-12-23T14:31:45.000Z | 2019-12-23T14:31:45.000Z | camera/gst-camera/gst-camera.cpp | zhangyldanny/gstCamera | 13d62d3e7304bb9bd2d70bbe80f6a31a997507b3 | [
"MIT"
] | null | null | null | /*
* inference-101
*/
#include "gstCamera.h"
#include "glDisplay.h"
#include "glTexture.h"
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include "cudaNormalize.h"
bool signal_recieved = false;
void sig_handler(int signo)
{
if( signo == SIGINT )
{
printf("received SIGINT\n");
signal_recieved = true;
}
}
int main( int argc, char** argv )
{
debug_print("gst-camera\n args (%i): ", argc);
for( int i=0; i < argc; i++ )
printf("%i [%s] ", i, argv[i]);
debug_print("\n");
if( signal(SIGINT, sig_handler) == SIG_ERR )
printf("\ncan't catch SIGINT\n");
/*
* create the camera device
*/
gstCamera* camera = gstCamera::Create();
if( !camera )
{
printf("\ngst-camera: failed to initialize video device\n");
return 0;
}
debug_print("\ngst-camera: successfully initialized video device\n");
debug_print(" width: %u\n", camera->GetWidth());
debug_print(" height: %u\n", camera->GetHeight());
debug_print(" depth: %u (bpp)\n", camera->GetPixelDepth());
/*
* create openGL window
*/
glDisplay* display = glDisplay::Create();
if( !display )
printf("\ngst-camera: failed to create openGL display\n");
const size_t texSz = camera->GetWidth() * camera->GetHeight() * sizeof(float4);
float4* texIn = (float4*)malloc(texSz);
/*if( texIn != NULL )
memset(texIn, 0, texSz);*/
if( texIn != NULL )
for( uint32_t y=0; y < camera->GetHeight(); y++ )
for( uint32_t x=0; x < camera->GetWidth(); x++ )
texIn[y*camera->GetWidth()+x] = make_float4(0.0f, 1.0f, 1.0f, 1.0f);
glTexture* texture = glTexture::Create(camera->GetWidth(), camera->GetHeight(), GL_RGBA32F_ARB/*GL_RGBA8*/, texIn);
if( !texture )
printf("gst-camera: failed to create openGL texture\n");
/*
* start streaming
*/
if( !camera->Open() )
{
printf("\ngst-camera: failed to open camera for streaming\n");
return 0;
}
debug_print("\ngst-camera: camera open for streaming\n");
while( !signal_recieved )
{
void* imgCPU = NULL;
void* imgCUDA = NULL;
// get the latest frame
if( !camera->Capture(&imgCPU, &imgCUDA, 1000) )
printf("\ngst-camera: failed to capture frame\n");
else
debug_print("gst-camera: recieved new frame CPU=0x%p GPU=0x%p\n", imgCPU, imgCUDA);
// convert from YUV to RGBA
void* imgRGBA = NULL;
if( !camera->ConvertNV12toRGBA(imgCUDA, &imgRGBA) )
printf("gst-camera: failed to convert from NV12 to RGBA\n");
// rescale image pixel intensities
CUDA(cudaNormalizeRGBA((float4*)imgRGBA, make_float2(0.0f, 255.0f),
(float4*)imgRGBA, make_float2(0.0f, 1.0f),
camera->GetWidth(), camera->GetHeight()));
// update display
if( display != NULL )
{
display->UserEvents();
display->BeginRender();
if( texture != NULL )
{
void* tex_map = texture->MapCUDA();
if( tex_map != NULL )
{
cudaMemcpy(tex_map, imgRGBA, texture->GetSize(), cudaMemcpyDeviceToDevice);
CUDA(cudaDeviceSynchronize());
texture->Unmap();
}
//texture->UploadCPU(texIn);
texture->Render(100,100);
}
display->EndRender();
}
}
debug_print("\ngst-camera: un-initializing video device\n");
/*
* shutdown the camera device
*/
if( camera != NULL )
{
delete camera;
camera = NULL;
}
if( display != NULL )
{
delete display;
display = NULL;
}
debug_print("gst-camera: video device has been un-initialized.\n");
debug_print("gst-camera: this concludes the test of the video device.\n");
return 0;
}
| 21.204819 | 116 | 0.63125 | [
"render"
] |
13b7cc25d57e1870a4d3756e68fd4647854586e1 | 1,637 | cpp | C++ | ext/opencollada/fw_meshvertexdata.cpp | Kerilk/opencollada-ruby | 539d136dbd456b337822c9ad5173c52c79806071 | [
"BSD-2-Clause"
] | 1 | 2020-03-08T11:11:25.000Z | 2020-03-08T11:11:25.000Z | ext/opencollada/fw_meshvertexdata.cpp | Kerilk/opencollada-ruby | 539d136dbd456b337822c9ad5173c52c79806071 | [
"BSD-2-Clause"
] | null | null | null | ext/opencollada/fw_meshvertexdata.cpp | Kerilk/opencollada-ruby | 539d136dbd456b337822c9ad5173c52c79806071 | [
"BSD-2-Clause"
] | null | null | null | #include "rice/Data_Type.hpp"
#include "rice/Constructor.hpp"
#include <COLLADAFWMeshVertexData.h>
#include "fw_meshvertexdata.hpp"
#include "fw_floatordouble.hpp"
#include "fw_arrayprimitivetype.hpp"
#include "fw.hpp"
using namespace Rice;
Data_Type<COLLADAFW::MeshVertexData> rb_cCFWMeshVertexData;
template<>
Object to_ruby<COLLADAFW::MeshVertexData>(COLLADAFW::MeshVertexData const & x)
{
return to_ruby(&x);
}
void rb_define_CFWMeshVertexData()
{
rb_cCFWMeshVertexData = rb_cCFW.define_class<COLLADAFW::MeshVertexData, COLLADAFW::FloatOrDoubleArray>("MeshVertexData");
rb_cCFWMeshVertexData.define_constructor(Constructor<COLLADAFW::MeshVertexData, COLLADAFW::FloatOrDoubleArray::DataType>(), (Arg("type") = COLLADAFW::FloatOrDoubleArray::DataType::DATA_TYPE_UNKNOWN));
Data_Type<COLLADAFW::MeshVertexData::InputInfos> rb_cCFWMVDInputInfos;
rb_cCFWMVDInputInfos = rb_cCFWMeshVertexData.define_class<COLLADAFW::MeshVertexData::InputInfos>("InputInfos");
rb_cCFWMVDInputInfos.define_constructor(Constructor<COLLADAFW::MeshVertexData::InputInfos>());
Data_Type<COLLADAFW::ArrayPrimitiveType<COLLADAFW::MeshVertexData::InputInfos>> rb_cCFWMVDInputInfosArray;
rb_createCFWArrayPrimitiveTypeClass<COLLADAFW::MeshVertexData::InputInfos>(rb_cCFWMVDInputInfosArray);
rb_cCFWMeshVertexData.define_method("num_inputs_info", &COLLADAFW::MeshVertexData::getNumInputInfos);
rb_cCFWMeshVertexData.define_method("name", &COLLADAFW::MeshVertexData::getName);
rb_cCFWMeshVertexData.define_method("stride", &COLLADAFW::MeshVertexData::getStride);
rb_cCFWMeshVertexData.define_method("length", &COLLADAFW::MeshVertexData::getLength);
}
| 49.606061 | 201 | 0.83201 | [
"object"
] |
13bd6ee2472f9317df95f7cdacf0eb5c5678275b | 1,245 | cpp | C++ | src/fieldplotter/window.test.cpp | jkotrc/Field-Plotter | df38a791cb7d783efa055f24585b387f75cabea6 | [
"MIT"
] | 3 | 2020-10-02T10:49:12.000Z | 2020-10-12T23:18:08.000Z | src/fieldplotter/window.test.cpp | jkotrc/Field-Plotter | df38a791cb7d783efa055f24585b387f75cabea6 | [
"MIT"
] | null | null | null | src/fieldplotter/window.test.cpp | jkotrc/Field-Plotter | df38a791cb7d783efa055f24585b387f75cabea6 | [
"MIT"
] | 1 | 2020-10-12T05:32:51.000Z | 2020-10-12T05:32:51.000Z | #include "window.h"
#include "graphics/renderer.h"
#include <gtest/gtest.h>
#include <iostream>
using namespace fieldplotter;
TEST(WindowTest, CreatesSuccessfully) {
Window win;
ASSERT_NO_THROW(win.show());
}
TEST(WindowTest, DimensionsAreCorrect) {
Window win(800, 600);
ASSERT_EQ(win.getWidth(), 800);
ASSERT_EQ(win.getHeight(), 600);
}
TEST(WindowTest, WindowCloses) {
Window win;
win.close();
ASSERT_TRUE(win.isClosed());
}
//TODO Version setting does not work so far
// TEST(WindowTest, OpenGLVersionSet) {
// Window::WindowOptions winopt;
// winopt.openGLVersion.first = 2;
// winopt.openGLVersion.second = 6;
// Window win(winopt, 800, 600);
// OpenGLContext ctx = win.getContext();
// ASSERT_EQ(ctx.getVersion().first, 2);
// ASSERT_EQ(ctx.getVersion().second, 6);
// }
// TODO Worry about profiles later
// TEST(WindowTest, OpenGLProfileSet) {
// Window::WindowOptions winopt;
// winopt.openGLProfile = Window::CORE_PROFILE;
// Window win(winopt, 800, 600);
// OpenGLContext ctx = win.getContext();
// ASSERT_E
// }
TEST(WindowTest, ValidRenderingSurface) {
Window win;
Renderer ren(win.getContext());
ren.render();
win.update();
}
| 23.942308 | 51 | 0.668273 | [
"render"
] |
13c2b1bbdf1c98c196dd1b9c184106273200ef44 | 4,194 | cpp | C++ | Utility/RazorEditArea.cpp | jeremybernstein/sws | 7d311a839e0b845ca0edb3b9220af4896b35ff6f | [
"MIT"
] | 285 | 2016-10-16T00:35:58.000Z | 2022-03-25T04:46:58.000Z | Utility/RazorEditArea.cpp | jeremybernstein/sws | 7d311a839e0b845ca0edb3b9220af4896b35ff6f | [
"MIT"
] | 754 | 2016-09-23T20:32:01.000Z | 2022-03-31T10:30:07.000Z | Utility/RazorEditArea.cpp | jeremybernstein/sws | 7d311a839e0b845ca0edb3b9220af4896b35ff6f | [
"MIT"
] | 77 | 2017-01-16T16:55:03.000Z | 2022-03-10T08:58:21.000Z | /******************************************************************************
/ RazorEditArea.cpp
/
/ Copyright (c) 2021 ReaTeam
/
/ 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 "stdafx.h"
#include "RazorEditArea.hpp"
razor::RazorEditArea::RazorEditArea() :
m_track(nullptr),
m_areaStart(-1.0),
m_areaEnd(-1.0),
m_envelopeGUID("")
{
}
std::vector<razor::RazorEditArea> razor::RazorEditArea::GetRazorEditAreas()
{
std::vector<razor::RazorEditArea> razorEditAreas;
if (atof(GetAppVersion()) < 6.24) // Razor edit area API was added in v6.24
return razorEditAreas;
char* razorEditAreasStr;
for (int i = 1; i <= GetNumTracks(); i++)
{
// API returns space-separated triples of start time, end time, and envelope GUID string
razorEditAreasStr = reinterpret_cast<char*> (GetSetMediaTrackInfo(CSurf_TrackFromID(i, false), "P_RAZOREDITS", nullptr));
if (razorEditAreasStr && razorEditAreasStr[0])
{
RazorEditArea rea;
// parse razorEditAreasStr
char* token = strtok(razorEditAreasStr, " "); // start time
while (token != nullptr)
{
rea.m_track = (CSurf_TrackFromID(i, false));
rea.m_areaStart = (atof(token));
token = strtok(nullptr, " "); // end time
rea.m_areaEnd = (atof(token));
token = strtok(nullptr, " "); // envelope GUID string
if (token[1] == '{')
rea.m_envelopeGUID = token;
else
rea.m_envelopeGUID = "";
razorEditAreas.push_back(rea);
token = strtok(nullptr, " "); // next triple
}
}
}
return razorEditAreas;
}
std::vector<MediaItem*> razor::RazorEditArea::GetMediaItemsCrossingRazorEditAreas(bool includeEnclosedItems)
{
std::vector<MediaItem*> itemsCrossingRazorEditAreas;
std::vector<razor::RazorEditArea> reas = razor::RazorEditArea::GetRazorEditAreas();
for (size_t i = 0; i < reas.size(); i++)
{
if (reas[i].m_envelopeGUID == "") // only check razor edit areas which aren't envelopes
{
MediaTrack* track = reas[i].m_track;
int itemCount = CountTrackMediaItems(track);
for (int j = 0; j < itemCount; j++)
{
MediaItem* item = GetTrackMediaItem(track, j);
double itemPos = GetMediaItemInfo_Value(item, "D_POSITION");
double itemEnd = itemPos + GetMediaItemInfo_Value(item, "D_LENGTH");
// check if item is in razor edit area bounds
if (includeEnclosedItems == false && reas[i].m_areaStart <= itemPos && reas[i].m_areaEnd >= itemEnd)// rea encloses item
continue;
if ((itemEnd > reas[i].m_areaStart && itemEnd <= reas[i].m_areaEnd) // item end within rea
|| (itemPos >= reas[i].m_areaStart && itemPos < reas[i].m_areaEnd) // item start within rea
|| (itemPos <= reas[i].m_areaStart && itemEnd >= reas[i].m_areaEnd)) // item encloses rae
itemsCrossingRazorEditAreas.push_back(item);
}
}
}
return itemsCrossingRazorEditAreas;
}
MediaTrack* razor::RazorEditArea::GetMediaTrack()
{
return m_track;
}
double razor::RazorEditArea::GetAreaStart()
{
return m_areaStart;
}
double razor::RazorEditArea::GetAreaEnd()
{
return m_areaEnd;
}
std::string razor::RazorEditArea::GetEnvelopeGUID()
{
return m_envelopeGUID;
}
| 33.285714 | 124 | 0.686695 | [
"vector"
] |
13c505e34e821c4d706021e8a6f0b6b1c84b5c87 | 8,152 | cpp | C++ | source/Utility/DataEncoder.cpp | xiaobai/swift-lldb | 9238527ce430e6837108a16d2a91b147551fb83c | [
"Apache-2.0"
] | 765 | 2015-12-03T16:44:59.000Z | 2022-03-07T12:41:10.000Z | source/Utility/DataEncoder.cpp | xiaobai/swift-lldb | 9238527ce430e6837108a16d2a91b147551fb83c | [
"Apache-2.0"
] | 1,815 | 2015-12-11T23:56:05.000Z | 2020-01-10T19:28:43.000Z | source/Utility/DataEncoder.cpp | xiaobai/swift-lldb | 9238527ce430e6837108a16d2a91b147551fb83c | [
"Apache-2.0"
] | 284 | 2015-12-03T16:47:25.000Z | 2022-03-12T05:39:48.000Z | //===-- DataEncoder.cpp -----------------------------------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "lldb/Utility/DataEncoder.h"
#include "lldb/Utility/DataBuffer.h"
#include "lldb/Utility/Endian.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include <cassert>
#include <cstddef>
#include <string.h>
using namespace lldb;
using namespace lldb_private;
using namespace llvm::support::endian;
// Default constructor.
DataEncoder::DataEncoder()
: m_start(nullptr), m_end(nullptr),
m_byte_order(endian::InlHostByteOrder()), m_addr_size(sizeof(void *)),
m_data_sp() {}
// This constructor allows us to use data that is owned by someone else. The
// data must stay around as long as this object is valid.
DataEncoder::DataEncoder(void *data, uint32_t length, ByteOrder endian,
uint8_t addr_size)
: m_start(static_cast<uint8_t *>(data)),
m_end(static_cast<uint8_t *>(data) + length), m_byte_order(endian),
m_addr_size(addr_size), m_data_sp() {}
// Make a shared pointer reference to the shared data in "data_sp" and set the
// endian swapping setting to "swap", and the address size to "addr_size". The
// shared data reference will ensure the data lives as long as any DataEncoder
// objects exist that have a reference to this data.
DataEncoder::DataEncoder(const DataBufferSP &data_sp, ByteOrder endian,
uint8_t addr_size)
: m_start(nullptr), m_end(nullptr), m_byte_order(endian),
m_addr_size(addr_size), m_data_sp() {
SetData(data_sp);
}
DataEncoder::~DataEncoder() = default;
// Clears the object contents back to a default invalid state, and release any
// references to shared data that this object may contain.
void DataEncoder::Clear() {
m_start = nullptr;
m_end = nullptr;
m_byte_order = endian::InlHostByteOrder();
m_addr_size = sizeof(void *);
m_data_sp.reset();
}
// If this object contains shared data, this function returns the offset into
// that shared data. Else zero is returned.
size_t DataEncoder::GetSharedDataOffset() const {
if (m_start != nullptr) {
const DataBuffer *data = m_data_sp.get();
if (data != nullptr) {
const uint8_t *data_bytes = data->GetBytes();
if (data_bytes != nullptr) {
assert(m_start >= data_bytes);
return m_start - data_bytes;
}
}
}
return 0;
}
// Set the data with which this object will extract from to data starting at
// BYTES and set the length of the data to LENGTH bytes long. The data is
// externally owned must be around at least as long as this object points to
// the data. No copy of the data is made, this object just refers to this data
// and can extract from it. If this object refers to any shared data upon
// entry, the reference to that data will be released. Is SWAP is set to true,
// any data extracted will be endian swapped.
uint32_t DataEncoder::SetData(void *bytes, uint32_t length, ByteOrder endian) {
m_byte_order = endian;
m_data_sp.reset();
if (bytes == nullptr || length == 0) {
m_start = nullptr;
m_end = nullptr;
} else {
m_start = static_cast<uint8_t *>(bytes);
m_end = m_start + length;
}
return GetByteSize();
}
// Assign the data for this object to be a subrange of the shared data in
// "data_sp" starting "data_offset" bytes into "data_sp" and ending
// "data_length" bytes later. If "data_offset" is not a valid offset into
// "data_sp", then this object will contain no bytes. If "data_offset" is
// within "data_sp" yet "data_length" is too large, the length will be capped
// at the number of bytes remaining in "data_sp". A ref counted pointer to the
// data in "data_sp" will be made in this object IF the number of bytes this
// object refers to in greater than zero (if at least one byte was available
// starting at "data_offset") to ensure the data stays around as long as it is
// needed. The address size and endian swap settings will remain unchanged from
// their current settings.
uint32_t DataEncoder::SetData(const DataBufferSP &data_sp, uint32_t data_offset,
uint32_t data_length) {
m_start = m_end = nullptr;
if (data_length > 0) {
m_data_sp = data_sp;
if (data_sp) {
const size_t data_size = data_sp->GetByteSize();
if (data_offset < data_size) {
m_start = data_sp->GetBytes() + data_offset;
const size_t bytes_left = data_size - data_offset;
// Cap the length of we asked for too many
if (data_length <= bytes_left)
m_end = m_start + data_length; // We got all the bytes we wanted
else
m_end = m_start + bytes_left; // Not all the bytes requested were
// available in the shared data
}
}
}
uint32_t new_size = GetByteSize();
// Don't hold a shared pointer to the data buffer if we don't share any valid
// bytes in the shared buffer.
if (new_size == 0)
m_data_sp.reset();
return new_size;
}
// Extract a single unsigned char from the binary data and update the offset
// pointed to by "offset_ptr".
//
// RETURNS the byte that was extracted, or zero on failure.
uint32_t DataEncoder::PutU8(uint32_t offset, uint8_t value) {
if (ValidOffset(offset)) {
m_start[offset] = value;
return offset + 1;
}
return UINT32_MAX;
}
uint32_t DataEncoder::PutU16(uint32_t offset, uint16_t value) {
if (ValidOffsetForDataOfSize(offset, sizeof(value))) {
if (m_byte_order != endian::InlHostByteOrder())
write16be(m_start + offset, value);
else
write16le(m_start + offset, value);
return offset + sizeof(value);
}
return UINT32_MAX;
}
uint32_t DataEncoder::PutU32(uint32_t offset, uint32_t value) {
if (ValidOffsetForDataOfSize(offset, sizeof(value))) {
if (m_byte_order != endian::InlHostByteOrder())
write32be(m_start + offset, value);
else
write32le(m_start + offset, value);
return offset + sizeof(value);
}
return UINT32_MAX;
}
uint32_t DataEncoder::PutU64(uint32_t offset, uint64_t value) {
if (ValidOffsetForDataOfSize(offset, sizeof(value))) {
if (m_byte_order != endian::InlHostByteOrder())
write64be(m_start + offset, value);
else
write64le(m_start + offset, value);
return offset + sizeof(value);
}
return UINT32_MAX;
}
// Extract a single integer value from the data and update the offset pointed
// to by "offset_ptr". The size of the extracted integer is specified by the
// "byte_size" argument. "byte_size" should have a value >= 1 and <= 8 since
// the return value is only 64 bits wide. Any "byte_size" values less than 1 or
// greater than 8 will result in nothing being extracted, and zero being
// returned.
//
// RETURNS the integer value that was extracted, or zero on failure.
uint32_t DataEncoder::PutMaxU64(uint32_t offset, uint32_t byte_size,
uint64_t value) {
switch (byte_size) {
case 1:
return PutU8(offset, value);
case 2:
return PutU16(offset, value);
case 4:
return PutU32(offset, value);
case 8:
return PutU64(offset, value);
default:
llvm_unreachable("GetMax64 unhandled case!");
}
return UINT32_MAX;
}
uint32_t DataEncoder::PutData(uint32_t offset, const void *src,
uint32_t src_len) {
if (src == nullptr || src_len == 0)
return offset;
if (ValidOffsetForDataOfSize(offset, src_len)) {
memcpy(m_start + offset, src, src_len);
return offset + src_len;
}
return UINT32_MAX;
}
uint32_t DataEncoder::PutAddress(uint32_t offset, lldb::addr_t addr) {
return PutMaxU64(offset, GetAddressByteSize(), addr);
}
uint32_t DataEncoder::PutCString(uint32_t offset, const char *cstr) {
if (cstr != nullptr)
return PutData(offset, cstr, strlen(cstr) + 1);
return UINT32_MAX;
}
| 34.542373 | 80 | 0.681428 | [
"object"
] |
13cc87fbb900b28dc718cc944fc4393712d4fd36 | 6,406 | cpp | C++ | backtracking/subset_sum.cpp | imprettyboiimstunnin/C-Plus-Plus | e9d052cdf1a3f1b12568276d9fc1b21c05f3283d | [
"MIT"
] | null | null | null | backtracking/subset_sum.cpp | imprettyboiimstunnin/C-Plus-Plus | e9d052cdf1a3f1b12568276d9fc1b21c05f3283d | [
"MIT"
] | null | null | null | backtracking/subset_sum.cpp | imprettyboiimstunnin/C-Plus-Plus | e9d052cdf1a3f1b12568276d9fc1b21c05f3283d | [
"MIT"
] | null | null | null | /**
* @file
* @brief Implementation of the [Subset
* Sum](https://en.wikipedia.org/wiki/Subset_sum_problem) problem.
* @details
* We are given an array and a sum value. The algorithm finds all
* the subsets of that array with sum equal to the given sum and return such
* subsets count. This approach will have exponential time complexity.
* @author [Swastika Gupta](https://github.com/Swastyy)
*
* Second Method added : This method used dynamic programming to
* reduce the time complexity of solution from exponential ,i.e, O(n*2^n) to O(n*sum_of_elements)
* dp[{i,j}] defines the number of possible subsets with sum 'j' , by considering only the first 'i' elements
* of the array
*
*/
#include <cassert> /// for assert
#include <iostream> /// for IO operations
#include <vector> /// for std::vector
#include <map> /// for std::map
/**
* @namespace backtracking
* @brief Backtracking algorithms
*/
namespace backtracking {
/**
* @namespace Subsets
* @brief Functions for the [Subset
* Sum](https://en.wikipedia.org/wiki/Subset_sum_problem) problem.
*/
namespace subset_sum {
/**
* @brief The main function implements count of subsets
* @param sum is the required sum of any subset
* @param in_arr is the input array
* @returns count of the number of subsets with required sum
*/
//1st Method
uint64_t number_of_subsets(int32_t sum, const std::vector<int32_t> &in_arr) {
int32_t nelement = in_arr.size();
uint64_t count_of_subset = 0;
for (int32_t i = 0; i < (1 << (nelement)); i++) {
int32_t check = 0;
for (int32_t j = 0; j < nelement; j++) {
if (i & (1 << j)) {
check += (in_arr[j]);
}
}
if (check == sum) {
count_of_subset++;
}
}
return count_of_subset;
}
//2nd Method
uint64_t number_of_subsets2(int32_t sum, const std::vector<int32_t> &in_arr) {
int32_t nelement = in_arr.size();
int32_t sum_of_elements = 0 ;
int32_t minimum = 0 ;
for (int32_t i = 0; i < nelement ; i++) {
if(in_arr[i]<0){
minimum += in_arr[i];
}
else{
sum_of_elements += in_arr[i];
}
}
std::map<std::pair<int32_t,int32_t>,uint64_t> dp ;
dp[{-1,0}]=1;
for(int32_t i = 0 ; i < nelement ; i++){
for(int32_t j = minimum; j <= sum_of_elements ;j++) {
dp[{i,j}] = dp[{i-1,j-in_arr[i]}] + dp[{i-1,j}] ;
}
}
return dp[{nelement-1,sum}];
}
} // namespace subset_sum
} // namespace backtracking
/**
* @brief Test implementations
* @returns void
*/
static void test() {
// Test 1
// 1st Method
std::cout << "1st test 1st Method ";
std::vector<int32_t> array1 = {-7, -3, -2, 5, 8}; // input array
assert(backtracking::subset_sum::number_of_subsets(0, array1) ==
2); // first argument in subset_sum function is the required sum and
// second is the input array
std::cout << "passed" << std::endl;
// Test 1
// 2nd Method
// input array = same as used in 1st test above.
std::cout << "1st test 2nd Method ";
assert(backtracking::subset_sum::number_of_subsets2(0, array1) ==
2); // first argument in subset_sum function is the required sum and
// second is the input array
std::cout << "passed" << std::endl;
// Test 2
// 1st Method
std::cout << "2nd test 1st Method ";
std::vector<int32_t> array2 = {1, 2, 3, 3};
assert(backtracking::subset_sum::number_of_subsets(6, array2) ==
3); // here we are expecting 3 subsets which sum up to 6 i.e.
// {(1,2,3),(1,2,3),(3,3)}
std::cout << "passed" << std::endl;
// Test 2
// 2nd Method
// input array = same as used in 2nd test above.
std::cout << "2nd test 2nd Method ";
assert(backtracking::subset_sum::number_of_subsets2(6, array2) ==
3); // here we are expecting 3 subsets which sum up to 6 i.e.
// {(1,2,3),(1,2,3),(3,3)}
std::cout << "passed" << std::endl;
// Test 3
// 1st Method
std::cout << "3rd test 1st Method ";
std::vector<int32_t> array3 = {1, 1, 1, 1};
assert(backtracking::subset_sum::number_of_subsets(1, array3) ==
4); // here we are expecting 4 subsets which sum up to 1 i.e.
// {(1),(1),(1),(1)}
std::cout << "passed" << std::endl;
// Test 3
// 2nd Method
// input array = same as used in 3rd test above.
std::cout << "3rd test 2nd Method ";
assert(backtracking::subset_sum::number_of_subsets2(1, array3) ==
4); // here we are expecting 4 subsets which sum up to 1 i.e.
// {(1),(1),(1),(1)}
std::cout << "passed" << std::endl;
// Test 4
// 1st Method
std::cout << "4th test 1st Method ";
std::vector<int32_t> array4 = {3, 3, 3, 3};
assert(backtracking::subset_sum::number_of_subsets(6, array4) ==
6); // here we are expecting 6 subsets which sum up to 6 i.e.
// {(3,3),(3,3),(3,3),(3,3),(3,3),(3,3)}
std::cout << "passed" << std::endl;
// Test 4
// 2nd Method
// input array = same as used in 4th test above.
std::cout << "4th test 2nd Method ";
assert(backtracking::subset_sum::number_of_subsets2(6, array4) ==
6); // here we are expecting 6 subsets which sum up to 6 i.e.
// {(3,3),(3,3),(3,3),(3,3),(3,3),(3,3)}
std::cout << "passed" << std::endl;
// Test 5
// 1st Method
std::cout << "5th test 1st Method ";
std::vector<int32_t> array5 = {};
assert(backtracking::subset_sum::number_of_subsets(6, array5) ==
0); // here we are expecting 0 subsets which sum up to 6 i.e. we
// cannot select anything from an empty array
std::cout << "passed" << std::endl;
// Test 5
// 2nd Method
// input array = same as used in 5th test above.
std::cout << "5th test 2nd Method ";
assert(backtracking::subset_sum::number_of_subsets2(6, array5) ==
0); // here we are expecting 0 subsets which sum up to 6 i.e. we
// cannot select anything from an empty array
std::cout << "passed" << std::endl;
}
/**
* @brief Main function
* @returns 0 on exit
*/
int main() {
test(); // run self-test implementations
return 0;
}
| 31.712871 | 109 | 0.577896 | [
"vector"
] |
13ddf5c69902bb7db36132aa0ed409297f4e2b20 | 19,556 | cpp | C++ | src/main.cpp | sgholap/CarND-Path-Planning-Project | bc4a58d92d441611357ff7a2a388d5082b472b84 | [
"MIT"
] | null | null | null | src/main.cpp | sgholap/CarND-Path-Planning-Project | bc4a58d92d441611357ff7a2a388d5082b472b84 | [
"MIT"
] | null | null | null | src/main.cpp | sgholap/CarND-Path-Planning-Project | bc4a58d92d441611357ff7a2a388d5082b472b84 | [
"MIT"
] | null | null | null | #include <uWS/uWS.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "helpers.h"
#include "json.hpp"
#include "Spline.h"
// for convenience
using nlohmann::json;
using std::string;
using std::vector;
// Enum for lanes
enum LANE_NUMBER {
LANE0,
LANE1,
LANE2,
INVALID_LANE
};
// Enum for states
enum STATE {
KEEP_LANE,
CHANGE_LEFT,
CHANGE_RIGHT,
PREPARE_CHANGE_LEFT,
PREPARE_CHANGE_RIGHT
};
// Paramters to tune
const double target_max_speed = 49.5;
const double target_max_acceleration = 0.223;
const double target_max_dist_for_lane_change_look = 60;
const double target_min_turn_front_dist = 20;
const double target_min_turn_back_dist = 15;
const double target_min_deaccer_front_dist = 30;
const double target_critical_front_dist = 2;
// Global Variable
STATE prev_state = KEEP_LANE;
LANE_NUMBER intendedLaneChange = INVALID_LANE;
// Get the lane number based on d
LANE_NUMBER getLaneNumber(double d) {
if (d >= 0 && d <= 4)
{
return LANE0;
}
else if (d >= 4 && d <= 8)
{
return LANE1;
}
else if (d >= 8 && d <= 12)
{
return LANE2;
}
else
{
return INVALID_LANE;
std::cout << "++++++ Invalid lane ++++++" << std::endl;
}
}
// Find the closes vechicle in front or back.
// parameters are current vechicle s and d, future Distance, sensor fustion data, front or back.
vector<double> closestVehicle(double ref_s, double ref_d, int lane, double futureDistance, vector < vector<double>> sensor_fusion, bool isFront)
{
double speed = target_max_speed;
double distance = std::numeric_limits<double>::max();
double d_l = std::numeric_limits<double>::max();
for (int vehicle = 0; vehicle < sensor_fusion.size(); vehicle++)
{
float d = sensor_fusion[vehicle][6];
double vx = sensor_fusion[vehicle][3];
double vy = sensor_fusion[vehicle][4];
double other_car_s = sensor_fusion[vehicle][5];
double other_car_speed = sqrt(vx*vx + vy * vy);
other_car_s += futureDistance * 0.02 * other_car_speed;
if (getLaneNumber(d) != INVALID_LANE && getLaneNumber(d) == lane)
{
if (isFront)
{
// Find closest in front;
if (other_car_s >= ref_s) {
if (distance > other_car_s - ref_s) {
distance = other_car_s - ref_s;
speed = other_car_speed;
d_l = std::abs(ref_d - d);
}
}
}
else
{
// Find closest in back
if (ref_s > other_car_s) {
if (distance > ref_s - other_car_s)
{
distance = ref_s - other_car_s;
speed = other_car_speed;
d_l = std::abs(ref_d - d);
}
}
}
}
}
std::cout << "Close vehicle " << (isFront ? "Front: " : "Back: ") << lane << " " << distance << " " << speed << " " << d_l << std::endl;
return { distance, speed, d_l};
}
// Check if state can be keep lane.
bool checkKeepLane(const vector<vector<vector<double>>> parameters,const int bestLane, const int curLane)
{
// Check if see any car in our lane.
// We can compare by lane number,
// But we may miss if front car is in changing lane and it may collide.
bool keeplane = false;
for (int t = 0; t < 3; t++)
{
if (parameters[t][0][0] < target_min_turn_front_dist &&
parameters[t][0][2] < 2.5)
{
keeplane = true;
break;
}
}
// Change lane only if require.
// keep in lane if:
// we don't want to change lane as enough distance is available
// or we are close to target,
// or we are already in best lane.
// or if we have best lane at two lane distance but car in adjacent lane is very close.
if (parameters[curLane][0][0] > target_max_dist_for_lane_change_look ||
keeplane ||
bestLane == curLane ||
(abs(bestLane - curLane) > 1 && (parameters[1][0][0] < target_min_turn_front_dist)))
{
return true;
}
return false;
}
// Action if state need to be in keep lane.
// return target speed and distance.
void actionKeepLane(const vector<vector<vector<double>>> ¶meters, STATE &newstate,const int &curLane, double &target_speed, double &front_distance, int &target_lane)
{
bool keeplane = false;
double speed = target_max_speed;
double distance = 1000; // Big number
// Check if see any car in our lane.
// We can compare by lane number,
// But we may miss if front car is in changing lane and it may collide.
for (int t = 0; t < 3; t++)
{
if (parameters[t][0][0] < target_min_deaccer_front_dist &&
parameters[t][0][2] < 2)
{
keeplane = true;
speed = parameters[t][0][1];
distance = parameters[t][0][0];
break;
}
}
// Check if same lane;
newstate = KEEP_LANE;
if (keeplane)
{
// If car is near the threshold for min dist, set speed = front car speed.
target_speed = speed;
front_distance = distance;
}
else {
target_speed = target_max_speed;
front_distance = 1000;
}
target_lane = curLane;
intendedLaneChange = INVALID_LANE;
std::cout << "Keep in same Lane " << std::endl;
}
// Action to preapare lane.
void actionPrepareLane(const vector<vector<vector<double>>> ¶meters, STATE &newstate, const int &curLane, const int &bestLane, double &target_speed, double &front_distance, int &target_lane)
{
// Better lane available. We can prepare.
int newLaneDir;
if (bestLane > curLane)
{
newstate = PREPARE_CHANGE_RIGHT;
newLaneDir = 1;
}
else
{
newstate = PREPARE_CHANGE_LEFT;
newLaneDir = -1;
}
if (parameters[curLane + newLaneDir][0][0] < target_min_deaccer_front_dist)
{
// if front car is close set the speed equal to front car.
target_speed = parameters[curLane + newLaneDir][0][1];
}
else
{
// Else send max speed
target_speed = target_max_speed;
}
front_distance = parameters[curLane][0][0];
target_lane = curLane;
std::cout << "Prepare for next lane to " << (newstate == PREPARE_CHANGE_LEFT ? "LEFT" : "RIGHT") << std::endl;
}
// Check if we can change the lane.
bool canLaneChange(const vector<vector<vector<double>>> parameters, const int bestLane, const int curLane, const vector<double> costLane, const double speed)
{
int newLaneDir;
if (prev_state == CHANGE_RIGHT || prev_state == PREPARE_CHANGE_RIGHT)
{
newLaneDir = 1;
}
else if (prev_state == CHANGE_LEFT || prev_state == PREPARE_CHANGE_LEFT)
{
newLaneDir = -1;
}
// Change the lane if:
// We are yet to finish previous lane change (intended lane != curLane), and
// If front car is far away or front car speed is greater our car speed, and
// if back car is far away or back car speed is less than or car speed.
if (intendedLaneChange != curLane &&
costLane[bestLane] < costLane[curLane] - 0.2 &&
((parameters[curLane + newLaneDir][0][0] > target_min_turn_front_dist) ||
(parameters[curLane + newLaneDir][0][0] > target_min_turn_front_dist / 2 &&
speed < parameters[curLane + newLaneDir][0][1])) &&
((parameters[curLane + newLaneDir][1][0] > target_min_turn_back_dist) ||
(parameters[curLane + newLaneDir][1][0] > target_min_turn_back_dist / 2 &&
speed > parameters[curLane + newLaneDir][1][1]))
)
{
return true;
}
return false;
}
// Change the Lane
void actionLaneChange(const vector<vector<vector<double>>> ¶meters, STATE &newstate, const int &curLane, const int &bestLane, double &target_speed, double &front_distance, int &target_lane)
{
int newLaneDir;
if (prev_state == PREPARE_CHANGE_RIGHT || prev_state == CHANGE_RIGHT)
{
newstate = CHANGE_RIGHT;
newLaneDir = 1;
}
else
{
newLaneDir = -1;
newstate = CHANGE_LEFT;
}
// Set the target speed to max if car is far otherwise set to car in front.
if (parameters[curLane + newLaneDir][0][0] < target_min_deaccer_front_dist)
{
target_speed = parameters[curLane + newLaneDir][0][1];
front_distance = parameters[curLane + newLaneDir][0][0];
}
else {
target_speed = target_max_speed;
front_distance = 1000;
}
target_lane = curLane + newLaneDir;
intendedLaneChange = (LANE_NUMBER)target_lane;
std::cout << "Change the lane to " << (newstate == CHANGE_LEFT ? "LEFT" : "RIGHT") << std::endl;
}
// Plan the next behavior or speed and lane.
// State transition from one state to other, and action of lane change and speed.
vector<double> behaviorPlanning(double ref_s, double ref_d, int curLane, double current_speed, double futureDistance, vector < vector<double>> sensor_fusion)
{
double target_speed = target_max_speed;
double front_distance = 1000;
int target_lane = curLane;
// Calculate cost of each lane. This help us to select best lane with least cost.
// Cost will find for closest vehicles in front and less from our car.
// Set cost to zero if no vehicle ahead or back.
vector<double> costLane = { 0, 0, 0 };
vector<vector<vector<double>>> parameters;
for (int lane = 0; lane < 3; lane++)
{
vector<double> closeFront = closestVehicle(ref_s, ref_d, lane, futureDistance, sensor_fusion, true);
vector<double> closeBack = closestVehicle(ref_s, ref_d, lane, futureDistance, sensor_fusion, false);
parameters.push_back({ closeFront, closeBack });
costLane[lane] += ((target_max_speed - closeFront[1]) / target_max_speed);
costLane[lane] += (1 - exp(-(target_min_deaccer_front_dist / closeFront[0])));
}
std::cout << costLane[0] << " " << costLane[1] << " " << costLane[2] << std::endl;
// State transition.
STATE state = KEEP_LANE;
// Find best lane based on cost, however, it may not feasible to change due to invalid states or other cars too close to it.
int bestLane = std::min_element(costLane.begin(), costLane.end()) - costLane.begin();
// If previously car was in keep lane state.
if (prev_state == KEEP_LANE) {
// Change lane only if require.
if (checkKeepLane(parameters, bestLane, curLane))
{
// Get best parameters.
actionKeepLane(parameters, state, curLane, target_speed, front_distance, target_lane);
}
else
{
// Better lane available. Let's prepare by setting target lane.
actionPrepareLane(parameters, state, curLane, bestLane, target_speed, front_distance, target_lane);
}
}
// If we were in prepare state.
else if (prev_state == PREPARE_CHANGE_LEFT || prev_state == PREPARE_CHANGE_RIGHT)
{
// If we don't want to change the lane now, as we are too close or far from front car.
// or, we are best lane now.
if (checkKeepLane(parameters, bestLane, curLane))
{
actionKeepLane(parameters, state, curLane, target_speed, front_distance, target_lane);
}
// Check if we can change the lane now.
else if (canLaneChange(parameters, bestLane, curLane, costLane, current_speed))
{
actionLaneChange(parameters, state, curLane, bestLane, target_speed, front_distance, target_lane);
}
else
{
// Wait in prepare state. // Match the target speed in adjacent lane.
actionPrepareLane(parameters, state, curLane, bestLane, target_speed, front_distance, target_lane);
}
}
// if we are changing the lane.
else {
// Continue to check if we have finsihed the lane change.
if (canLaneChange(parameters, bestLane, curLane, costLane, current_speed))
{
actionLaneChange(parameters, state, curLane, bestLane, target_speed, front_distance, target_lane);
}
else
{
// Change state to keep lane once lane change is finish.
actionKeepLane(parameters, state, curLane, target_speed, front_distance, target_lane);
}
}
prev_state = state;
std::cout << "State: " << prev_state << " -> " << state << std::endl;
std::cout << "Target Lane " << target_lane << " target speed" << target_speed << " front_distance " << front_distance << std::endl;
return { (double)target_lane, target_speed, front_distance};
}
int main() {
uWS::Hub h;
// Load up map values for waypoint's x,y,s and d normalized normal vectors
vector<double> map_waypoints_x;
vector<double> map_waypoints_y;
vector<double> map_waypoints_s;
vector<double> map_waypoints_dx;
vector<double> map_waypoints_dy;
// Waypoint map to read from
string map_file_ = "../data/highway_map.csv";
// The max s value before wrapping around the track back to 0
double max_s = 6945.554;
std::ifstream in_map_(map_file_.c_str(), std::ifstream::in);
string line;
while (getline(in_map_, line)) {
std::istringstream iss(line);
double x;
double y;
float s;
float d_x;
float d_y;
iss >> x;
iss >> y;
iss >> s;
iss >> d_x;
iss >> d_y;
map_waypoints_x.push_back(x);
map_waypoints_y.push_back(y);
map_waypoints_s.push_back(s);
map_waypoints_dx.push_back(d_x);
map_waypoints_dy.push_back(d_y);
}
double ref_v = 0.0;
h.onMessage([&map_waypoints_x,&map_waypoints_y,&map_waypoints_s,
&map_waypoints_dx,&map_waypoints_dy, &ref_v]
(uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length,
uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2') {
auto s = hasData(data);
if (s != "") {
auto j = json::parse(s);
string event = j[0].get<string>();
if (event == "telemetry") {
// j[1] is the data JSON object
// Main car's localization Data
double car_x = j[1]["x"];
double car_y = j[1]["y"];
double car_s = j[1]["s"];
double car_d = j[1]["d"];
double car_yaw = j[1]["yaw"];
double car_speed = j[1]["speed"];
// Previous path data given to the Planner
auto previous_path_x = j[1]["previous_path_x"];
auto previous_path_y = j[1]["previous_path_y"];
// Previous path's end s and d values
double end_path_s = j[1]["end_path_s"];
double end_path_d = j[1]["end_path_d"];
// Sensor Fusion Data, a list of all other cars on the same side
// of the road.
auto sensor_fusion = j[1]["sensor_fusion"];
json msgJson;
double prev_size = previous_path_x.size();
vector<double> next_x_vals;
vector<double> next_y_vals;
// Project code start here
// Sensor Fusion to avoid collision.
if (prev_size > 0)
{
car_s = end_path_s;
//car_d = end_path_d;
}
// GEt the best lane and target speed.
int lane = getLaneNumber(car_d);
if (lane == INVALID_LANE) lane = 1;
vector<double> behaviorResult = behaviorPlanning(car_s, car_d, lane, ref_v, prev_size, sensor_fusion);
lane = (int)behaviorResult[0];
// Set the velocity based on target speed and acceleration.
// TODO: Try to smooth it in future by varying accleration.
if (ref_v < behaviorResult[1])
{
ref_v += target_max_acceleration;
}
else if (ref_v > behaviorResult[1])
{
ref_v -= target_max_acceleration;
}
if (ref_v > target_max_speed) ref_v = target_max_speed;
if (ref_v < 0.5 || behaviorResult[2] < target_critical_front_dist) ref_v = 0.5;
std::cout << "Current Lane: " << lane << " speed: " << ref_v<<std::endl;
std::cout<< "**********************************" << std::endl;
/* Generate trajectories */
vector<double> ptsx;
vector<double> ptsy;
double ref_x = car_x;
double ref_y = car_y;
double ref_yaw = deg2rad(car_yaw);
if (prev_size < 2)
{
// we don't have enough previous point. Use current car position and make path tangent to car;
double prev_car_x = car_x - cos (car_yaw);
double prev_car_y = car_y - sin (car_yaw);
ptsx.push_back(prev_car_x);
ptsy.push_back(prev_car_y);
ptsx.push_back(car_x);
ptsy.push_back(car_y);
}
else
{
// We have previous path. Take couple of points from previous path. This help in smooth trajectories and avoid jerk.
// Update reference point as well.
ref_x = previous_path_x[prev_size-1];
ref_y = previous_path_y[prev_size-1];
double ref_x_prev = previous_path_x[prev_size-2];
double ref_y_prev = previous_path_y[prev_size-2];
ref_yaw = atan2(ref_y-ref_y_prev, ref_x - ref_x_prev);
ptsx.push_back(ref_x_prev);
ptsy.push_back(ref_y_prev);
ptsx.push_back(ref_x);
ptsy.push_back(ref_y);
}
// Get the waypoint at 30, 60 and 90 mt. This are dest points.
vector<double> wp1 = getXY(car_s+30, (2+lane * 4), map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector<double> wp2 = getXY(car_s+60, (2+lane * 4), map_waypoints_s, map_waypoints_x, map_waypoints_y);
vector<double> wp3 = getXY(car_s+90, (2+lane * 4), map_waypoints_s, map_waypoints_x, map_waypoints_y);
ptsx.push_back(wp1[0]);
ptsy.push_back(wp1[1]);
ptsx.push_back(wp2[0]);
ptsy.push_back(wp2[1]);
ptsx.push_back(wp3[0]);
ptsy.push_back(wp3[1]);
// Transfer to car coordinate
for (int i =0; i < ptsx.size(); i++)
{
double shift_x = ptsx[i] - ref_x;
double shift_y = ptsy[i] - ref_y;
ptsx[i] = shift_x * cos(-ref_yaw) - shift_y * sin(-ref_yaw);
ptsy[i] = shift_x * sin(-ref_yaw) + shift_y * cos(-ref_yaw);
}
tk::spline s;
// set the set of anchor points in spine
s.set_points(ptsx, ptsy);
// Add previous left over point. This avoid sudden jerk due to previous and next trajectories.
for (int i=0; i < previous_path_x.size(); i++)
{
next_x_vals.push_back(previous_path_x[i]);
next_y_vals.push_back(previous_path_y[i]);
}
// Find remaining new points.
double target_x = 30;
double target_y = s(target_x);
double target_dist = sqrt(target_x*target_x + target_y*target_y);
double x_acc = 0.0;
for (int i=0; i < (50-previous_path_x.size()); i++)
{
// Calculate points along new path
double N = (target_dist/(.02*ref_v/2.24));
double x_point = x_acc+(target_x)/N;
double y_point = s(x_point);
x_acc = x_point;
double x_temp = x_point;
double y_temp = y_point;
// Rotate and shift back to normal
x_point = (x_temp*cos(ref_yaw)-y_temp*sin(ref_yaw));
y_point = (x_temp*sin(ref_yaw)+y_temp*cos(ref_yaw));
x_point += ref_x;
y_point += ref_y;
next_x_vals.push_back(x_point);
next_y_vals.push_back(y_point);
}
// Project code end here
msgJson["next_x"] = next_x_vals;
msgJson["next_y"] = next_y_vals;
auto msg = "42[\"control\","+ msgJson.dump()+"]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
} // end "telemetry" if
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
} // end websocket if
}); // end h.onMessage
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code,
char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port)) {
std::cout << "Listening to port " << port << std::endl;
} else {
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
} | 32.006547 | 196 | 0.644815 | [
"object",
"vector"
] |
13dfc975d673ff621abd0d39ed3767367ff3d570 | 14,830 | cpp | C++ | src/ConstraintSolver/AngleLine2D.cpp | peizhan/psketcher | d84be7c64b101e3ec5fdec416a21c4a4674f535d | [
"BSD-2-Clause"
] | 1 | 2022-03-01T09:03:40.000Z | 2022-03-01T09:03:40.000Z | src/ConstraintSolver/AngleLine2D.cpp | peizhan/psketcher | d84be7c64b101e3ec5fdec416a21c4a4674f535d | [
"BSD-2-Clause"
] | null | null | null | src/ConstraintSolver/AngleLine2D.cpp | peizhan/psketcher | d84be7c64b101e3ec5fdec416a21c4a4674f535d | [
"BSD-2-Clause"
] | 1 | 2022-03-01T09:03:42.000Z | 2022-03-01T09:03:42.000Z | /*
Copyright (c) 2006-2014, Michael Greminger
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF A
DVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sstream>
#include "AngleLine2D.h"
#include "IndependentDOF.h"
#include "pSketcherModel.h"
using namespace std;
// Create an angle constraint between two lines
AngleLine2D::AngleLine2D(const Line2DPointer line1, const Line2DPointer line2, double angle /* radians */, bool interior_angle):
line1_(line1),
line2_(line2),
interior_angle_(interior_angle),
text_angle_(new IndependentDOF(0.0,false)),
text_radius_(new IndependentDOF(0.0,false)),
text_s_(new IndependentDOF(0.0,false)),
text_t_(new IndependentDOF(0.0,false))
{
// store the primitives that this primitive depends on
AddPrimitive(line1);
AddPrimitive(line2);
AddDOF(line1_->GetS1());
AddDOF(line1_->GetS2());
AddDOF(line1_->GetT1());
AddDOF(line1_->GetT2());
AddDOF(line2_->GetS1());
AddDOF(line2_->GetS2());
AddDOF(line2_->GetT1());
AddDOF(line2_->GetT2());
AddDOF(text_angle_);
AddDOF(text_radius_);
AddDOF(text_s_);
AddDOF(text_t_);
SetDefaultTextLocation();
// Create a DOF for the angle parameter
DOFPointer new_dof(new IndependentDOF(angle,false));
angle_ = new_dof;
AddDOF(angle_);
// define the constraint equation
if(interior_angle_)
{
solver_function_.reset(new angle_line_2d_interior(line1_->GetS1(),line1_->GetT1(),line1_->GetS2(),line1_->GetT2(),line2_->GetS1(),line2_->GetT1(),line2_->GetS2(),line2_->GetT2(),angle_));
} else {
solver_function_.reset(new angle_line_2d_exterior(line1_->GetS1(),line1_->GetT1(),line1_->GetS2(),line1_->GetT2(),line2_->GetS1(),line2_->GetT1(),line2_->GetS2(),line2_->GetT2(),angle_));
}
weight_ = 1.0;
}
// Construct from database
AngleLine2D::AngleLine2D(unsigned id, pSketcherModel &psketcher_model)
{
SetID(id); bool exists = SyncToDatabase(psketcher_model);
if(!exists) // this object does not exist in the table
{
stringstream error_description;
error_description << "SQLite rowid " << id << " in table " << SQL_angle_line2d_database_table_name << " does not exist";
throw pSketcherException(error_description.str());
}
}
void AngleLine2D::SetDefaultTextLocation()
{
// first determine the intersection point of the two lines
double x1 = line1_->GetPoint1()->GetSValue();
double x2 = line1_->GetPoint2()->GetSValue();
double x3 = line2_->GetPoint1()->GetSValue();
double x4 = line2_->GetPoint2()->GetSValue();
double y1 = line1_->GetPoint1()->GetTValue();
double y2 = line1_->GetPoint2()->GetTValue();
double y3 = line2_->GetPoint1()->GetTValue();
double y4 = line2_->GetPoint2()->GetTValue();
double denominator = (x1-x2)*(y3-y4)-(x3-x4)*(y1-y2);
if(denominator == 0.0)
{
// so use the length of the lines to set a reasonable radius and set angle to 0.0
text_radius_->SetValue(0.25*(sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) + sqrt((x3-x4)*(x3-x4)+(y3-y4)*(y3-y4))));
text_angle_->SetValue(0.0);
// use the following parameters to locate the text instead
text_s_->SetValue(0.25*(x1+x2+x3+x4));
text_t_->SetValue(0.25*(y1+y2+y3+y4));
} else {
// lines do intersect
// finish calculating the intersection point
double temp1 = x1*y2-y1*x2;
double temp2 = x3*y4-x4*y3;
double x_center = (temp1*(x3-x4)-temp2*(x1-x2))/denominator;
double y_center = (temp1*(y3-y4)-temp2*(y1-y2))/denominator;
// calculate the average radius and the average angle of all of the line endpoints
double ave_radius = 0.0;
double ave_angle = 0.0;
ave_radius += sqrt((x1-x_center)*(x1-x_center)+(y1-y_center)*(y1-y_center));
ave_radius += sqrt((x2-x_center)*(x2-x_center)+(y2-y_center)*(y2-y_center));
ave_radius += sqrt((x3-x_center)*(x3-x_center)+(y3-y_center)*(y3-y_center));
ave_radius += sqrt((x4-x_center)*(x4-x_center)+(y4-y_center)*(y4-y_center));
ave_radius = ave_radius/4.0;
int angle_counter = 0;
if((y1-y_center)*(y1-y_center)+(x1-x_center)*(x1-x_center) > 0)
{
ave_angle += atan2(y1-y_center,x1-x_center) + 2.0*mmcPI;
angle_counter++;
}
if((y2-y_center)*(y2-y_center)+(x2-x_center)*(x2-x_center) > 0)
{
ave_angle += atan2(y2-y_center,x2-x_center) + 2.0*mmcPI;
angle_counter++;
}
if((y3-y_center)*(y3-y_center)+(x3-x_center)*(x3-x_center) > 0)
{
ave_angle += atan2(y3-y_center,x3-x_center) + 2.0*mmcPI;
angle_counter++;
}
if((y4-y_center)*(y4-y_center)+(x4-x_center)*(x4-x_center) > 0)
{
ave_angle += atan2(y4-y_center,x4-x_center) + 2.0*mmcPI;
angle_counter++;
}
if(angle_counter > 0)
ave_angle = ave_angle / (double)angle_counter;
else
ave_angle = 0.0;
text_radius_->SetValue(ave_radius*0.75);
text_angle_->SetValue(ave_angle);
}
}
void AngleLine2D::SetSTTextLocation(double text_s, double text_t, bool update_db)
{
// first determine the intersection point of the two lines
double x1 = line1_->GetPoint1()->GetSValue();
double x2 = line1_->GetPoint2()->GetSValue();
double x3 = line2_->GetPoint1()->GetSValue();
double x4 = line2_->GetPoint2()->GetSValue();
double y1 = line1_->GetPoint1()->GetTValue();
double y2 = line1_->GetPoint2()->GetTValue();
double y3 = line2_->GetPoint1()->GetTValue();
double y4 = line2_->GetPoint2()->GetTValue();
double denominator = (x1-x2)*(y3-y4)-(x3-x4)*(y1-y2);
if(denominator == 0.0)
{
// the lines are parallel
// use the following parameters to locate the text instead of text_radius_ and text_angle_
text_s_->SetValue(text_s, update_db);
text_t_->SetValue(text_t, update_db);
} else {
// lines do intersect
// finish calculating the intersection point
double temp1 = x1*y2-y1*x2;
double temp2 = x3*y4-x4*y3;
double x_center = (temp1*(x3-x4)-temp2*(x1-x2))/denominator;
double y_center = (temp1*(y3-y4)-temp2*(y1-y2))/denominator;
text_radius_->SetValue(sqrt((x_center - text_s)*(x_center - text_s) + (y_center - text_t)*(y_center - text_t)), update_db);
text_angle_->SetValue(atan2(text_t-y_center, text_s-x_center), update_db);
}
}
double AngleLine2D::GetActualAngle() const
{
double line1_ds = line1_->GetS2()->GetValue() - line1_->GetS1()->GetValue();
double line1_dt = line1_->GetT2()->GetValue() - line1_->GetT1()->GetValue();
double line1_length = sqrt(line1_ds*line1_ds+line1_dt*line1_dt);
double line2_ds = line2_->GetS2()->GetValue() - line2_->GetS1()->GetValue();
double line2_dt = line2_->GetT2()->GetValue() - line2_->GetT1()->GetValue();
double line2_length = sqrt(line2_ds*line2_ds+line2_dt*line2_dt);
double actual_angle;
if(interior_angle_)
actual_angle = acos((1/(line1_length*line2_length))*(line1_ds*line2_ds + line1_dt*line2_dt));
else
actual_angle = mmcPI - acos((1/(line1_length*line2_length))*(line1_ds*line2_ds + line1_dt*line2_dt));
return actual_angle;
}
void AngleLine2D::AddToDatabase(sqlite3 *database)
{
database_ = database;
DatabaseAddRemove(true);
}
void AngleLine2D::RemoveFromDatabase()
{
DatabaseAddRemove(false);
}
void AngleLine2D::DatabaseAddRemove(bool add_to_database) // Utility method used by AddToDatabase and RemoveFromDatabase
{
string sql_do, sql_undo;
stringstream dof_list_table_name;
dof_list_table_name << "dof_table_" << GetID();
stringstream primitive_list_table_name;
primitive_list_table_name << "primitive_table_" << GetID();
stringstream constraint_list_table_name;
// First, create the sql statements to undo and redo this operation
stringstream temp_stream;
temp_stream.precision(__DBL_DIG__);
temp_stream << "BEGIN; "
<< "INSERT INTO " << SQL_angle_line2d_database_table_name << " VALUES("
<< GetID() << ",'" << dof_list_table_name.str() << "','"
<< primitive_list_table_name.str()
<< "'," << line1_->GetID() << "," << line2_->GetID()
<< "," << angle_->GetID() << "," << interior_angle_
<< "," << text_angle_->GetID() << "," << text_radius_->GetID()
<< "," << text_s_->GetID() << "," << text_t_->GetID()
<< "," << weight_
<< "); "
<< "INSERT INTO constraint_equation_list VALUES("
<< GetID() << ",'" << SQL_angle_line2d_database_table_name << "'); "
<< "COMMIT; ";
if(add_to_database)
sql_do = temp_stream.str();
else
sql_undo = temp_stream.str();
temp_stream.str(""); // clears the string stream
temp_stream << "BEGIN; "
<< "DELETE FROM constraint_equation_list WHERE id=" << GetID()
<< "; DELETE FROM " << SQL_angle_line2d_database_table_name << " WHERE id=" << GetID()
<< "; COMMIT;";
if(add_to_database)
sql_undo = temp_stream.str();
else
sql_do = temp_stream.str();
// add this object to the appropriate tables by executing the SQL command sql_insert
char *zErrMsg = 0;
int rc = sqlite3_exec(database_, sql_do.c_str(), 0, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
if(add_to_database)
{
//std::cerr << "SQL error: " << zErrMsg << endl;
sqlite3_free(zErrMsg);
// the table "independent_dof_list" may not exist, attempt to create
rc = sqlite3_exec(database_, ("ROLLBACK;"+SQL_angle_line2d_database_schema).c_str(), 0, 0, &zErrMsg); // need to add ROLLBACK since previous transaction failed
if( rc!=SQLITE_OK ){
std::string error_description = "SQL error: " + std::string(zErrMsg);
sqlite3_free(zErrMsg);
throw pSketcherException(error_description);
}
// now that the table has been created, attempt the insert one last time
rc = sqlite3_exec(database_, sql_do.c_str(), 0, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
std::string error_description = "SQL error: " + std::string(zErrMsg);
sqlite3_free(zErrMsg);
throw pSketcherException(error_description);
}
} else {
std::string error_description = "SQL error: " + std::string(zErrMsg);
sqlite3_free(zErrMsg);
throw pSketcherException(error_description);
}
}
// finally, update the undo_redo_list in the database with the database changes that have just been made
// need to use sqlite3_mprintf to make sure the single quotes in the sql statements get escaped where needed
char *sql_undo_redo = sqlite3_mprintf("INSERT INTO undo_redo_list(undo,redo) VALUES('%q','%q')",sql_undo.c_str(),sql_do.c_str());
rc = sqlite3_exec(database_, sql_undo_redo, 0, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
std::string error_description = "SQL error: " + std::string(zErrMsg);
sqlite3_free(zErrMsg);
throw pSketcherException(error_description);
}
sqlite3_free(sql_undo_redo);
// Now use the methods provided by PrimitiveBase and ConstraintEquationBase to create the tables listing the DOF's, the other Primitives that this primitive depends on, and the constraint equations
DatabaseAddDeleteLists(add_to_database,dof_list_table_name.str(),primitive_list_table_name.str());
}
bool AngleLine2D::SyncToDatabase(pSketcherModel &psketcher_model)
{
database_ = psketcher_model.GetDatabase();
string table_name = SQL_angle_line2d_database_table_name;
char *zErrMsg = 0;
int rc;
sqlite3_stmt *statement;
stringstream sql_command;
sql_command << "SELECT * FROM " << table_name << " WHERE id=" << GetID() << ";";
rc = sqlite3_prepare(psketcher_model.GetDatabase(), sql_command.str().c_str(), -1, &statement, 0);
if( rc!=SQLITE_OK ){
stringstream error_description;
error_description << "SQL error: " << sqlite3_errmsg(psketcher_model.GetDatabase());
throw pSketcherException(error_description.str());
}
rc = sqlite3_step(statement);
stringstream dof_table_name, primitive_table_name;
if(rc == SQLITE_ROW) {
// row exists, store the values to initialize this object
dof_table_name << sqlite3_column_text(statement,1);
primitive_table_name << sqlite3_column_text(statement,2);
line1_ = psketcher_model.FetchPrimitive<Line2D>(sqlite3_column_int(statement,3));
line2_ = psketcher_model.FetchPrimitive<Line2D>(sqlite3_column_int(statement,4));
angle_ = psketcher_model.FetchDOF(sqlite3_column_int(statement,5));
interior_angle_ = sqlite3_column_int(statement,6);
text_angle_ = psketcher_model.FetchDOF(sqlite3_column_int(statement,7));
text_radius_ = psketcher_model.FetchDOF(sqlite3_column_int(statement,8));
text_s_ = psketcher_model.FetchDOF(sqlite3_column_int(statement,9));
text_t_ = psketcher_model.FetchDOF(sqlite3_column_int(statement,10));
weight_ = sqlite3_column_double(statement,11);
if(interior_angle_)
{
solver_function_.reset(new angle_line_2d_interior(line1_->GetS1(),line1_->GetT1(),line1_->GetS2(),line1_->GetT2(),line2_->GetS1(),line2_->GetT1(),line2_->GetS2(),line2_->GetT2(),angle_));
} else {
solver_function_.reset(new angle_line_2d_exterior(line1_->GetS1(),line1_->GetT1(),line1_->GetS2(),line1_->GetT2(),line2_->GetS1(),line2_->GetT1(),line2_->GetS2(),line2_->GetT2(),angle_));
}
} else {
// the requested row does not exist in the database
sqlite3_finalize(statement);
return false; // row does not exist in the database, exit method and return false
}
rc = sqlite3_step(statement);
if( rc!=SQLITE_DONE ){
// sql statement didn't finish properly, some error must to have occured
stringstream error_description;
error_description << "SQL error: " << sqlite3_errmsg(psketcher_model.GetDatabase());
throw pSketcherException(error_description.str());
}
rc = sqlite3_finalize(statement);
if( rc!=SQLITE_OK ){
stringstream error_description;
error_description << "SQL error: " << sqlite3_errmsg(psketcher_model.GetDatabase());
throw pSketcherException(error_description.str());
}
// now sync the lists store in the base classes
SyncListsToDatabase(dof_table_name.str(),primitive_table_name.str(),psketcher_model); // PrimitiveBase
return true; // row existed in the database
}
| 36.982544 | 200 | 0.715509 | [
"object"
] |
13e7a9024d0e949ba407c64331541161072cb5a4 | 406 | cpp | C++ | Tests/Vector_tests.cpp | Scapior/KompotEngine | 9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc | [
"MIT"
] | null | null | null | Tests/Vector_tests.cpp | Scapior/KompotEngine | 9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc | [
"MIT"
] | 36 | 2020-10-14T15:17:46.000Z | 2022-02-07T22:10:54.000Z | Tests/Vector_tests.cpp | Scapior/KompotEngine | 9de8c7c6a1158198a18aa237e6a2dbe41ffb44cc | [
"MIT"
] | 1 | 2019-05-12T16:59:50.000Z | 2019-05-12T16:59:50.000Z | /*
* Vector_tests.cpp
* Copyright (C) 2021 by Maxim Stoianov
* Licensed under the MIT license.
*/
#include <iostream>
#include <Math/Vector.hpp>
#include <gtest/gtest.h>
TEST(Vector2D, foo)
{
Math::Vector2D v;
v.x = 5;
v.y = 3;
EXPECT_FLOAT_EQ(v.foo(), 8.0f);
}
TEST(Vector, foo)
{
Math::Vector v;
v.x = 5;
v.y = 3;
v.z = 1;
EXPECT_FLOAT_EQ(v.foo(), 9.0f);
}
| 14.5 | 40 | 0.576355 | [
"vector"
] |
13f1ba782dea1de0967b2b032b7ca26a22e7b245 | 1,746 | cc | C++ | polardbx/src/model/RetryPolarxOrderRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | polardbx/src/model/RetryPolarxOrderRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | polardbx/src/model/RetryPolarxOrderRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/polardbx/model/RetryPolarxOrderRequest.h>
using AlibabaCloud::Polardbx::Model::RetryPolarxOrderRequest;
RetryPolarxOrderRequest::RetryPolarxOrderRequest() :
RpcServiceRequest("polardbx", "2020-02-02", "RetryPolarxOrder")
{
setMethod(HttpRequest::Method::Post);
}
RetryPolarxOrderRequest::~RetryPolarxOrderRequest()
{}
std::string RetryPolarxOrderRequest::getDBInstanceName()const
{
return dBInstanceName_;
}
void RetryPolarxOrderRequest::setDBInstanceName(const std::string& dBInstanceName)
{
dBInstanceName_ = dBInstanceName;
setParameter("DBInstanceName", dBInstanceName);
}
std::string RetryPolarxOrderRequest::getRegionId()const
{
return regionId_;
}
void RetryPolarxOrderRequest::setRegionId(const std::string& regionId)
{
regionId_ = regionId;
setParameter("RegionId", regionId);
}
std::string RetryPolarxOrderRequest::getScaleOutToken()const
{
return scaleOutToken_;
}
void RetryPolarxOrderRequest::setScaleOutToken(const std::string& scaleOutToken)
{
scaleOutToken_ = scaleOutToken;
setParameter("ScaleOutToken", scaleOutToken);
}
| 27.714286 | 83 | 0.764032 | [
"model"
] |
13fe9cf9af394e045340b20e1d88a902a0fcae44 | 2,723 | cpp | C++ | GRIT/unit_tests/grit_test_data/grit_test_data.cpp | H2020-MSCA-ITN-rainbow/GRIT | 1bdfb0735515e9d462214f66b88a71aabf836d76 | [
"MIT"
] | 4 | 2018-05-28T19:59:05.000Z | 2021-04-23T19:57:26.000Z | GRIT/unit_tests/grit_test_data/grit_test_data.cpp | H2020-MSCA-ITN-rainbow/GRIT | 1bdfb0735515e9d462214f66b88a71aabf836d76 | [
"MIT"
] | 18 | 2018-05-06T21:08:19.000Z | 2018-06-11T17:59:00.000Z | GRIT/unit_tests/grit_test_data/grit_test_data.cpp | misztal/GRIT | 6850fec967c9de7c6c501f5067d021ef5288b88e | [
"MIT"
] | null | null | null | #include <grit.h>
#include <glue.h> // needed for svg_draw
#include <util.h> // needed for util::get_data_file_path
#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
inline void test_data(std::string const & txt_filename)
{
grit::engine2d_type engine;
grit::param_type parameters;
std::string const full_filename = util::get_data_file_path(txt_filename);
BOOST_CHECK_NO_THROW( grit::init_engine_with_mesh_file(full_filename,parameters,engine) );
{
std::string const svg_filename = full_filename + ".svg";
std::vector<unsigned int> labels;
grit::compute_phase_labels(engine.mesh(), labels);
for(unsigned int i=0u; i< labels.size();++i)
{
parameters.add_label(labels[i]);
}
glue::svg_draw(svg_filename, engine, parameters);
}
}
BOOST_AUTO_TEST_SUITE(grit);
BOOST_AUTO_TEST_CASE(test_mesh_data_files)
{
test_data( "circle.txt" ); // has an ear
test_data( "crescent.txt" ); // has an ear
test_data( "filled.txt" ); // has an ear
test_data( "filled2.txt" ); // has an ear
test_data( "filled3.txt" ); // has an ear
test_data( "hollow_circle.txt" ); // has an ear
test_data( "JeppeSandbox.txt" ); // has an ear
test_data( "rectangle.txt" ); // has an ear
test_data( "rectangle_refined.txt" ); // has an ear
test_data( "simple_rectangle.txt" ); // has an ear, has triangles with negative orientation
test_data( "smaller_circle.txt" ); // has an ear
test_data( "small_circle.txt" ); // has an ear
test_data( "small_circles.txt" ); // has an ear
test_data( "small_circle_larger_domain.txt" ); // has an ear
test_data( "small_magnets.txt" ); // has an ear
test_data( "small_rectangle.txt" ); // has an ear
test_data( "small_rectangles.txt" ); // has an ear
test_data( "unit_coarse.txt" ); // has an ear
test_data( "circle_enright.txt" );
test_data( "horseshoe.txt" );
test_data( "magnet.txt" );
test_data( "refined_circle.txt" );
test_data( "unit_test.txt" );
test_data( "zalesak.txt" );
test_data( "two_rectangles.txt" );
test_data( "breast.msh" ); // has triangles with negative orientation
test_data( "two_rectangles.msh" );
}
BOOST_AUTO_TEST_SUITE_END();
| 40.044118 | 104 | 0.597503 | [
"mesh",
"vector"
] |
13ff5a414ae2d7b25211998be59dda8b5f8d0198 | 838 | cpp | C++ | Unidad-1/Aula04/8.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | Unidad-1/Aula04/8.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | Unidad-1/Aula04/8.cpp | luismoroco/ProgrCompetitiva | 011cdb18749a16d17fd635a7c36a8a21b2b643d9 | [
"BSD-3-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, x, target, i, left, rigth, tmp;
bool flag = false;
vector<int> array;
cin >> n >> target;
while (n--){
cin >> x;
array.push_back(x);
}
for ( i = 1; i <= array.size(); ++i)
{
left = i;
rigth = array.size()-1;
while (left < rigth && array[left] && array[rigth])
{
tmp = array[left] + array[rigth];
if (tmp == target)
{
cout << left << ' ' << rigth << '\n';
flag = true;
exit(1);
}
else if (tmp < target)
left++;
else
rigth--;
}
}
if (flag == false)
cout << "IMPOSSIBLE" << '\n';
return EXIT_SUCCESS;
}
| 19.952381 | 60 | 0.390215 | [
"vector"
] |
cd0410c26f4112b83c7d654b599986317757b447 | 12,089 | cpp | C++ | Test/UnitTests/UnitTests.cpp | kernyan/KalmanFilterController | c04c48b29c826a2c942ba09132b5b764399196c7 | [
"MIT"
] | null | null | null | Test/UnitTests/UnitTests.cpp | kernyan/KalmanFilterController | c04c48b29c826a2c942ba09132b5b764399196c7 | [
"MIT"
] | null | null | null | Test/UnitTests/UnitTests.cpp | kernyan/KalmanFilterController | c04c48b29c826a2c942ba09132b5b764399196c7 | [
"MIT"
] | 1 | 2021-10-03T12:48:28.000Z | 2021-10-03T12:48:28.000Z |
#include "fusion_kf.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "measurement_package.h"
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
class LKFTest : public :: testing::Test {
protected:
virtual void SetUp(){
mu_ = VectorXd(4);
mu_ << 0.312242687, 0.580339789,1,1;
Sigma_ = MatrixXd(4,4);
Sigma_ << 1,0,0,0,
0,1,0,0,
0,0,1000,0,
0,0,0,1000;
t_ = 0;
LaserLKF *LaserFilter = new LaserLKF(mu_, Sigma_, t_);
LaserFilter->Initialize();
ParaKF_ = LaserFilter;
meas_.sensor_type_ = LASER;
meas_.raw_measurements_ = VectorXd(2);
meas_.raw_measurements_ << 0.312242687, 0.580339789;
meas_.timestamp_ = t_ + 100000;
}
virtual void TearDown() {
delete ParaKF_;
ParaKF_ = nullptr;
}
VectorXd mu_;
MatrixXd Sigma_;
long long t_;
ParametricKF *ParaKF_;
MeasurementPackage meas_;
};
TEST_F(LKFTest, PredictionMu){
ParaKF_->Step(meas_);
auto LKF = dynamic_cast<LinearKF*> (ParaKF_);
auto Mat = LKF->GetMuBar();
vector<float> Calc(Mat.data(),Mat.data()+Mat.rows()*Mat.cols());
vector<float> Ans {0.412242687, 0.680339789,1,1};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.00001) << "for i: " << i;
}
}
TEST_F(LKFTest, PredictionSigma){
ParaKF_->Step(meas_);
auto LKF = dynamic_cast<LinearKF*> (ParaKF_);
auto Mat = LKF->GetSigmaBar();
vector<float> Calc(Mat.data(),Mat.data()+Mat.rows()*Mat.cols());
vector<float> Ans {11.0002, 0, 100.005, 0,
0, 11.0002, 0, 100.005,
100.005, 0, 1000.09, 0,
0, 100.005, 0, 1000.09};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.001) << "for i: " << i;
}
}
TEST_F(LKFTest, PredictAndUpdate){
ParaKF_->Step(meas_);
meas_.raw_measurements_ << 0.6, 0.6;
meas_.timestamp_ += 100000;
ParaKF_->Step(meas_);
auto LKF = dynamic_cast<LinearKF*> (ParaKF_);
vector<float> Calc(mu_.data(),mu_.data()+mu_.rows()*mu_.cols());
vector<float> Ans {0.593825,0.599774,2.69674,0.188019};
vector<float> Calc2(Sigma_.data(), Sigma_.data() + Sigma_.rows() * Sigma_.cols());
vector<float> Ans2 {0.0220007,0,0.210544,0,
0,0.0220007,0,0.210544,
0.210544,0,4.09938,0,
0,0.210544,0,4.09938};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.001) << "for i: " << i;
}
for (int i = 0; i < Calc2.size(); ++i){
EXPECT_NEAR(Calc2[i], Ans2[i], 0.001) << "for i: " << i;
}
}
class RKFTest : public :: testing::Test {
protected:
virtual void SetUp(){
mu_ = VectorXd(4);
mu_ << 1,1,1,1;
Sigma_ = MatrixXd(4,4);
Sigma_ << 1,0,0,0,
0,1,0,0,
0,0,1000,0,
0,0,0,1000;
t_ = 0;
ExtendedKF *EFilter = new ExtendedKF(mu_, Sigma_, t_);
MatrixXd Gt(4,4);
float dt = 0.1;
Gt << 1,0,dt, 0,
0,1, 0,dt,
0,0, 1, 0,
0,0, 0, 1;
function<VectorXd (VectorXd)> g_in = [Gt](VectorXd Mu_in){
return Gt*Mu_in;
};
MatrixXd Rt(4,4);
float noise_ax = 9;
float noise_ay = 9;
float dt_2 = dt*dt;
float dt_3 = dt_2*dt;
float dt_4 = dt_3*dt;
Rt << dt_4/4*noise_ax, 0, dt_3/2*noise_ax, 0,
0, dt_4/4*noise_ay, 0, dt_3/2*noise_ay,
dt_3/2*noise_ax, 0, dt_2*noise_ax, 0,
0, dt_3/2*noise_ay, 0, dt_2*noise_ay;
function<VectorXd (VectorXd)> h_in = [](VectorXd MuBar_in){
VectorXd zhat(3);
float px = MuBar_in(0);
float py = MuBar_in(1);
float vx = MuBar_in(2);
float vy = MuBar_in(3);
float p = sqrt(px*px + py*py);
float phi = atan2(py, px);
if (phi > -M_PI){
while (phi > M_PI) phi -= 2*M_PI;
} else {
while (phi < -M_PI) phi += 2*M_PI;
}
float p_dot = (px*vx+py*vy)/p;
zhat << p, phi, p_dot;
return zhat;
};
function<MatrixXd (VectorXd)> H_in = [](VectorXd MuBar_in){
MatrixXd Hj(3,4);
float px = MuBar_in(0);
float py = MuBar_in(1);
float vx = MuBar_in(2);
float vy = MuBar_in(3);
float p_mag = px*px + py*py;
float p_dot = sqrt(p_mag);
if (p_mag < 0.001) return Hj;
Hj << px/p_dot, py/p_dot, 0, 0,
-py/p_mag, px/p_mag, 0, 0,
py*(vx*py-vy*px)/(p_mag*p_dot), px*(vy*px-vx*py)/(p_mag*p_dot), px/p_dot, py/p_dot;
return Hj;
};
MatrixXd Qt(3,3);
Qt << 0.09,0 ,0,
0 ,0.0009,0,
0 ,0 ,0.09;
EFilter->Initialize(g_in, Gt, Rt, h_in, H_in, Qt);
ParaKF_ = EFilter;
meas_.sensor_type_ = RADAR;
meas_.raw_measurements_ = VectorXd(3);
meas_.raw_measurements_ << 1.01489198, 0.554329216,4.89280701;
meas_.timestamp_ = t_ + 100000;
}
virtual void TearDown() {
delete ParaKF_;
ParaKF_ = nullptr;
}
VectorXd mu_;
MatrixXd Sigma_;
long long t_;
ParametricKF *ParaKF_;
MeasurementPackage meas_;
};
TEST_F(RKFTest, PredictionMu){
ParaKF_->Step(meas_);
auto EKF = dynamic_cast<ExtendedKF*> (ParaKF_);
auto Mat = EKF->GetMuBar();
vector<float> Calc(Mat.data(),Mat.data()+Mat.rows()*Mat.cols());
vector<float> Ans {1.1,1.1,1,1};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.00001) << "for i: " << i;
}
}
TEST_F(RKFTest, PredictionSigma){
ParaKF_->Step(meas_);
auto RKF = dynamic_cast<ExtendedKF*> (ParaKF_);
auto Mat = RKF->GetSigmaBar();
vector<float> Calc(Mat.data(),Mat.data()+Mat.rows()*Mat.cols());
vector<float> Ans {11.0002, 0, 100.005, 0,
0, 11.0002, 0, 100.005,
100.005, 0, 1000.09, 0,
0, 100.005, 0, 1000.09};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.001) << "for i: " << i;
}
}
TEST_F(RKFTest, PredictAndUpdate){
ParaKF_->Step(meas_);
auto RKF = dynamic_cast<ExtendedKF*> (ParaKF_);
vector<float> Calc(mu_.data(),mu_.data()+mu_.rows()*mu_.cols());
vector<float> Ans {1.02359,0.515336,5.76462,1.14404};
vector<float>Calc2(Sigma_.data(),Sigma_.data()+Sigma_.rows()*Sigma_.cols());
vector<float>Ans2{0.042377,0.0401995,0.0102694,-0.00952716,
0.0401995,0.042377,-0.00952716,0.0102694,
0.0102694,-0.00952716,45.6029,-45.513,
-0.00952716,0.0102694,-45.513,45.6029};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.001) << "for i: " << i;
}
for (int i = 0; i < Calc2.size(); ++i){
EXPECT_NEAR(Calc2[i], Ans2[i], 0.001) << "for i: " << i;
}
}
class FusionTest : public :: testing::Test {
protected:
virtual void SetUp(){
measL1.sensor_type_ = LASER;
measL1.raw_measurements_ = VectorXd(2);
measL1.raw_measurements_ << 0.312242687, 0.580339789;
measL1.timestamp_ = 0;
measR1.sensor_type_ = RADAR;
measR1.raw_measurements_ = VectorXd(3);
measR1.raw_measurements_ << 1.01489,0.554329,4.89281;
measR1.timestamp_ = measL1.timestamp_ + 50000;
measL2.sensor_type_ = LASER;
measL2.raw_measurements_ = VectorXd(2);
measL2.raw_measurements_ << 1.17385,0.481073;
measL2.timestamp_ = measR1.timestamp_ + 50000;
measR2.sensor_type_ = RADAR;
measR2.raw_measurements_ = VectorXd(3);
measR2.raw_measurements_ << 1.04751,0.38924,4.51132;
measR2.timestamp_ = measL2.timestamp_ + 50000;
}
virtual void TearDown(){};
MeasurementPackage measL1;
MeasurementPackage measL2;
MeasurementPackage measR1;
MeasurementPackage measR2;
};
TEST_F(FusionTest, FusionLaserLKF){
FusionKF FKF(CONSTANT_VELOCITY);
FKF.AddLaserLKF();
FKF.ProcessMeasurement(measL1);
auto Mu = FKF.GetMu();
auto Sg = FKF.GetSigma();
vector<float> Calc(Mu.data(),Mu.data()+Mu.rows()*Mu.cols());
vector<float> Ans {0.312243,0.58034,0,0};
vector<float>Calc2(Sg.data(),Sg.data()+Sg.rows()*Sg.cols());
vector<float> Ans2 {0.0220049,0,0,0,
0,0.0220049,0,0,
0,0,1000,0,
0,0,0,1000};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.001) << "for i: " << i;
}
for (int i = 0; i < Calc2.size(); ++i){
EXPECT_NEAR(Calc2[i], Ans2[i], 0.001) << "for i: " << i;
}
FKF.ProcessMeasurement(measL2);
Mu = FKF.GetMu();
Sg = FKF.GetSigma();
vector<float>Calc3(Mu.data(),Mu.data()+Mu.rows()*Mu.cols());
vector<float>Ans3{1.17192,0.481295,8.57809,-0.988292};
vector<float>Calc4(Sg.data(),Sg.data()+Sg.rows()*Sg.cols());
vector<float>Ans4{0.0224496,0,0.224008,0,
0,0.0224496,0,0.224008,
0.224008,0,4.45347,0,
0,0.224008,0,4.45347};
for (int i = 0; i < Calc3.size(); ++i){
EXPECT_NEAR(Calc3[i], Ans3[i], 0.001) << "for i: " << i;
}
for (int i = 0; i < Calc4.size(); ++i){
EXPECT_NEAR(Calc4[i], Ans4[i], 0.001) << "for i: " << i;
}
}
TEST_F(FusionTest, FusionRadarEKF){
FusionKF FKF(CONSTANT_VELOCITY);
FKF.AddRadarEKF();
FKF.ProcessMeasurement(measR1);
auto Mu = FKF.GetMu();
auto Sg = FKF.GetSigma();
vector<float> Calc(Mu.data(),Mu.data()+Mu.rows()*Mu.cols());
vector<float> Ans {0.870819,0.547247,4.29365,2.34518};
vector<float>Calc2(Sg.data(),Sg.data()+Sg.rows()*Sg.cols());
vector<float> Ans2 {0.0638724,0.0342303,0,0,
0.0342303,0.0198985,0,0,
0,0,229.849,-420.653,
0,0,-420.653,770.241};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.001) << "for i: " << i;
}
for (int i = 0; i < Calc2.size(); ++i){
EXPECT_NEAR(Calc2[i], Ans2[i], 0.001) << "for i: " << i;
}
FKF.ProcessMeasurement(measR2);
Mu = FKF.GetMu();
Sg = FKF.GetSigma();
vector<float>Calc3(Mu.data(),Mu.data()+Mu.rows()*Mu.cols());
vector<float>Ans3{1.21447,0.460064,5.2626,0.11902};
vector<float>Calc4(Sg.data(),Sg.data()+Sg.rows()*Sg.cols());
vector<float>Ans4{0.0322415,0.018169,-0.000717736,0.00503674,
0.018169,0.0130109,-0.0123944,0.0239852,
-0.000717736,-0.0123944,0.134095,-0.128462,
0.00503674,0.0239852,-0.128462,0.282386};
for (int i = 0; i < Calc3.size(); ++i){
EXPECT_NEAR(Calc3[i], Ans3[i], 0.001) << "for i: " << i;
}
for (int i = 0; i < Calc4.size(); ++i){
EXPECT_NEAR(Calc4[i], Ans4[i], 0.001) << "for i: " << i;
}
}
TEST_F(FusionTest, FusionLaserAndRadar){
FusionKF FKF(CONSTANT_VELOCITY);
FKF.AddRadarEKF();
FKF.AddLaserLKF();
FKF.ProcessMeasurement(measL1);
FKF.ProcessMeasurement(measR1);
FKF.ProcessMeasurement(measL2);
FKF.ProcessMeasurement(measR2);
auto Mu = FKF.GetMu();
auto Sg = FKF.GetSigma();
vector<float>Calc(Mu.data(),Mu.data()+Mu.rows()*Mu.cols());
vector<float>Ans{1.09685,0.586652,4.81974,2.05109};
vector<float>Calc2(Sg.data(),Sg.data()+Sg.rows()*Sg.cols());
vector<float>Ans2{0.0044511,0.00215911,0.0186872,-0.0177024,
0.00215911,0.00313799,0.00460727,0.000653721,
0.0186872,0.00460727,0.125729,-0.0910125,
-0.0177024,0.000653721,-0.0910125,0.194103};
for (int i = 0; i < Calc.size(); ++i){
EXPECT_NEAR(Calc[i], Ans[i], 0.001) << "for i: " << i;
}
for (int i = 0; i < Calc2.size(); ++i){
EXPECT_NEAR(Calc2[i], Ans2[i], 0.001) << "for i: " << i;
}
}
TEST(UnscentedTest, SimpleRun){
FusionKF FKF(CONSTANT_TURNRATE_VELOCITY);
FKF.AddRadarUKF();
MeasurementPackage meas_in;
meas_in.timestamp_ = 0;
meas_in.raw_measurements_ = VectorXd(3);
meas_in.raw_measurements_ << 5.9214,0.2187,2.0062;
FKF.ProcessMeasurement(meas_in);
//cout << "Mu\n" << FKF.GetMu() << endl;
MeasurementPackage meas_in2;
meas_in.timestamp_ = 100000;
meas_in.raw_measurements_ = VectorXd(3);
meas_in.raw_measurements_ << 5.9214,0.2187,2.0062;
}
| 27.727064 | 94 | 0.58119 | [
"vector"
] |
cd063cf61c938beb29c7c418f437d003e1eff0fc | 4,557 | cpp | C++ | Testing/VisualPipes/albaPipeIsosurfaceTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Testing/VisualPipes/albaPipeIsosurfaceTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Testing/VisualPipes/albaPipeIsosurfaceTest.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaPipeIsosurfaceTest
Authors: Matteo Giacomoni
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include <cppunit/config/SourcePrefix.h>
#include "albaPipeIsosurfaceTest.h"
#include "albaPipeIsosurface.h"
#include "albaSceneNode.h"
#include "albaVMEVolumeGray.h"
#include "mmaVolumeMaterial.h"
#include "vtkALBAAssembly.h"
#include "vtkMapper.h"
#include "vtkPointData.h"
#include "vtkStructuredPointsReader.h"
#include "vtkCamera.h"
#include "vtkRectilinearGrid.h"
#include "vtkProp3DCollection.h"
#include "vtkDataSetReader.h"
// render window stuff
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include <iostream>
#include <fstream>
//----------------------------------------------------------------------------
void albaPipeIsosurfaceTest::TestFixture()
//----------------------------------------------------------------------------
{
}
//----------------------------------------------------------------------------
void albaPipeIsosurfaceTest::BeforeTest()
//----------------------------------------------------------------------------
{
vtkNEW(m_Renderer);
vtkNEW(m_RenderWindow);
vtkNEW(m_RenderWindowInteractor);
m_Renderer->SetBackground(0.1, 0.1, 0.1);
m_RenderWindow->AddRenderer(m_Renderer);
m_RenderWindow->SetSize(640, 480);
m_RenderWindow->SetPosition(200, 0);
m_RenderWindowInteractor->SetRenderWindow(m_RenderWindow);
}
//----------------------------------------------------------------------------
void albaPipeIsosurfaceTest::AfterTest()
//----------------------------------------------------------------------------
{
vtkDEL(m_Renderer);
vtkDEL(m_RenderWindow);
vtkDEL(m_RenderWindowInteractor);
}
//----------------------------------------------------------------------------
void albaPipeIsosurfaceTest::TestPipeExecution()
//----------------------------------------------------------------------------
{
vtkDataSetReader *Importer;
vtkNEW(Importer);
albaString filename=ALBA_DATA_ROOT;
filename<<"/Test_PipeIsosurface/volumeRG.vtk";
Importer->SetFileName(filename);
Importer->Update();
albaVMEVolumeGray *volumeInput;
albaNEW(volumeInput);
volumeInput->SetData((vtkRectilinearGrid*)Importer->GetOutput(),0.0);
volumeInput->GetOutput()->GetVTKData()->Update();
volumeInput->GetOutput()->Update();
volumeInput->Update();
mmaVolumeMaterial *material;
albaNEW(material);
albaVMEOutputVolume::SafeDownCast(volumeInput->GetOutput())->SetMaterial(material);
//Assembly will be create when instancing albaSceneNode
albaSceneNode *sceneNode;
sceneNode = new albaSceneNode(NULL,NULL,volumeInput, NULL);
double scalarValue[2] = {1.0,0.0};
for (int v = 0 ; v<2;v++)
{
/////////// Pipe Instance and Creation ///////////
albaPipeIsosurface *pipeIso = new albaPipeIsosurface;
pipeIso->Create(sceneNode);
pipeIso->SetContourValue(scalarValue[v]);
////////// ACTORS List ///////////////
vtkProp3DCollection *actorList = pipeIso->GetAssemblyFront()->GetParts();
actorList->InitTraversal();
vtkProp *actor = actorList->GetNextProp();
while(actor)
{
m_Renderer->AddActor(actor);
m_RenderWindow->Render();
actor = actorList->GetNextProp();
}
m_RenderWindow->Render();
double b[6];
volumeInput->GetOutput()->GetVTKData()->GetBounds(b);
m_Renderer->ResetCamera(b);
m_RenderWindow->Render();
printf("\n Visualization: \n");
COMPARE_IMAGES("TestPipeExecution", v);
m_Renderer->RemoveAllProps();
sceneNode->DeletePipe();
}
delete sceneNode;
albaDEL(material);
albaDEL(volumeInput);
vtkDEL(Importer);
} | 30.790541 | 85 | 0.582401 | [
"render"
] |
997fab2343c8d69ea3de42129b052b3def717ded | 9,998 | cpp | C++ | Source.cpp | jordanbarber/zombieGame | 42e4c65ada02bc4af0f9d3ae719b728b24e5982a | [
"Artistic-2.0"
] | null | null | null | Source.cpp | jordanbarber/zombieGame | 42e4c65ada02bc4af0f9d3ae719b728b24e5982a | [
"Artistic-2.0"
] | null | null | null | Source.cpp | jordanbarber/zombieGame | 42e4c65ada02bc4af0f9d3ae719b728b24e5982a | [
"Artistic-2.0"
] | null | null | null | //SKELETON PROGRAM
//---------------------------------
//include libraries
//include standard libraries
#include <iostream > //for output and input: cin >> and cout <<
#include <iomanip> //for formatted output in 'cout'
#include <conio.h> //for getch()
#include <string> //for string
using namespace std;
//include our own libraries
#include "RandomUtils.h" //for Seed, Random
#include "ConsoleUtils.h" //for Clrscr, Gotoxy, etc.
//---------------------------------
//define constants
//---------------------------------
//define global constants
//defining the size of the grid
const int SIZEY(12); //vertical dimension
const int SIZEX(20); //horizontal dimension
//defining symbols used for display of the grid and content
const char SPOT('@'); //spot
const char TUNNEL(' '); //open space
const char WALL('#'); //border
//defining the command letters to move the blob on the maze
const int UP(72); //up arrow
const int DOWN(80); //down arrow
const int RIGHT(77); //right arrow
const int LEFT(75); //left arrow
//defining the other command letters
const char QUIT('Q'); //end the game
//data structure to store data for a grid item
struct Item {
const char symbol; //symbol on grid
int x, y; //coordinates
};
//---------------------------------------------------------------------------
//----- run game
//---------------------------------------------------------------------------
int main()
{
//function declarations (prototypes)
void initialiseGame(char grid[][SIZEX], Item& spot);
bool wantToQuit(int k);
bool isArrowKey(int k);
int getKeyPress();
void updateGame(char g[][SIZEX], Item& sp, int k, string& mess);
void renderGame(const char g[][SIZEX], string mess);
void endProgram();
//local variable declarations
char grid[SIZEY][SIZEX]; //grid for display
Item spot = { SPOT }; //Spot's symbol and position (0, 0)
string message("LET'S START... "); //current message to player
//action...
initialiseGame(grid, spot); //initialise grid (incl. walls and spot)
int key(' '); //create key to store keyboard events
do {
renderGame(grid, message); //render game state on screen
message = " "; //reset message
key = getKeyPress(); //read in next keyboard event
if (isArrowKey(key))
updateGame(grid, spot, key, message);
else
message = "INVALID KEY! "; //set 'Invalid key' message
} while (!wantToQuit(key)); //while user does not want to quit
endProgram(); //display final message
return 0;
} //end main
void updateGame(char grid[][SIZEX], Item& spot, int key, string& message)
{ //updateGame state
void updateSpotCoordinates(const char g[][SIZEX], Item& spot, int key, string& mess);
void updateGrid(char g[][SIZEX], Item spot);
updateSpotCoordinates(grid, spot, key, message); //update spot coordinates
//according to key
updateGrid(grid, spot); //update grid information
}
//---------------------------------------------------------------------------
//----- initialise game state
//---------------------------------------------------------------------------
void initialiseGame(char grid[][SIZEX], Item& spot)
{ //initialise grid and place spot in middle
void setGrid(char[][SIZEX]);
void setSpotInitialCoordinates(Item& spot);
void placeSpot(char gr[][SIZEX], Item spot);
Seed(); //seed reandom number generator
setSpotInitialCoordinates(spot); //initialise spot position
setGrid(grid); //reset empty grid
placeSpot(grid, spot); //set spot in grid
} //end of initialiseGame
void setSpotInitialCoordinates(Item& spot)
{ //set spot coordinates inside the grid at random at beginning of game
spot.y = Random(SIZEY - 2); //vertical coordinate in range [1..(SIZEY - 2)]
spot.x = Random(SIZEX - 2); //horizontal coordinate in range [1..(SIZEX - 2)]
} //end of setSpotInitialoordinates
void setGrid(char grid[][SIZEX])
{ //reset the empty grid configuration
for (int row(0); row < SIZEY; ++row) //for each column
{
for (int col(0); col < SIZEX; ++col) //for each col
{
if ((row == 0) || (row == SIZEY - 1)) //top and bottom walls
grid[row][col] = WALL; //draw a wall symbol
else
if ((col == 0) || (col == SIZEX - 1)) //left and right walls
grid[row][col] = WALL; //draw a wall symbol
else
grid[row][col] = TUNNEL; //draw a space
} //end of row-loop
} //end of col-loop
} //end of setGrid
void placeSpot(char gr[][SIZEX], Item spot)
{ //place spot at its new position in grid
gr[spot.y][spot.x] = spot.symbol;
} //end of placeSpot
//---------------------------------------------------------------------------
//----- update grid state
//---------------------------------------------------------------------------
void updateGrid(char grid[][SIZEX], Item spot)
{ //update grid configuration after each move
void setGrid(char[][SIZEX]);
void placeSpot(char g[][SIZEX], Item spot);
setGrid(grid); //reset empty grid
placeSpot(grid, spot); //set spot in grid
} //end of updateGrid
//---------------------------------------------------------------------------
//----- move the spot
//---------------------------------------------------------------------------
void updateSpotCoordinates(const char g[][SIZEX], Item& sp, int key, string& mess)
{ //move spot in required direction
void setKeyDirection(int k, int& dx, int& dy);
//calculate direction of movement required by key - if any
int dx(0), dy(0);
setKeyDirection(key, dx, dy); //find direction indicated by key
//check new target position in grid
//and update spot coordinates if move is possible
const int targetY(sp.y + dy);
const int targetX(sp.x + dx);
switch (g[targetY][targetX])
{ //...depending on what's on the target position in grid...
case TUNNEL: //can move
sp.y += dy; //go in that Y direction
sp.x += dx; //go in that X direction
break;
case WALL: //hit a wall and stay there
cout << '\a'; //beep the alarm
mess = "CANNOT GO THERE! ";
break;
}
} //end of updateSpotCoordinates
//---------------------------------------------------------------------------
//----- process key
//---------------------------------------------------------------------------
void setKeyDirection(int key, int& dx, int& dy)
{ //
switch (key) //...depending on the selected key...
{
case LEFT: //when LEFT arrow pressed...
dx = -1; //decrease the X coordinate
dy = 0;
break;
case RIGHT: //when RIGHT arrow pressed...
dx = +1; //increase the X coordinate
dy = 0;
break;
case DOWN: //---------ADDED TO SKELETON---------//
dy = +1; //when up addow pressed y coordinate increased
dx = 0;
break;
case UP:
dy = -1; //when down arrow pressed y coordinate decreased
dx = 0;
break;
}
} //end of setKeyDirection
int getKeyPress()
{ //get key or command selected by user
int keyPressed;
keyPressed = getch(); //read in the selected arrow key or command letter
while (keyPressed == 224) //ignore symbol following cursor key
keyPressed = getch();
return(keyPressed);
} //end of getKeyPress
bool isArrowKey(int key)
{ //check if the key pressed is an arrow key (also accept 'K', 'M', 'H' and 'P')
return ((key == LEFT) || (key == RIGHT) || (key == UP) || (key == DOWN));
} //end of isArrowKey
bool wantToQuit(int key)
{ //check if the key pressed is 'Q'
return (key == QUIT);
} //end of wantToQuit
//---------------------------------------------------------------------------
//----- display info on screen
//---------------------------------------------------------------------------
void clearMessage()
{ //clear message area on screen
SelectBackColour(clBlack);
SelectTextColour(clWhite);
Gotoxy(40, 8);
string str(20, ' ');
cout << str; //display blank message
} //end of setMessage
void renderGame(const char gd[][SIZEX], string mess)
{ //display game title, messages, maze, spot and apples on screen
void paintGrid(const char g[][SIZEX]);
void showTitle();
void showOptions();
void showMessage(string);
Gotoxy(0, 0);
//display grid contents
paintGrid(gd);
//display game title
showTitle();
//display menu options available
showOptions();
//display message if any
showMessage(mess);
} //end of paintGame
void paintGrid(const char g[][SIZEX])
{ //display grid content on screen
SelectBackColour(clBlack);
SelectTextColour(clWhite);
Gotoxy(0, 2);
for (int row(0); row < SIZEY; ++row) //for each row (vertically)
{
for (int col(0); col < SIZEX; ++col) //for each column (horizontally)
{
cout << g[row][col]; //output cell content
} //end of col-loop
cout << endl;
} //end of row-loop
} //end of paintGrid
void showTitle()
{ //display game title
SelectTextColour(clYellow);
Gotoxy(0, 0);
cout << "___ZOMBIES GAME SKELETON___\n" << endl;
SelectBackColour(clWhite);
SelectTextColour(clRed);
Gotoxy(40, 0);
cout << "Pascale Vacher: March 15";
} //end of showTitle
void showOptions()
{ //show game options
SelectBackColour(clRed);
SelectTextColour(clYellow);
Gotoxy(40, 5);
cout << "TO MOVE USE KEYBOARD ARROWS ";
Gotoxy(40, 6);
cout << "TO QUIT ENTER 'Q' ";
} //end of showOptions
void showMessage(string m)
{ //print auxiliary messages if any
SelectBackColour(clBlack);
SelectTextColour(clWhite);
Gotoxy(40, 8);
cout << m; //display current message
} //end of showMessage
void endProgram()
{ //end program with appropriate message
SelectBackColour(clBlack);
SelectTextColour(clYellow);
Gotoxy(40, 8);
cout << "PLAYER QUITS! ";
//hold output screen until a keyboard key is hit
Gotoxy(40, 9);
system("pause");
} //end of endProgram
| 33.10596 | 86 | 0.572715 | [
"render"
] |
9980a1722b685f39e5600b95ae3a83e96ac9edd6 | 7,426 | cpp | C++ | src/game/shared/hl2mp/weapons/weapon_hl2mpbase_machinegun.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/shared/hl2mp/weapons/weapon_hl2mpbase_machinegun.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/shared/hl2mp/weapons/weapon_hl2mpbase_machinegun.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#if defined( CLIENT_DLL )
#include "c_hl2mp_player.h"
#else
#include "hl2mp_player.h"
#endif
#include "weapon_hl2mpbase_machinegun.h"
#include "in_buttons.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
IMPLEMENT_NETWORKCLASS_ALIASED(HL2MPMachineGun, DT_HL2MPMachineGun)
BEGIN_NETWORK_TABLE(CHL2MPMachineGun, DT_HL2MPMachineGun)
END_NETWORK_TABLE ()
BEGIN_PREDICTION_DATA(CHL2MPMachineGun)
END_PREDICTION_DATA()
//=========================================================
// >> CHLSelectFireMachineGun
//=========================================================
BEGIN_DATADESC(CHL2MPMachineGun)
DEFINE_FIELD(m_nShotsFired, FIELD_INTEGER),
DEFINE_FIELD(m_flNextSoundTime, FIELD_TIME),
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CHL2MPMachineGun::CHL2MPMachineGun(void) {
}
const Vector &CHL2MPMachineGun::GetBulletSpread(void) {
static Vector cone = VECTOR_CONE_3DEGREES;
return cone;
}
//-----------------------------------------------------------------------------
// Purpose:
//
//
//-----------------------------------------------------------------------------
void CHL2MPMachineGun::PrimaryAttack(void) {
// Only the player fires this way so we can cast
CBasePlayer *pPlayer = ToBasePlayer(GetOwner());
if (!pPlayer)
return;
// Abort here to handle burst and auto fire modes
if ((UsesClipsForAmmo1() && m_iClip1 == 0) || (!UsesClipsForAmmo1() && !pPlayer->GetAmmoCount(m_iPrimaryAmmoType)))
return;
m_nShotsFired++;
pPlayer->DoMuzzleFlash();
// To make the firing framerate independent, we may have to fire more than one bullet here on low-framerate systems,
// especially if the weapon we're firing has a really fast rate of fire.
int iBulletsToFire = 0;
float fireRate = GetFireRate();
while (m_flNextPrimaryAttack <= gpGlobals->curtime) {
// MUST call sound before removing a round from the clip of a CHLMachineGun
WeaponSound(SINGLE, m_flNextPrimaryAttack);
m_flNextPrimaryAttack = m_flNextPrimaryAttack + fireRate;
iBulletsToFire++;
}
// Make sure we don't fire more than the amount in the clip, if this weapon uses clips
if (UsesClipsForAmmo1()) {
if (iBulletsToFire > m_iClip1)
iBulletsToFire = m_iClip1;
m_iClip1 -= iBulletsToFire;
}
CHL2MP_Player *pHL2MPPlayer = ToHL2MPPlayer(pPlayer);
// Fire the bullets
FireBulletsInfo_t info;
info.m_iShots = iBulletsToFire;
info.m_vecSrc = pHL2MPPlayer->Weapon_ShootPosition();
info.m_vecDirShooting = pPlayer->GetAutoaimVector(AUTOAIM_5DEGREES);
info.m_vecSpread = pHL2MPPlayer->GetAttackSpread(this);
info.m_flDistance = MAX_TRACE_LENGTH;
info.m_iAmmoType = m_iPrimaryAmmoType;
info.m_iTracerFreq = 2;
FireBullets(info);
//Factor in the view kick
AddViewKick();
if (!m_iClip1 && pPlayer->GetAmmoCount(m_iPrimaryAmmoType) <= 0) {
// HEV suit - indicate out of ammo condition
pPlayer->SetSuitUpdate("!HEV_AMO0", FALSE, 0);
}
SendWeaponAnim(GetPrimaryAttackActivity());
pPlayer->SetAnimation(PLAYER_ATTACK1);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : &info -
//-----------------------------------------------------------------------------
void CHL2MPMachineGun::FireBullets(const FireBulletsInfo_t &info) {
if (CBasePlayer *pPlayer = ToBasePlayer(GetOwner())) {
pPlayer->FireBullets(info);
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2MPMachineGun::DoMachineGunKick(CBasePlayer *pPlayer, float dampEasy, float maxVerticleKickAngle,
float fireDurationTime, float slideLimitTime) {
#define KICK_MIN_X 0.2f //Degrees
#define KICK_MIN_Y 0.2f //Degrees
#define KICK_MIN_Z 0.1f //Degrees
QAngle vecScratch;
int iSeed = CBaseEntity::GetPredictionRandomSeed() & 255;
//Find how far into our accuracy degradation we are
float duration = (fireDurationTime > slideLimitTime) ? slideLimitTime : fireDurationTime;
float kickPerc = duration / slideLimitTime;
// do this to get a hard discontinuity, clear out anything under 10 degrees punch
pPlayer->ViewPunchReset(10);
//Apply this to the view angles as well
vecScratch.x = -(KICK_MIN_X + (maxVerticleKickAngle * kickPerc));
vecScratch.y = -(KICK_MIN_Y + (maxVerticleKickAngle * kickPerc)) / 3;
vecScratch.z = KICK_MIN_Z + (maxVerticleKickAngle * kickPerc) / 8;
RandomSeed(iSeed);
//Wibble left and right
if (RandomInt(-1, 1) >= 0)
vecScratch.y *= -1;
iSeed++;
//Wobble up and down
if (RandomInt(-1, 1) >= 0)
vecScratch.z *= -1;
//Clip this to our desired min/max
UTIL_ClipPunchAngleOffset(vecScratch, pPlayer->m_Local.m_vecPunchAngle, QAngle(24.0f, 3.0f, 1.0f));
//Add it to the view punch
// NOTE: 0.5 is just tuned to match the old effect before the punch became simulated
pPlayer->ViewPunch(vecScratch * 0.5);
}
//-----------------------------------------------------------------------------
// Purpose: Reset our shots fired
//-----------------------------------------------------------------------------
bool CHL2MPMachineGun::Deploy(void) {
m_nShotsFired = 0;
return BaseClass::Deploy();
}
//-----------------------------------------------------------------------------
// Purpose: Make enough sound events to fill the estimated think interval
// returns: number of shots needed
//-----------------------------------------------------------------------------
int CHL2MPMachineGun::WeaponSoundRealtime(WeaponSound_t shoot_type) {
int numBullets = 0;
// ran out of time, clamp to current
if (m_flNextSoundTime < gpGlobals->curtime) {
m_flNextSoundTime = gpGlobals->curtime;
}
// make enough sound events to fill up the next estimated think interval
float dt = clamp(m_flAnimTime - m_flPrevAnimTime, 0, 0.2);
if (m_flNextSoundTime < gpGlobals->curtime + dt) {
WeaponSound(SINGLE_NPC, m_flNextSoundTime);
m_flNextSoundTime += GetFireRate();
numBullets++;
}
if (m_flNextSoundTime < gpGlobals->curtime + dt) {
WeaponSound(SINGLE_NPC, m_flNextSoundTime);
m_flNextSoundTime += GetFireRate();
numBullets++;
}
return numBullets;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHL2MPMachineGun::ItemPostFrame(void) {
CBasePlayer *pOwner = ToBasePlayer(GetOwner());
if (pOwner == NULL)
return;
// Debounce the recoiling counter
if ((pOwner->m_nButtons & IN_ATTACK) == false) {
m_nShotsFired = 0;
}
BaseClass::ItemPostFrame();
}
| 32.713656 | 120 | 0.559117 | [
"vector"
] |
998c958c3f03d05c04b150c1ec7dd7d047175b49 | 1,259 | cpp | C++ | Dev/unitTest_Engine_cpp_gtest/ObjectSystem/UpdateFrequency.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 37 | 2015-07-12T14:21:03.000Z | 2020-10-17T03:08:17.000Z | Dev/unitTest_Engine_cpp_gtest/ObjectSystem/UpdateFrequency.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 91 | 2015-06-14T10:47:22.000Z | 2020-06-29T18:05:21.000Z | Dev/unitTest_Engine_cpp_gtest/ObjectSystem/UpdateFrequency.cpp | GCLemon/Altseed | b525740d64001aaed673552eb4ba3e98a321fcdf | [
"FTL"
] | 14 | 2015-07-13T04:15:20.000Z | 2021-09-30T01:34:51.000Z | #include <gtest/gtest.h>
#include <Altseed.h>
#include "../EngineTest.h"
using namespace std;
using namespace asd;
class ObjectSystem_UpdateFrequency : public EngineTest
{
class MovingObject : public TextureObject2D
{
protected:
void OnUpdate()
{
SetPosition(GetPosition() + Vector2DF(3, 0));
}
};
public:
ObjectSystem_UpdateFrequency(bool isOpenGLMode)
: EngineTest(asd::ToAString("UpdateFrequency"), isOpenGLMode, 60)
{
}
protected:
void OnStart()
{
auto scene = make_shared<Scene>();
Engine::ChangeScene(scene);
AddHastedLayerTo(scene, 2, Vector2DF(10, 10));
AddHastedLayerTo(scene, 1, Vector2DF(10, 110));
AddHastedLayerTo(scene, 0.2f, Vector2DF(10, 210));
AddHastedLayerTo(scene, 0, Vector2DF(10, 310));
}
private:
void AddHastedLayerTo(Scene::Ptr scene, float frequency, Vector2DF position)
{
auto layer = make_shared<Layer2D>();
auto object = make_shared<MovingObject>();
layer->SetUpdateFrequency(frequency);
object->SetTexture(asd::Engine::GetGraphics()->CreateTexture2D(ToAString("Data/Texture/Cloud1.png").c_str()));
object->SetScale(Vector2DF(0.5f, 0.5f));
object->SetPosition(position);
scene->AddLayer(layer);
layer->AddObject(object);
}
};
ENGINE_TEST(ObjectSystem, UpdateFrequency) | 23.754717 | 112 | 0.728356 | [
"object"
] |
999022e780a0e11d21eb9ab4b4be370609b2c03b | 30,515 | cpp | C++ | libs/gui/src/CDisplayWindow3D.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 2 | 2017-03-25T18:09:17.000Z | 2017-05-22T08:14:48.000Z | libs/gui/src/CDisplayWindow3D.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | null | null | null | libs/gui/src/CDisplayWindow3D.cpp | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 1 | 2018-07-29T09:40:46.000Z | 2018-07-29T09:40:46.000Z | /* +---------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2017, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+---------------------------------------------------------------------------+ */
#include "gui-precomp.h" // Precompiled headers
#include <mrpt/config.h>
#include <mrpt/gui/CDisplayWindow3D.h>
#include <mrpt/utils/CImage.h>
#include <mrpt/utils/CTicTac.h>
#include <mrpt/gui/WxSubsystem.h>
#include <mrpt/gui/WxUtils.h>
using namespace mrpt;
using namespace mrpt::gui;
using namespace mrpt::utils;
using namespace mrpt::system;
using namespace mrpt::opengl;
using namespace mrpt::math;
using namespace std;
IMPLEMENTS_MRPT_OBJECT(CDisplayWindow3D,CBaseGUIWindow,mrpt::gui)
#if MRPT_HAS_OPENGL_GLUT
#ifdef MRPT_OS_WINDOWS
// Windows:
#include <windows.h>
#endif
#ifdef MRPT_OS_APPLE
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#ifdef HAVE_FREEGLUT_EXT_H
#include <GL/freeglut_ext.h>
#endif
#endif
#endif
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
#if !wxUSE_GLCANVAS
#error "OpenGL required: set wxUSE_GLCANVAS to 1 and rebuild wxWidgets"
#endif
#include <mrpt/gui/CMyGLCanvasBase.h>
#include <mrpt/opengl/CTextMessageCapable.h>
namespace mrpt
{
namespace gui
{
class CMyGLCanvas_DisplayWindow3D : public mrpt::gui::CMyGLCanvasBase
{
public:
CMyGLCanvas_DisplayWindow3D( CDisplayWindow3D *win3D,
wxWindow *parent, wxWindowID id = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0, const wxString& name = _T("CMyGLCanvas_DisplayWindow3D") );
virtual ~CMyGLCanvas_DisplayWindow3D();
CDisplayWindow3D *m_win3D;
// The idea is that CMyGLCanvas_DisplayWindow3D was derived from CTextMessageCapable, but
// that raises errors in MSVC when converting method pointers to wxObjectEventFunction...
struct THubClass : public mrpt::opengl::CTextMessageCapable
{
void render_text_messages_public(const int w, const int h) const { render_text_messages(w,h); }
};
THubClass m_text_msgs;
void OnCharCustom( wxKeyEvent& event );
void OnMouseDown(wxMouseEvent& event);
void OnPreRender();
void OnPostRender();
void OnPostRenderSwapBuffers(double At, wxPaintDC &dc);
static void display3D_processKeyEvent(CDisplayWindow3D *m_win3D, wxKeyEvent&ev);
};
}
}
CMyGLCanvas_DisplayWindow3D::CMyGLCanvas_DisplayWindow3D(
CDisplayWindow3D *win3D,
wxWindow *parent, wxWindowID id,
const wxPoint& pos, const wxSize& size, long style, const wxString& name)
: CMyGLCanvasBase(parent,id,pos,size,style,name)
{
m_win3D = win3D;
Connect(wxEVT_CHAR,(wxObjectEventFunction)&CMyGLCanvas_DisplayWindow3D::OnCharCustom);
Connect(wxEVT_CHAR_HOOK,(wxObjectEventFunction)&CMyGLCanvas_DisplayWindow3D::OnCharCustom);
Connect(wxEVT_LEFT_DOWN,(wxObjectEventFunction)&CMyGLCanvas_DisplayWindow3D::OnMouseDown);
Connect(wxEVT_RIGHT_DOWN,(wxObjectEventFunction)&CMyGLCanvas_DisplayWindow3D::OnMouseDown);
}
void CMyGLCanvas_DisplayWindow3D::display3D_processKeyEvent(CDisplayWindow3D *m_win3D, wxKeyEvent&ev)
{
if (m_win3D)
{
if (ev.AltDown() && ev.GetKeyCode()== MRPTK_RETURN)
{
if (mrpt::system::timeDifference( m_win3D->m_lastFullScreen, mrpt::system::now() )>0.2)
{
m_win3D->m_lastFullScreen = mrpt::system::now();
cout << "[CDisplayWindow3D] Switching fullscreen...\n";
C3DWindowDialog *win = (C3DWindowDialog*) m_win3D->m_hwnd.get();
if (win)
{
win->ShowFullScreen( !win->IsFullScreen() );
}
}
// Alt+Enter: Don't notify on this key stroke, since if we're switching to fullscreen
// and the user is waiting for a key to close the window, a runtime crash will occur,
// so return now:
return;
}
const int code = ev.GetKeyCode();
const mrptKeyModifier mod = mrpt::gui::keyEventToMrptKeyModifier(ev);
m_win3D->m_keyPushedCode = code;
m_win3D->m_keyPushedModifier = mod;
m_win3D->m_keyPushed = true;
// Send the event:
try {
m_win3D->publishEvent( mrptEventWindowChar(m_win3D,code,mod));
} catch(...) {}
}
//ev.Skip(); // Pass the event to whoever else.
}
void CMyGLCanvas_DisplayWindow3D::OnCharCustom( wxKeyEvent& ev )
{
CMyGLCanvas_DisplayWindow3D::display3D_processKeyEvent(m_win3D, ev);
}
void CMyGLCanvas_DisplayWindow3D::OnMouseDown(wxMouseEvent& event)
{
// Send the event:
if (m_win3D)
{
try {
m_win3D->publishEvent( mrptEventMouseDown(m_win3D, TPixelCoord(event.GetX(), event.GetY()), event.LeftDown(), event.RightDown() ) );
} catch(...) { }
}
event.Skip(); // so it's processed by the wx system!
}
CMyGLCanvas_DisplayWindow3D::~CMyGLCanvas_DisplayWindow3D()
{
m_openGLScene.clear_unique(); // Avoid the base class to free this object (it's freed by CDisplayWindow3D)
}
void CMyGLCanvas_DisplayWindow3D::OnPreRender()
{
if (m_openGLScene) m_openGLScene.clear_unique();
COpenGLScenePtr ptrScene = m_win3D->get3DSceneAndLock();
if (ptrScene)
m_openGLScene = ptrScene;
}
void CMyGLCanvas_DisplayWindow3D::OnPostRender()
{
// Avoid the base class to free this object (it's freed by CDisplayWindow3D)
m_openGLScene.clear_unique();
m_win3D->unlockAccess3DScene();
// If any, draw the 2D text messages:
int w,h;
this->GetSize(&w,&h);
m_text_msgs.render_text_messages_public(w,h);
}
void CMyGLCanvas_DisplayWindow3D::OnPostRenderSwapBuffers(double At, wxPaintDC &dc)
{
if (m_win3D) m_win3D->internal_setRenderingFPS(At>0 ? 1.0/At : 1e9);
// If we are requested to do so, grab images to disk as they are rendered:
string grabFile;
if (m_win3D)
grabFile = m_win3D->grabImageGetNextFile();
if (m_win3D && (!grabFile.empty() || m_win3D->isCapturingImgs()) )
{
int w,h;
dc.GetSize(&w, &h);
//Save image directly from OpenGL - It could also use 4 channels and save with GL_BGRA_EXT
CImagePtr frame(new CImage(w, h, 3, false));
glReadBuffer(GL_FRONT);
glReadPixels(0, 0, w, h, GL_BGR_EXT, GL_UNSIGNED_BYTE, (*frame)(0,0) );
if (!grabFile.empty())
{
frame->saveToFile(grabFile);
m_win3D->internal_emitGrabImageEvent(grabFile);
}
if (m_win3D->isCapturingImgs())
{
{
mrpt::synch::CCriticalSectionLocker lock(& m_win3D->m_last_captured_img_cs );
m_win3D->m_last_captured_img = frame;
frame.clear_unique();
}
}
}
}
#endif // Wx + OpenGL
#if MRPT_HAS_WXWIDGETS
BEGIN_EVENT_TABLE(C3DWindowDialog,wxFrame)
END_EVENT_TABLE()
const long C3DWindowDialog::ID_MENUITEM1 = wxNewId();
const long C3DWindowDialog::ID_MENUITEM2 = wxNewId();
C3DWindowDialog::C3DWindowDialog(
CDisplayWindow3D *win3D,
WxSubsystem::CWXMainFrame* parent,
wxWindowID id,
const std::string &caption,
wxSize initialSize ) :
m_win3D( win3D ),
m_mainFrame(parent)
{
#if MRPT_HAS_OPENGL_GLUT
Create(parent, id, _U(caption.c_str()), wxDefaultPosition, initialSize, wxDEFAULT_FRAME_STYLE, _T("id"));
wxIcon FrameIcon;
FrameIcon.CopyFromBitmap(mrpt::gui::WxSubsystem::getMRPTDefaultIcon());
SetIcon(FrameIcon);
// Create the wxCanvas object:
m_canvas = new CMyGLCanvas_DisplayWindow3D( win3D, this, wxID_ANY, wxDefaultPosition, wxDefaultSize );
// Events:
Connect(wxID_ANY,wxEVT_CLOSE_WINDOW,(wxObjectEventFunction)&C3DWindowDialog::OnClose);
Connect(ID_MENUITEM1,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&C3DWindowDialog::OnMenuClose);
Connect(ID_MENUITEM2,wxEVT_COMMAND_MENU_SELECTED,(wxObjectEventFunction)&C3DWindowDialog::OnMenuAbout);
Connect(wxID_ANY,wxEVT_CHAR,(wxObjectEventFunction)&C3DWindowDialog::OnChar);
Connect(wxID_ANY,wxEVT_SIZE,(wxObjectEventFunction)&C3DWindowDialog::OnResize);
// Increment number of windows:
//int winCount =
WxSubsystem::CWXMainFrame::notifyWindowCreation();
//cout << "[C3DWindowDialog] Notifying new window: " << winCount << endl;
#else
THROW_EXCEPTION("MRPT was compiled without OpenGL support")
#endif
//this->Iconize(false);
}
// Destructor
C3DWindowDialog::~C3DWindowDialog()
{
// cout << "[C3DWindowDialog::~C3DWindowDialog]" << endl;
}
// OnClose event:
void C3DWindowDialog::OnClose(wxCloseEvent& event)
{
// Send the event:
bool allow_close=true;
try {
mrptEventWindowClosed ev(m_win3D, true /* allow close */);
m_win3D->publishEvent(ev);
allow_close = ev.allow_close;
} catch(...){}
if (!allow_close) return; // Don't process this close event.
// cout << "[C3DWindowDialog::OnClose]" << endl;
// Set the m_hwnd=NULL in our parent object.
m_win3D->notifyChildWindowDestruction();
// Decrement number of windows:
WxSubsystem::CWXMainFrame::notifyWindowDestruction();
// Signal we are destroyed:
m_win3D->m_semWindowDestroyed.release();
event.Skip(); // keep processing by parent classes.
}
// Menu: Close
void C3DWindowDialog::OnMenuClose(wxCommandEvent& event)
{
Close();
}
// Menu: About
void C3DWindowDialog::OnMenuAbout(wxCommandEvent& event)
{
::wxMessageBox(_("3D Scene viewer\n Class gui::CDisplayWindow3D\n MRPT C++ library"),_("About..."));
}
void C3DWindowDialog::OnChar(wxKeyEvent& ev)
{
#if MRPT_HAS_OPENGL_GLUT
CMyGLCanvas_DisplayWindow3D::display3D_processKeyEvent(m_win3D, ev);
#endif
}
void C3DWindowDialog::OnResize(wxSizeEvent& event)
{
#if MRPT_HAS_OPENGL_GLUT
// Send the event:
if (m_win3D)
{
try {
m_win3D->publishEvent( mrptEventWindowResize(m_win3D,event.GetSize().GetWidth(),event.GetSize().GetHeight()));
} catch(...) {}
}
event.Skip(); // so it's processed by the wx system!
#endif
}
void C3DWindowDialog::clearTextMessages()
{
#if MRPT_HAS_OPENGL_GLUT
m_canvas->m_text_msgs.clearTextMessages();
#endif
}
void C3DWindowDialog::addTextMessage(
const double x_frac,
const double y_frac,
const std::string &text,
const mrpt::utils::TColorf &color,
const size_t unique_index,
const mrpt::opengl::TOpenGLFont font
)
{
#if MRPT_HAS_OPENGL_GLUT
m_canvas->m_text_msgs.addTextMessage( x_frac, y_frac, text,color,unique_index,font );
#endif
}
void C3DWindowDialog::addTextMessage(
const double x_frac,
const double y_frac,
const std::string &text,
const mrpt::utils::TColorf &color,
const std::string &font_name,
const double font_size,
const mrpt::opengl::TOpenGLFontStyle font_style,
const size_t unique_index,
const double font_spacing,
const double font_kerning,
const bool has_shadow,
const mrpt::utils::TColorf &shadow_color
)
{
#if MRPT_HAS_OPENGL_GLUT
m_canvas->m_text_msgs.addTextMessage( x_frac, y_frac, text,color, font_name, font_size, font_style, unique_index, font_spacing, font_kerning,has_shadow,shadow_color );
#endif
}
#endif // MRPT_HAS_WXWIDGETS
/*---------------------------------------------------------------
Constructor
---------------------------------------------------------------*/
CDisplayWindow3D::CDisplayWindow3D(
const std::string &windowCaption,
unsigned int initialWindowWidth,
unsigned int initialWindowHeight )
: CBaseGUIWindow(static_cast<void*>(this),300,399, windowCaption),
m_csAccess3DScene(),
m_grab_imgs_prefix(),
m_grab_imgs_idx(0),
m_is_capturing_imgs(false),
m_last_captured_img_cs("m_last_captured_img_cs"),
m_lastFullScreen (mrpt::system::now()),
m_last_FPS(10)
{
// static mrpt::utils::CStdOutStream oo;
// m_csAccess3DScene.m_debugOut = &oo;
m_3Dscene = COpenGLScene::Create();
CBaseGUIWindow::createWxWindow(initialWindowWidth,initialWindowHeight);
}
CDisplayWindow3DPtr CDisplayWindow3D::Create(
const std::string &windowCaption,
unsigned int initialWindowWidth,
unsigned int initialWindowHeight )
{
return CDisplayWindow3DPtr(new CDisplayWindow3D(windowCaption,initialWindowWidth,initialWindowHeight));
}
/*---------------------------------------------------------------
Destructor
---------------------------------------------------------------*/
CDisplayWindow3D::~CDisplayWindow3D( )
{
// get lock so we make sure nobody else is touching the window right now.
m_csAccess3DScene.enter();
m_csAccess3DScene.leave();
CBaseGUIWindow::destroyWxWindow();
}
/*---------------------------------------------------------------
resize
---------------------------------------------------------------*/
void CDisplayWindow3D::resize(
unsigned int width,
unsigned int height )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
if (!isOpen())
{
cerr << "[CDisplayWindow3D::setPos] Window closed!: " << m_caption << endl;
return;
}
// Send a request to destroy this object:
WxSubsystem::TRequestToWxMainThread *REQ = new WxSubsystem::TRequestToWxMainThread[1];
REQ->source3D = this;
REQ->OPCODE = 303;
REQ->x = width;
REQ->y = height;
WxSubsystem::pushPendingWxRequest( REQ );
#else
MRPT_UNUSED_PARAM(width);
MRPT_UNUSED_PARAM(height);
#endif
}
/*---------------------------------------------------------------
setPos
---------------------------------------------------------------*/
void CDisplayWindow3D::setPos( int x, int y )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
if (!isOpen())
{
cerr << "[CDisplayWindow3D::setPos] Window closed!: " << m_caption << endl;
return;
}
// Send a request to destroy this object:
WxSubsystem::TRequestToWxMainThread *REQ = new WxSubsystem::TRequestToWxMainThread[1];
REQ->source3D = this;
REQ->OPCODE = 302;
REQ->x = x;
REQ->y = y;
WxSubsystem::pushPendingWxRequest( REQ );
#else
MRPT_UNUSED_PARAM(x); MRPT_UNUSED_PARAM(y);
#endif
}
/*---------------------------------------------------------------
setWindowTitle
---------------------------------------------------------------*/
void CDisplayWindow3D::setWindowTitle( const std::string &str )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
if (!isOpen())
{
cerr << "[CDisplayWindow3D::setWindowTitle] Window closed!: " << m_caption << endl;
return;
}
// Send a request to destroy this object:
WxSubsystem::TRequestToWxMainThread *REQ = new WxSubsystem::TRequestToWxMainThread[1];
REQ->source3D = this;
REQ->OPCODE = 304;
REQ->str = str;
WxSubsystem::pushPendingWxRequest( REQ );
#else
MRPT_UNUSED_PARAM(str);
#endif
}
/*---------------------------------------------------------------
get3DSceneAndLock
---------------------------------------------------------------*/
opengl::COpenGLScenePtr& CDisplayWindow3D::get3DSceneAndLock( )
{
m_csAccess3DScene.enter();
return m_3Dscene;
}
/*---------------------------------------------------------------
unlockAccess3DScene
---------------------------------------------------------------*/
void CDisplayWindow3D::unlockAccess3DScene()
{
m_csAccess3DScene.leave();
}
/*---------------------------------------------------------------
forceRepaint
---------------------------------------------------------------*/
void CDisplayWindow3D::forceRepaint()
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
{
//win->Refresh(false); // Do not erase background
// We must do this from the wx thread!
// Send refresh request:
WxSubsystem::TRequestToWxMainThread *REQ = new WxSubsystem::TRequestToWxMainThread[1];
REQ->source3D = this;
REQ->OPCODE = 350;
WxSubsystem::pushPendingWxRequest( REQ );
}
#endif
}
/*---------------------------------------------------------------
setCameraElevationDeg
---------------------------------------------------------------*/
void CDisplayWindow3D::setCameraElevationDeg( float deg )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
win->m_canvas->cameraElevationDeg = deg;
#else
MRPT_UNUSED_PARAM(deg);
#endif
}
void CDisplayWindow3D::useCameraFromScene(bool useIt)
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
win->m_canvas->useCameraFromScene = useIt;
#else
MRPT_UNUSED_PARAM(useIt);
#endif
}
/*---------------------------------------------------------------
setCameraAzimuthDeg
---------------------------------------------------------------*/
void CDisplayWindow3D::setCameraAzimuthDeg( float deg )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
win->m_canvas->cameraAzimuthDeg = deg;
#else
MRPT_UNUSED_PARAM(deg);
#endif
}
/*---------------------------------------------------------------
setCameraPointingToPoint
---------------------------------------------------------------*/
void CDisplayWindow3D::setCameraPointingToPoint( float x,float y, float z )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
{
win->m_canvas->cameraPointingX = x;
win->m_canvas->cameraPointingY = y;
win->m_canvas->cameraPointingZ = z;
}
#else
MRPT_UNUSED_PARAM(x); MRPT_UNUSED_PARAM(y); MRPT_UNUSED_PARAM(z);
#endif
}
/*---------------------------------------------------------------
setCameraZoom
---------------------------------------------------------------*/
void CDisplayWindow3D::setCameraZoom( float zoom )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
win->m_canvas->cameraZoomDistance = zoom;
#else
MRPT_UNUSED_PARAM(zoom);
#endif
}
/*---------------------------------------------------------------
setCameraProjective
---------------------------------------------------------------*/
void CDisplayWindow3D::setCameraProjective( bool isProjective )
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
win->m_canvas->cameraIsProjective = isProjective;
#else
MRPT_UNUSED_PARAM(isProjective);
#endif
}
void CDisplayWindow3D::setMinRange(double new_min)
{
if (m_3Dscene)
{
mrpt::opengl::COpenGLViewportPtr gl_view = m_3Dscene->getViewport("main");
if (gl_view)
{
double m,M;
gl_view->getViewportClipDistances(m,M);
gl_view->setViewportClipDistances(new_min,M);
}
}
}
void CDisplayWindow3D::setMaxRange(double new_max)
{
if (m_3Dscene)
{
mrpt::opengl::COpenGLViewportPtr gl_view = m_3Dscene->getViewport("main");
if (gl_view)
{
double m,M;
gl_view->getViewportClipDistances(m,M);
gl_view->setViewportClipDistances(m,new_max);
}
}
}
float CDisplayWindow3D::getFOV() const
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
return win->m_canvas->cameraFOV;
#endif
return .0f;
}
void CDisplayWindow3D::setFOV(float v)
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
win->m_canvas->cameraFOV = v;
#endif
}
/*---------------------------------------------------------------
getCameraElevationDeg
---------------------------------------------------------------*/
float CDisplayWindow3D::getCameraElevationDeg() const
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
const C3DWindowDialog *win = (const C3DWindowDialog*) m_hwnd.get();
return win ? win->m_canvas->cameraElevationDeg : 0;
#else
return 0;
#endif
}
/*---------------------------------------------------------------
getCameraAzimuthDeg
---------------------------------------------------------------*/
float CDisplayWindow3D::getCameraAzimuthDeg() const
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
const C3DWindowDialog *win = (const C3DWindowDialog*) m_hwnd.get();
return win ? win->m_canvas->cameraAzimuthDeg : 0;
#else
return 0;
#endif
}
/*---------------------------------------------------------------
getCameraPointingToPoint
---------------------------------------------------------------*/
void CDisplayWindow3D::getCameraPointingToPoint( float &x,float &y, float &z ) const
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
const C3DWindowDialog *win = (const C3DWindowDialog*) m_hwnd.get();
if (win)
{
x = win->m_canvas->cameraPointingX;
y = win->m_canvas->cameraPointingY;
z = win->m_canvas->cameraPointingZ;
}
else
x=y=z=0;
#else
MRPT_UNUSED_PARAM(x); MRPT_UNUSED_PARAM(y); MRPT_UNUSED_PARAM(z);
#endif
}
/*---------------------------------------------------------------
getCameraZoom
---------------------------------------------------------------*/
float CDisplayWindow3D::getCameraZoom() const
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
const C3DWindowDialog *win = (const C3DWindowDialog*) m_hwnd.get();
return win ? win->m_canvas->cameraZoomDistance : 0;
#else
return 0;
#endif
}
/*---------------------------------------------------------------
isCameraProjective
---------------------------------------------------------------*/
bool CDisplayWindow3D::isCameraProjective() const
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
const C3DWindowDialog *win = (const C3DWindowDialog*) m_hwnd.get();
return win ? win->m_canvas->cameraIsProjective : true;
#else
return true;
#endif
}
/*---------------------------------------------------------------
getLastMousePosition
---------------------------------------------------------------*/
bool CDisplayWindow3D::getLastMousePosition(int &x, int &y) const
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
const C3DWindowDialog *win = (const C3DWindowDialog*) m_hwnd.get();
if (!win) return false;
win->m_canvas->getLastMousePosition(x,y);
return true;
#else
MRPT_UNUSED_PARAM(x); MRPT_UNUSED_PARAM(y);
return false;
#endif
}
/*---------------------------------------------------------------
getLastMousePositionRay
---------------------------------------------------------------*/
bool CDisplayWindow3D::getLastMousePositionRay(TLine3D &ray) const
{
int x,y;
if (getLastMousePosition(x,y))
{
m_csAccess3DScene.enter();
m_3Dscene->getViewport("main")->get3DRayForPixelCoord(x,y,ray);
m_csAccess3DScene.leave();
return true;
}
else return false;
}
/*---------------------------------------------------------------
setCursorCross
---------------------------------------------------------------*/
void CDisplayWindow3D::setCursorCross(bool cursorIsCross)
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
const C3DWindowDialog *win = (const C3DWindowDialog*) m_hwnd.get();
if (!win) return;
win->m_canvas->SetCursor( *(cursorIsCross ? wxCROSS_CURSOR : wxSTANDARD_CURSOR) );
#else
MRPT_UNUSED_PARAM(cursorIsCross);
#endif
}
/*---------------------------------------------------------------
grabImagesStart
---------------------------------------------------------------*/
void CDisplayWindow3D::grabImagesStart( const std::string &grab_imgs_prefix )
{
m_grab_imgs_prefix = grab_imgs_prefix;
m_grab_imgs_idx = 0;
}
/*---------------------------------------------------------------
grabImagesStop
---------------------------------------------------------------*/
void CDisplayWindow3D::grabImagesStop()
{
m_grab_imgs_prefix.clear();
}
/*---------------------------------------------------------------
grabImageGetNextFile
---------------------------------------------------------------*/
std::string CDisplayWindow3D::grabImageGetNextFile()
{
if ( m_grab_imgs_prefix.empty() )
return string();
else return format( "%s%06u.png",m_grab_imgs_prefix.c_str(), m_grab_imgs_idx++ );
}
/*---------------------------------------------------------------
captureImagesStart
---------------------------------------------------------------*/
void CDisplayWindow3D::captureImagesStart()
{
m_is_capturing_imgs = true;
}
/*---------------------------------------------------------------
captureImagesStop
---------------------------------------------------------------*/
void CDisplayWindow3D::captureImagesStop()
{
m_is_capturing_imgs = false;
}
/*---------------------------------------------------------------
getLastWindowImage
---------------------------------------------------------------*/
bool CDisplayWindow3D::getLastWindowImage( mrpt::utils::CImage &out_img ) const
{
bool ret;
{
mrpt::synch::CCriticalSectionLocker lock(& m_last_captured_img_cs );
if (m_last_captured_img)
{
out_img = *m_last_captured_img; // Copy the full image
ret = true;
}
else ret = false;
}
return ret;
}
/*---------------------------------------------------------------
getLastWindowImagePtr
---------------------------------------------------------------*/
CImagePtr CDisplayWindow3D::getLastWindowImagePtr() const
{
mrpt::synch::CCriticalSectionLocker lock(& m_last_captured_img_cs );
return m_last_captured_img;
}
/*---------------------------------------------------------------
addTextMessage
---------------------------------------------------------------*/
void CDisplayWindow3D::addTextMessage(
const double x_frac,
const double y_frac,
const std::string &text,
const mrpt::utils::TColorf &color,
const size_t unique_index,
const TOpenGLFont font
)
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
{
// Send request:
// Add a 2D text message:
// vector_x: [0]:x, [1]:y, [2,3,4]:R G B, "x": enum of desired font. "y": unique index, "str": String.
WxSubsystem::TRequestToWxMainThread *REQ = new WxSubsystem::TRequestToWxMainThread[1];
REQ->source3D = this;
REQ->OPCODE = 360;
REQ->str = text;
REQ->vector_x.resize(5);
REQ->vector_x[0] = x_frac;
REQ->vector_x[1] = y_frac;
REQ->vector_x[2] = color.R;
REQ->vector_x[3] = color.G;
REQ->vector_x[4] = color.B;
REQ->x = int(font);
REQ->y = int(unique_index);
WxSubsystem::pushPendingWxRequest( REQ );
}
#else
MRPT_UNUSED_PARAM(x_frac); MRPT_UNUSED_PARAM(y_frac); MRPT_UNUSED_PARAM(text);
MRPT_UNUSED_PARAM(color); MRPT_UNUSED_PARAM(unique_index); MRPT_UNUSED_PARAM(font);
#endif
}
/*---------------------------------------------------------------
addTextMessage
---------------------------------------------------------------*/
void CDisplayWindow3D::addTextMessage(
const double x_frac,
const double y_frac,
const std::string &text,
const mrpt::utils::TColorf &color,
const std::string &font_name,
const double font_size,
const mrpt::opengl::TOpenGLFontStyle font_style,
const size_t unique_index,
const double font_spacing,
const double font_kerning,
const bool draw_shadow,
const mrpt::utils::TColorf &shadow_color
)
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
{
// Send request:
// Add a 2D text message:
WxSubsystem::TRequestToWxMainThread *REQ = new WxSubsystem::TRequestToWxMainThread[1];
REQ->source3D = this;
REQ->OPCODE = 362;
REQ->str = text;
REQ->plotName = font_name;
REQ->vector_x.resize(12);
REQ->vector_x[0] = x_frac;
REQ->vector_x[1] = y_frac;
REQ->vector_x[2] = color.R;
REQ->vector_x[3] = color.G;
REQ->vector_x[4] = color.B;
REQ->vector_x[5] = font_size;
REQ->vector_x[6] = font_spacing;
REQ->vector_x[7] = font_kerning;
REQ->vector_x[8] = draw_shadow ? 1:0;
REQ->vector_x[9] = shadow_color.R;
REQ->vector_x[10] = shadow_color.G;
REQ->vector_x[11] = shadow_color.B;
REQ->x = int(font_style);
REQ->y = int(unique_index);
WxSubsystem::pushPendingWxRequest( REQ );
}
#else
MRPT_UNUSED_PARAM(x_frac);
MRPT_UNUSED_PARAM(y_frac);
MRPT_UNUSED_PARAM(text);
MRPT_UNUSED_PARAM(color);
MRPT_UNUSED_PARAM(font_name);
MRPT_UNUSED_PARAM(font_size);
MRPT_UNUSED_PARAM(font_style);
MRPT_UNUSED_PARAM(unique_index);
MRPT_UNUSED_PARAM(font_spacing);
MRPT_UNUSED_PARAM(font_kerning);
MRPT_UNUSED_PARAM(draw_shadow);
MRPT_UNUSED_PARAM(shadow_color);
#endif
}
/*---------------------------------------------------------------
clearTextMessages
---------------------------------------------------------------*/
void CDisplayWindow3D::clearTextMessages()
{
#if MRPT_HAS_WXWIDGETS && MRPT_HAS_OPENGL_GLUT
C3DWindowDialog *win = (C3DWindowDialog*) m_hwnd.get();
if (win)
{
// Send request:
WxSubsystem::TRequestToWxMainThread *REQ = new WxSubsystem::TRequestToWxMainThread[1];
REQ->source3D = this;
REQ->OPCODE = 361;
WxSubsystem::pushPendingWxRequest( REQ );
}
#endif
}
void CDisplayWindow3D::internal_setRenderingFPS(double FPS)
{
const double ALPHA = 0.99;
m_last_FPS = ALPHA*m_last_FPS+(1-ALPHA)*FPS;
}
// Called by CMyGLCanvas_DisplayWindow3D::OnPostRenderSwapBuffers
void CDisplayWindow3D::internal_emitGrabImageEvent(const std::string &fil)
{
const mrptEvent3DWindowGrabImageFile ev(this,fil);
publishEvent(ev);
}
// Returns the "main" viewport of the scene.
mrpt::opengl::COpenGLViewportPtr CDisplayWindow3D::getDefaultViewport()
{
m_csAccess3DScene.enter();
mrpt::opengl::COpenGLViewportPtr view = m_3Dscene->getViewport("main");
m_csAccess3DScene.leave();
return view;
}
void CDisplayWindow3D::setImageView(const mrpt::utils::CImage &img)
{
m_csAccess3DScene.enter();
mrpt::opengl::COpenGLViewportPtr view = m_3Dscene->getViewport("main");
view->setImageView(img);
m_csAccess3DScene.leave();
}
void CDisplayWindow3D::setImageView_fast(mrpt::utils::CImage &img)
{
m_csAccess3DScene.enter();
mrpt::opengl::COpenGLViewportPtr view = m_3Dscene->getViewport("main");
view->setImageView_fast(img);
m_csAccess3DScene.leave();
}
CDisplayWindow3DLocker::CDisplayWindow3DLocker(CDisplayWindow3D &win, mrpt::opengl::COpenGLScenePtr &out_scene_ptr) :
m_win(win)
{
out_scene_ptr = m_win.get3DSceneAndLock();
}
CDisplayWindow3DLocker::CDisplayWindow3DLocker(CDisplayWindow3D &win) :
m_win(win)
{
m_win.get3DSceneAndLock();
}
CDisplayWindow3DLocker::~CDisplayWindow3DLocker()
{
m_win.unlockAccess3DScene();
}
| 29.145177 | 168 | 0.620449 | [
"object",
"3d"
] |
99952e9e3d99c667bc4f92c5d92ca39976ddadb7 | 4,465 | cpp | C++ | Strategy/clsWeekMa.cpp | caicaiking/AbamaAnalysis | d3d370e59c7049be36e06da61e1a315ba58d049d | [
"MIT"
] | null | null | null | Strategy/clsWeekMa.cpp | caicaiking/AbamaAnalysis | d3d370e59c7049be36e06da61e1a315ba58d049d | [
"MIT"
] | null | null | null | Strategy/clsWeekMa.cpp | caicaiking/AbamaAnalysis | d3d370e59c7049be36e06da61e1a315ba58d049d | [
"MIT"
] | null | null | null | #include "clsWeekMa.h"
#include <QDateTime>
#include <QDebug>
#include <QApplication>
#include "clsSingleStockData.h"
#include "clsGetLastWorkDay.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
clsWeekMa::clsWeekMa(QObject *parent)
{
this->hsl =0;
average = 20;
db = new clsDBCreateTables(this);
}
QStringList clsWeekMa::findStockCodes()
{
QStringList codes;
if(lastCode.isEmpty())
codes= db->getStockCodes();
else
codes = lastCode;
QStringList stockCodes;
showProgress(tr("正在获取最后一个交易日日期"));
QString workDay =clsGetLastWorkDay::getLastWorkDate(
QDateTime::currentDateTime().addSecs(-1*18*60*60).date()).toString("yyyy-MM-dd");
int x=0;
foreach (QString strCode, codes)
{
x++;
//strCode ="sh603939";
showProgress(QString("现在进度 %1/%2--找到:%3股票.")
.arg(x).arg(codes.length()).arg(stockCodes.length()));
qApp->processEvents();
SingleStockDataList tmp = db->getStockData(strCode);
SingleStockDataList weekTmp = splitToWeek(tmp,QDate::fromString(workDay,"yyyy-MM-dd"));
if(weekTmp.length()< average)
continue;
if(QDate::currentDate().toString("yyyy-MM-dd")> workDay)
{
if(weekTmp.first().date < workDay)
continue;
}
else
{
if(weekTmp.first().date < QDateTime::currentDateTime().addSecs(-1*18*60*60).date().toString("yyyy-MM-dd"))
continue;
}
double sum=0;
for(int index=0; index< average; index++)
{
sum+=weekTmp.at(index).close;
}
double dblAve = sum/average;
if(dblAve > weekTmp.first().close)
continue;
if(dblAve < weekTmp.first().open)
continue;
if((weekTmp.first().close/weekTmp.first().open > 1.15) ||
(weekTmp.first().close/weekTmp.first().open < 1.02))
continue;
stockCodes.append(strCode);
qApp->processEvents();
}
showProgress(QString("查找已经完毕-共计 %1 股票").arg(stockCodes.length()));
return stockCodes;
}
SingleStockDataList clsWeekMa::splitToWeek(SingleStockDataList tmp,
QDate date)
{
int i=1;
i++;
SingleStockDataList weekTmp;
int dayOfWeek = date.dayOfWeek();
QDate thisWeekEnd = date.addDays(7-dayOfWeek);
QDate thisMonday = thisWeekEnd.addDays(-6);
// qDebug()<< thisWeekEnd;
// qDebug()<<thisMonday;
SingleStockDataList data;
for(int index = 0; index< tmp.length(); index++)
{
QString tmpDate = tmp.at(index).date;
if((tmpDate >= thisMonday.toString("yyyy-MM-dd"))
&& (tmpDate <= thisWeekEnd.toString("yyyy-MM-dd")))
{
data.append(tmp.at(index));
}
}
if(data.isEmpty())
return weekTmp;
SingleStockData weekData;
weekData.open = data.last().open;
weekData.close = data.first().close;
weekData.date = data.first().date;
weekData.zd = weekData.close - weekData.open;
if(weekData.open!=0.0)
weekData.zdf = weekData.close/weekData.open-1.0;
double sum=0;
for(int j =0; j< data.length(); j++)
{
sum+= data.at(j).cje;
}
weekData.cje = sum;
weekTmp.append(weekData);
qApp->processEvents();
if(i > average)
return weekTmp;
else
{
SingleStockDataList tmpWeek=splitToWeek(tmp,thisMonday.addDays(-1));
return weekTmp +tmpWeek;
}
}
void clsWeekMa::setCondition(QString condition)
{
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(condition.toUtf8(),
&error);
if(error.error == QJsonParseError::NoError)
{
if(doc.isObject())
{
QJsonObject obj = doc.object();
this->average = obj.value("average").toInt();
this->hsl = obj.value("hsl").toInt();
this->lastCode = obj.value("stocks").toString().split(",", QString::SkipEmptyParts);
}
}
}
void clsWeekMa::deepCopy(DoubleArray &dest, DoubleArray src)
{
if (src.len > dest.len)
{
delete[] const_cast<double *>(dest.data);
dest.data = new double[src.len];
}
memcpy(const_cast<double *>(dest.data), src.data, src.len * sizeof(double));
dest.len = src.len;
}
| 25.08427 | 118 | 0.578052 | [
"object"
] |
999b8c0775f302fae8ced0f85cd34771c37576c3 | 8,231 | hpp | C++ | src/libv/lma/lm/ba/create_hessian.hpp | bezout/LMA | 9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2 | [
"BSL-1.0"
] | 29 | 2015-12-08T12:07:30.000Z | 2022-01-08T21:23:01.000Z | src/libv/lma/lm/ba/create_hessian.hpp | ayumizll/LMA | e945452e12a8b05bd17400b46a20a5322aeda01d | [
"BSL-1.0"
] | 3 | 2016-07-11T16:23:48.000Z | 2017-04-05T13:33:00.000Z | src/libv/lma/lm/ba/create_hessian.hpp | bezout/LMA | 9555e41eed5f44690c5f6e3ea2d22d520ff1a9d2 | [
"BSL-1.0"
] | 8 | 2015-12-21T01:52:27.000Z | 2017-12-26T02:26:55.000Z | /**
\file
\author Datta Ramadasan
//==============================================================================
// Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
*/
#ifndef __LMA_OPT2_BA_CREATE_HESSIAN_HPP__
#define __LMA_OPT2_BA_CREATE_HESSIAN_HPP__
#include "make_type.hpp"
#include <libv/lma/ttt/mpl/for.hpp>
#include <libv/lma/lm/function/function.hpp>
#include <libv/lma/ttt/fusion/pair.hpp>
#include <libv/lma/ttt/mpl/naming.hpp>
#include <libv/lma/ttt/mpl/cat.hpp>
#include <boost/mpl/unique.hpp>
#include <boost/mpl/count_if.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/replace.hpp>
#include <boost/mpl/copy_if.hpp>
#include <boost/type_traits/is_same.hpp>
namespace lma
{
// extract parameters
template<class L1> using ListOfListOfParameters = mpl::transform<L1,Function<mpl::_1>>;
template<class A, class B> struct MakePair
{
typedef bf::pair<A,B> type;
};
template<class Int_, class List, class Int, class Result> struct CreatePairs3_
: mpl::push_back<
Result,
typename MakePair<typename mpl::at<List,Int_>::type,typename mpl::at<List,Int>::type>::type
> {};
template<class Int> using CreatePairs3 = CreatePairs3_<Int,mpl::_1,mpl::_2,mpl::_3>;
template<class List, class Int, class Result> struct CreatePairs2_ : For<Int::value+1,mpl::size<List>::value,List,CreatePairs3<Int>,Result> {};
template<class L> using CreatePairs2 = CreatePairs2_<L,mpl::_2,mpl::_3>;
template<class T> struct Unique : mpl::unique<T, boost::is_same<mpl::_1,mpl::_2> > {};// ne retire que les doublons contigus
// L ne doit pas contenir de doublon
template<class L> struct CreatePairs : For<0,mpl::size<L>::value,L,CreatePairs2<L>> {};
// get cross parameters
template<class L2> using CrossParameters = mpl::transform<typename mpl::transform<L2,Unique<mpl::_1>>::type,CreatePairs<mpl::_1>>;
template<class T> struct Double {};
template<class T> struct Single {};
template<class T, class L> struct SingleOrDouble : mpl::if_c<(mpl::count_if<L,boost::is_same<mpl::_1,T>>::value>1),Double<T>,Single<T>> {};
template<class L> struct DiagHessianFunctor : mpl::transform<typename Unique<L>::type,SingleOrDouble<mpl::_1,L>> {};
template<class L2> using ToSingleOrDouble = mpl::transform<L2,DiagHessianFunctor<mpl::_1>>;
template<class L3, class L4> using CatCrossAndDiag = mpl::transform<L4,L3,Cat<mpl::_1,mpl::_2>>;
template<class L, class T> struct AddIf;
template<class L, class A, class B> struct AddIf<L,bf::pair<A,B>>
: mpl::if_<
mpl::or_<
mpl::contains<L,bf::pair<A,B>>,
mpl::contains<L,bf::pair<B,A>>
>,
L,
typename mpl::push_back<L,bf::pair<A,B>>::type
> {};
template<class L, class T> struct AddIf<L,Single<T>>
: mpl::if_<
mpl::or_<
mpl::contains<L,Single<T>>,
mpl::contains<L,Double<T>>
>,
L,
typename mpl::push_front<L,Single<T>>::type
> {};
template<class L, class T> struct AddIf<L,Double<T>>
: mpl::if_<
boost::mpl::contains<L,Single<T>>,
typename mpl::replace<L,Single<T>,Double<T>>::type,
typename mpl::push_front<L,Double<T>>::type
> {};
template<class List, class Int, class Result> struct ForEachParameters : AddIf<Result,typename mpl::at<List,Int>::type> {};
template<class List, class Int, class Result> struct ForEachFunctor :
For<0,mpl::size<typename mpl::at<List,Int>::type>::value,typename mpl::at<List,Int>::type,ForEachParameters<mpl::_1,mpl::_2,mpl::_3>,Result> {};
template<class L> using TypesContainers = For<0,mpl::size<L>::value,L,ForEachFunctor<mpl::_1,mpl::_2,mpl::_3>>;
template<class T, class Flt> struct ToTable;
template<class A, class Flt> struct ToTable<Single<A>,Flt>// : MakeTupleTable<A,A,Flt> {
{
typedef bf::pair<bf::pair<A,A>,Table<A,A,Flt,Diagonal>> type;
};
template<class A, class Flt> struct ToTable<Double<A>,Flt>
{
typedef bf::pair<bf::pair<A,A>,Table<A,A,Flt,Symetric>> type;
};
template<class A, class B, class Flt> struct ToTable<bf::pair<A,B>,Flt> : MakeTupleTable<A,B,Flt> {};
template<class L, class Flt> using Containers = mpl::transform<L,ToTable<mpl::_1,Flt>>;
template<class Result, class A, class B> struct add_ { typedef Result type; };
template<class Result, class A> struct add_<Result,A,Single<A>> : mpl::push_back<Result,Single<A>> {};
template<class Result, class A> struct add_<Result,A,Double<A>> : mpl::push_back<Result,Double<A>> {};
template<class Result, class A, class B> struct add_<Result,A,bf::pair<A,B>> : mpl::push_back<Result,bf::pair<A,B>> {};
template<class Elt, class L, class Int, class Result> struct Ordering2 : add_<Result,Elt,typename mpl::at<L,Int>::type> {};
template<class L, class Ordre, class Int, class Result> struct Ordering : For<0,mpl::size<L>::value,L,Ordering2<typename mpl::at<Ordre,Int>::type,mpl::_1,mpl::_2,mpl::_3>,Result> {};
template<class L, class Ordre> struct Order : For<0,mpl::size<Ordre>::value,Ordre,Ordering<L,mpl::_1,mpl::_2,mpl::_3>> {};
template<class Keys, class T> struct IsKeyUs : mpl::false_ { };
template<class Keys, class Key, class P, class Q, class T, class Tag> struct IsKeyUs<Keys, bf::pair< Key, Table<P,Q,T,Tag> >>
: mpl::and_< mpl::contains<Keys,P>, mpl::contains<Keys,Q> > { };
template<class T> struct SymetricToDiagonal { typedef T type; };
template<class Key, class P, class T> struct SymetricToDiagonal<bf::pair< Key, Table<P,P,T,Diagonal> >> { typedef bf::pair< Key, Table<P,P,T,Symetric> > type; };
template<class H, class KeyUs> struct ListS
{
typedef typename mpl::copy_if<H, IsKeyUs<KeyUs,mpl::_1>>::type type0;
typedef typename mpl::transform<type0, SymetricToDiagonal<mpl::_1>>::type type;
};
template<class Bundle, class flt> struct ListH
{
typedef typename Bundle::ListFunction ListFunction;
typedef typename Bundle::ListeParam ListeParam;
typedef typename Bundle::ParamFonctor ParamFonctor;
typedef ListFunction L1;
// typedef typename CreateListParam<ListFunction,ParamFonctor>::type parameters;
typedef typename ListOfListOfParameters<L1>::type L2_;
typedef typename mpl::transform<L2_,ParamFonctor>::type L2;
typedef typename CrossParameters<L2>::type L3;
typedef typename ToSingleOrDouble<L2>::type L4;
typedef typename CatCrossAndDiag<L3,L4>::type L5;
typedef typename TypesContainers<L5>::type L6;
typedef typename Order<L6,ListeParam>::type L7;
typedef typename Containers<L7,flt>::type type;
static void disp()
{
std::cout << " Functors : " << ttt::name<L1>() << std::endl;
std::cout << " ListOfListOfParameters : " << ttt::name<L2>() << std::endl;
std::cout << " ToSingleOrDouble : " << ttt::name<L4>() << std::endl;
std::cout << std::endl;
std::cout << " CrossAndDiag : " << ttt::name<L5>() << std::endl;
std::cout << std::endl;
std::cout << " Types : " << ttt::name<L6>() << std::endl;
std::cout << " Order : " << ttt::name<L7>() << std::endl;
std::cout << " Containers : " << ttt::name<type>() << std::endl;
// std::cout << " Parmaeters " << ttt::name<ListeParam>() << std::endl;
}
};
}
namespace ttt
{
template<class T> struct Name<lma::Single<T>> { static std::string name() { return std::string("Single<") + ttt::name<T>() + ">"; } };
template<class T> struct Name<lma::Double<T>> { static std::string name() { return std::string("Double<") + ttt::name<T>() + ">"; } };
}
#endif | 40.348039 | 184 | 0.625926 | [
"transform"
] |
999d724465a807fbff1fcb1f64796f835b40498f | 3,839 | cpp | C++ | AnimalCooking/GpadKeySwitcher.cpp | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | null | null | null | AnimalCooking/GpadKeySwitcher.cpp | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | 23 | 2020-03-02T16:43:28.000Z | 2020-04-16T09:58:08.000Z | AnimalCooking/GpadKeySwitcher.cpp | TenByTen-Studios/AnimalCooking | 8bb22f426cdc819cefde16caa23d8eb045276be8 | [
"MIT"
] | null | null | null | #include "GpadKeySwitcher.h"
#include "Entity.h"
#include "Transform.h"
#include "GPadController.h"
#include "ConfigState.h"
void GpadKeySwitcher::init()
{
config::Options::GPadButtons& keys = SDLGame::instance()->getOptions().players_gPadButtons[player_];
Transform* t = GETCMP1_(Transform);
switchers_.reserve(7);
switchers_.emplace_back(new SwitcherGPad_Boolean(Vector2D(t->getPos().getX() + 310, t->getPos().getY() - t->getH() / 6), Vector2D(), SDLGame::instance()->getOptions().usePS4_symbols_[player_], Resources::TextureId::Config_XBoxOrPs4Icon, player_));
switchers_.emplace_back(new SwitcherGPad(Vector2D(t->getPos().getX(), t->getPos().getY()), Vector2D(), keys.ATTACK, Resources::TextureId::AttackText, player_));
switchers_.emplace_back(new SwitcherGPad(Vector2D(t->getPos().getX(), t->getPos().getY() + t->getH() / 6), Vector2D(), keys.OPEN, Resources::TextureId::OpenText, player_));
switchers_.emplace_back(new SwitcherGPad(Vector2D(t->getPos().getX(), t->getPos().getY() + t->getH() * 2 / 6), Vector2D(), keys.PICKUP, Resources::TextureId::PickUpText, player_));
switchers_.emplace_back(new SwitcherGPad(Vector2D(t->getPos().getX(), t->getPos().getY() + t->getH() * 3 / 6), Vector2D(), keys.FINISHER, Resources::TextureId::FinishText, player_));
switchers_.emplace_back(new SwitcherGPad(Vector2D(t->getPos().getX(), t->getPos().getY() + t->getH() * 4 / 6), Vector2D(), keys.NEXT, Resources::TextureId::NextText, player_));
switchers_.emplace_back(new SwitcherGPad(Vector2D(t->getPos().getX(), t->getPos().getY() + t->getH() * 5 / 6), Vector2D(), keys.PREVIOUS, Resources::TextureId::PreviousText, player_));
for (auto& s : switchers_)
s->setSize(Vector2D(buttonWidth_, buttonHeight_));
//Symbol 1 button con entity
/*
//Symbol 1 button
GPadController* gpCont = GPadController::instance();
if (gpCont->playerControllerConnected(0)) {
symbolPlayer1 = stage->addEntity();
stage->addToGroup(symbolPlayer1, ecs::GroupID::ui);
symbolPlayer1->addComponent<Transform>(
Vector2D(1200, 290),
Vector2D(), 94, 74, 0);
bb = symbolPlayer1->addComponent<ButtonBehaviour>(symbolCallback1, app);
symbolPlayer1->addComponent<ButtonChangeOnClick>(game_->getOptions().usePS4_symbols_[0]);
bcr = symbolPlayer1->addComponent<ButtonCheckRenderer>(nullptr, nullptr);
bcr->setCheckedAndUncheckedTextures(Resources::TextureId::Config_XBoxIcon, Resources::TextureId::Config_Ps4Icon);
bb->setButtonCheckRenderer(bcr);
}
//Symbol 2 button
symbolPlayer2 = nullptr;
if (gpCont->playerControllerConnected(1)) {
symbolPlayer2 = stage->addEntity();
stage->addToGroup(symbolPlayer2, ecs::GroupID::ui);
symbolPlayer2->addComponent<Transform>(
Vector2D(1770, 290),
Vector2D(), 94, 74, 0);
bb = symbolPlayer2->addComponent<ButtonBehaviour>(symbolCallback2, app);
symbolPlayer2->addComponent<ButtonChangeOnClick>(game_->getOptions().usePS4_symbols_[1]);
bcr = symbolPlayer2->addComponent<ButtonCheckRenderer>(nullptr, nullptr);
bcr->setCheckedAndUncheckedTextures(Resources::TextureId::Config_XBoxIcon, Resources::TextureId::Config_Ps4Icon);
bb->setButtonCheckRenderer(bcr);
}
*/
}
void GpadKeySwitcher::update()
{
if (!update_)
return;
if (navEnabled) {
GPadController* gpad = GPadController::instance();
if (gpad->isAnyButtonJustPressed()) {
if (gpad->playerPressed(player_, SDL_CONTROLLER_BUTTON_DPAD_DOWN)) focus++;
else if (gpad->playerPressed(player_, SDL_CONTROLLER_BUTTON_DPAD_UP)) focus--;
if (focus < 0) focus = 0;
else if (focus > 6) focus = 6;
}
}
if (focus >= 0) switchers_[focus]->update();
}
void GpadKeySwitcher::setFocushed(const int& delta)
{
if (delta == -1) update_ = !update_;
else focus = delta;
}
void GpadKeySwitcher::addFocushed(const int& delta)
{
if (!switchers_[focus]->getPlayerIsChoosing())
focus = (focus + 7 + delta) % 7;
}
| 44.639535 | 248 | 0.728575 | [
"transform"
] |
99a49cd4ada2ec7a1547bd894d748464b9dc6e85 | 498 | hpp | C++ | src/DeJong.hpp | limzykenneth/DeJong-lasercut | 31eea76f341706c4fa8f19796ea7c54f50e83861 | [
"BSD-3-Clause"
] | null | null | null | src/DeJong.hpp | limzykenneth/DeJong-lasercut | 31eea76f341706c4fa8f19796ea7c54f50e83861 | [
"BSD-3-Clause"
] | null | null | null | src/DeJong.hpp | limzykenneth/DeJong-lasercut | 31eea76f341706c4fa8f19796ea7c54f50e83861 | [
"BSD-3-Clause"
] | null | null | null | //
// DeJong.hpp
// DeJong
//
// Created by Kenneth Lim on 24/10/2015.
//
//
#ifndef DeJong_hpp
#define DeJong_hpp
#include <stdio.h>
#include <vector>
#include "ofMain.h"
class DeJong{
public:
int intensity;
int iterations;
double maxDensity;
int N;
double xSeed;
double ySeed;
double x;
double y;
DeJong();
void clear();
void seed();
void populate(int samples);
void reseed();
void plot(int samples);
};
#endif /* DeJong_hpp */
| 13.833333 | 41 | 0.606426 | [
"vector"
] |
99a88b943854fd359396c73252573103cba183c9 | 3,002 | cpp | C++ | nau/src/nau/geometry/square.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 29 | 2015-09-16T22:28:30.000Z | 2022-03-11T02:57:36.000Z | nau/src/nau/geometry/square.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 1 | 2017-03-29T13:32:58.000Z | 2017-03-31T13:56:03.000Z | nau/src/nau/geometry/square.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 10 | 2015-10-15T14:20:15.000Z | 2022-02-17T10:37:29.000Z | #include "nau/geometry/square.h"
#include "nau/math/vec3.h"
#include "nau/geometry/vertexData.h"
#include "nau/material/materialGroup.h"
using namespace nau::geometry;
using namespace nau::render;
using namespace nau::material;
using namespace nau::math;
Square::Square(void) : Primitive() {
float n = 1.0f;
std::shared_ptr<std::vector<VertexData::Attr>> vertices =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(4));
std::shared_ptr<std::vector<VertexData::Attr>> tangent =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(4));
std::shared_ptr<std::vector<VertexData::Attr>> textureCoords =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(4));
std::shared_ptr<std::vector<VertexData::Attr>> normals =
std::shared_ptr<std::vector<VertexData::Attr>>(new std::vector<VertexData::Attr>(4));
//BOTTOM
vertices->at (Square::TOP_LEFT).set (-n, 0.0f, n);
vertices->at (Square::TOP_RIGHT).set ( n, 0.0f, n);
vertices->at (Square::BOTTOM_RIGHT).set ( n, 0.0f, -n);
vertices->at (Square::BOTTOM_LEFT).set (-n, 0.0f, -n);
tangent->at (Square::TOP_LEFT).set (0.0f, 0.0f, -1.0f);
tangent->at (Square::TOP_RIGHT).set (0.0f, 0.0f, -1.0f);
tangent->at (Square::BOTTOM_RIGHT).set (0.0f, 0.0f, -1.0f);
tangent->at (Square::BOTTOM_LEFT).set (0.0f, 0.0f, -1.0f);
textureCoords->at (Square::TOP_LEFT).set (0.0f, n, 0.0f);
textureCoords->at (Square::TOP_RIGHT).set (n, n, 0.0f);
textureCoords->at (Square::BOTTOM_RIGHT).set (n, 0.0f, 0.0f);
textureCoords->at (Square::BOTTOM_LEFT).set (0.0f, 0.0f, 0.0f);
normals->at (Square::TOP_LEFT).set ( 0.0f, 1.0f, 0.0f, 0.0f);
normals->at (Square::TOP_RIGHT).set ( 0.0f, 1.0f, 0.0f, 0.0f);
normals->at (Square::BOTTOM_RIGHT).set ( 0.0f, 1.0f, 0.0f, 0.0f);
normals->at (Square::BOTTOM_LEFT).set ( 0.0f, 1.0f, 0.0f, 0.0f);
std::shared_ptr<VertexData> &vertexData = getVertexData();
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("position")), vertices);
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("texCoord0")), textureCoords);
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("tangent")), tangent);
vertexData->setDataFor (VertexData::GetAttribIndex(std::string("normal")), normals);
std::shared_ptr<MaterialGroup> aMaterialGroup = MaterialGroup::Create(this, "__Light Grey");
std::shared_ptr<std::vector<unsigned int>> indices =
std::shared_ptr<std::vector<unsigned int>>(new std::vector<unsigned int>(6));
//BOTTOM
indices->at (0)= Square::BOTTOM_LEFT;
indices->at (1)= Square::TOP_LEFT;
indices->at (2)= Square::TOP_RIGHT;
indices->at (3)= Square::BOTTOM_RIGHT;
indices->at (4)= Square::BOTTOM_LEFT;
indices->at (5)= Square::TOP_RIGHT;
aMaterialGroup->setIndexList (indices);
addMaterialGroup (aMaterialGroup);
}
Square::~Square(void) {
}
std::string
Square::getClassName() {
return "Square";
}
void
Square::build() {
}
| 32.630435 | 94 | 0.688541 | [
"geometry",
"render",
"vector"
] |
99ab736f3c0828f17c0399b81f6f824ab94cf41f | 672 | cpp | C++ | leetcode.com/0682 Baseball Game/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2020-08-20T11:02:49.000Z | 2020-08-20T11:02:49.000Z | leetcode.com/0682 Baseball Game/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | null | null | null | leetcode.com/0682 Baseball Game/main.cpp | sky-bro/AC | 29bfa3f13994612887e18065fa6e854b9a29633d | [
"MIT"
] | 1 | 2022-01-01T23:23:13.000Z | 2022-01-01T23:23:13.000Z | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int calPoints(vector<string>& ops) {
vector<int> scores;
int n = 0, sum = 0;
for (const string& op : ops) {
if (op == "C") {
sum -= scores.back();
scores.pop_back();
--n;
} else if (op == "D") {
scores.push_back(scores.back()*2);
sum += scores.back();
++n;
} else if (op == "+") {
scores.push_back(scores[n-1]+scores[n-2]);
sum += scores.back();
++n;
} else {
scores.push_back(stoi(op));
sum += scores.back();
++n;
}
}
return sum;
}
}; | 21 | 50 | 0.471726 | [
"vector"
] |
99add7b340459c78e5f354e3aa74c1d51c6458e2 | 13,499 | hpp | C++ | include/libsharedmemory/libsharedmemory.hpp | kyr0/libsharedmemory | 083315bb64f6abeeac4acbbc2545627ae7dd6f4f | [
"MIT"
] | 5 | 2021-12-15T06:54:55.000Z | 2022-03-27T15:59:28.000Z | include/libsharedmemory/libsharedmemory.hpp | kyr0/libsharedmemory | 083315bb64f6abeeac4acbbc2545627ae7dd6f4f | [
"MIT"
] | null | null | null | include/libsharedmemory/libsharedmemory.hpp | kyr0/libsharedmemory | 083315bb64f6abeeac4acbbc2545627ae7dd6f4f | [
"MIT"
] | null | null | null |
#ifndef INCLUDE_LIBSHAREDMEMORY_HPP_
#define INCLUDE_LIBSHAREDMEMORY_HPP_
#include <ostream>
#define LIBSHAREDMEMORY_VERSION_MAJOR 0
#define LIBSHAREDMEMORY_VERSION_MINOR 0
#define LIBSHAREDMEMORY_VERSION_PATCH 9
#include <cstdint>
#include <cstring>
#include <string>
#include <unistd.h>
#include <iostream>
#include <cstddef> // nullptr_t, ptrdiff_t, std::size_t
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#endif
namespace lsm {
enum Error {
kOK = 0,
kErrorCreationFailed = 100,
kErrorMappingFailed = 110,
kErrorOpeningFailed = 120,
};
enum DataType {
kMemoryChanged = 1,
kMemoryTypeString = 2,
kMemoryTypeFloat = 4,
kMemoryTypeDouble = 8,
};
// byte sizes of memory layout
const size_t bufferSizeSize = 4; // size_t takes 4 bytes
const size_t sizeOfOneFloat = 4; // float takes 4 bytes
const size_t sizeOfOneChar = 1; // char takes 1 byte
const size_t sizeOfOneDouble = 8; // double takes 8 bytes
const size_t flagSize = 1; // char takes 1 byte
class Memory {
public:
// path should only contain alpha-numeric characters, and is normalized
// on linux/macOS.
explicit Memory(std::string path, std::size_t size, bool persist);
// create a shared memory area and open it for writing
inline Error create() { return createOrOpen(true); };
// open an existing shared memory for reading
inline Error open() { return createOrOpen(false); };
inline std::size_t size() { return _size; };
inline const std::string &path() { return _path; }
inline void *data() { return _data; }
void destroy();
void close();
~Memory();
private:
Error createOrOpen(bool create);
std::string _path;
void *_data = nullptr;
std::size_t _size = 0;
bool _persist = true;
#if defined(_WIN32)
HANDLE _handle;
#else
int _fd = -1;
#endif
};
// Windows shared memory implementation
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#include <io.h> // CreateFileMappingA, OpenFileMappingA, etc.
Memory::Memory(const std::string path, const std::size_t size, const bool persist) : _path(path), _size(size), _persist(persist) {};
Error Memory::createOrOpen(const bool create) {
if (create) {
DWORD size_high_order = 0;
DWORD size_low_order = static_cast<DWORD>(size_);
_handle = CreateFileMappingA(INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
size_high_order, size_low_order,
_path.c_str() // name of mapping object
);
if (!_handle) {
return kErrorCreationFailed;
}
} else {
_handle = OpenFileMappingA(FILE_MAP_READ, // read access
FALSE, // do not inherit the name
_path.c_str() // name of mapping object
);
// TODO: Windows has no default support for shared memory persistence
// see: destroy() to implement that
if (!_handle) {
return kErrorOpeningFailed;
}
}
// TODO: might want to use GetWriteWatch to get called whenever
// the memory section changes
// https://docs.microsoft.com/de-de/windows/win32/api/memoryapi/nf-memoryapi-getwritewatch?redirectedfrom=MSDN
const DWORD access = create ? FILE_MAP_ALL_ACCESS : FILE_MAP_READ;
_data = MapViewOfFile(_handle, access, 0, 0, _size);
if (!_data) {
return kErrorMappingFailed;
}
return kOK;
}
void Memory::destroy() {
// TODO: Windows needs priviledges to define a shared memory (file mapping)
// OBJ_PERMANENT; furthermore, ZwCreateSection would need to be used.
// Instead of doing this; saving a file here (by name, temp dir)
// and reading memory from file in createOrOpen seems more suitable.
// Especially, because files can be removed on reboot using:
// MoveFileEx() with the MOVEFILE_DELAY_UNTIL_REBOOT flag and lpNewFileName
// set to NULL.
}
void Memory::close() {
if (_data) {
UnmapViewOfFile(_data);
_data = nullptr;
}
CloseHandle(_handle);
}
Memory::~Memory() {
close();
if (!_persist) {
destroy();
}
}
#endif // defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#if defined(__APPLE__) || defined(__linux__) || defined(__unix__) || defined(_POSIX_VERSION) || defined(__ANDROID__)
#include <fcntl.h> // for O_* constants
#include <sys/mman.h> // mmap, munmap
#include <sys/stat.h> // for mode constants
#include <unistd.h> // unlink
#if defined(__APPLE__)
#include <errno.h>
#endif // __APPLE__
#include <stdexcept>
inline Memory::Memory(const std::string path, const std::size_t size, const bool persist) : _size(size), _persist(persist) {
_path = "/" + path;
};
inline Error Memory::createOrOpen(const bool create) {
if (create) {
// shm segments persist across runs, and macOS will refuse
// to ftruncate an existing shm segment, so to be on the safe
// side, we unlink it beforehand.
const int ret = shm_unlink(_path.c_str());
if (ret < 0) {
if (errno != ENOENT) {
return kErrorCreationFailed;
}
}
}
const int flags = create ? (O_CREAT | O_RDWR) : O_RDONLY;
_fd = shm_open(_path.c_str(), flags, 0755);
if (_fd < 0) {
if (create) {
return kErrorCreationFailed;
} else {
return kErrorOpeningFailed;
}
}
if (create) {
// this is the only way to specify the size of a
// newly-created POSIX shared memory object
int ret = ftruncate(_fd, _size);
if (ret != 0) {
return kErrorCreationFailed;
}
}
const int prot = create ? (PROT_READ | PROT_WRITE) : PROT_READ;
_data = mmap(nullptr, // addr
_size, // length
prot, // prot
MAP_SHARED, // flags
_fd, // fd
0 // offset
);
if (_data == MAP_FAILED) {
return kErrorMappingFailed;
}
if (!_data) {
return kErrorMappingFailed;
}
return kOK;
}
inline void Memory::destroy() { shm_unlink(_path.c_str()); }
inline void Memory::close() {
munmap(_data, _size);
::close(_fd);
}
inline Memory::~Memory() {
close();
if (!_persist) {
destroy();
}
}
#endif // defined(__APPLE__) || defined(__linux__) || defined(__unix__) || defined(_POSIX_VERSION) || defined(__ANDROID__)
class SharedMemoryReadStream {
public:
SharedMemoryReadStream(const std::string name, const std::size_t bufferSize, const bool isPersistent):
_memory(name, bufferSize, isPersistent) {
if (_memory.open() != kOK) {
throw "Shared memory segment could not be opened.";
}
}
inline char readFlags() {
char* memory = (char*) _memory.data();
return memory[0];
}
inline void close() { _memory.close(); }
inline size_t readSize(char dataType) {
void *memory = _memory.data();
std::size_t size = 0;
// TODO(kyr0): should be clarified why we need to use size_t there
// for the size to be received correctly, but in float, we need int
// Might be prone to undefined behaviour; should be tested
// with various compilers; otherwise use memcpy() for the size
// and align the memory with one cast.
if (dataType & kMemoryTypeDouble) {
size_t *intMemory = (size_t *)memory;
// copy size data to size variable
std::memcpy(&size, &intMemory[flagSize], bufferSizeSize);
}
if (dataType & kMemoryTypeFloat) {
int* intMemory = (int*) memory;
// copy size data to size variable
std::memcpy(&size, &intMemory[flagSize], bufferSizeSize);
}
if (dataType & kMemoryTypeString) {
char* charMemory = (char*) memory;
// copy size data to size variable
std::memcpy(&size, &charMemory[flagSize], bufferSizeSize);
}
return size;
}
inline size_t readLength(char dataType) {
size_t size = readSize(dataType);
if (dataType & kMemoryTypeString) {
return size / sizeOfOneChar;
}
if (dataType & kMemoryTypeFloat) {
return size / sizeOfOneFloat;
}
if (dataType & kMemoryTypeDouble) {
return size / sizeOfOneDouble;
}
return 0;
}
/**
* @brief Returns a doible* read from shared memory
* Caller has the obligation to call delete [] on the returning float*.
*
* @return float*
*/
// TODO: might wanna use templated functions here like: <T> readNumericArray()
inline double* readDoubleArray() {
void *memory = _memory.data();
std::size_t size = readSize(kMemoryTypeDouble);
double* typedMemory = (double*) memory;
// allocating memory on heap (this might leak)
double *data = new double[size / sizeOfOneDouble]();
// copy to data buffer
std::memcpy(data, &typedMemory[flagSize + bufferSizeSize], size);
return data;
}
/**
* @brief Returns a float* read from shared memory
* Caller has the obligation to call delete [] on the returning float*.
*
* @return float*
*/
inline float* readFloatArray() {
void *memory = _memory.data();
float *typedMemory = (float *)memory;
std::size_t size = readSize(kMemoryTypeFloat);
// allocating memory on heap (this might leak)
float *data = new float[size / sizeOfOneFloat]();
// copy to data buffer
std::memcpy(data, &typedMemory[flagSize + bufferSizeSize], size);
return data;
}
inline std::string readString() {
char* memory = (char*) _memory.data();
std::size_t size = readSize(kMemoryTypeString);
// create a string that copies the data from memory
std::string data =
std::string(&memory[flagSize + bufferSizeSize], size);
return data;
}
private:
Memory _memory;
};
class SharedMemoryWriteStream {
public:
SharedMemoryWriteStream(const std::string name, const std::size_t bufferSize, const bool isPersistent):
_memory(name, bufferSize, isPersistent) {
if (_memory.create() != kOK) {
throw "Shared memory segment could not be created.";
}
}
inline void close() {
_memory.close();
}
// https://stackoverflow.com/questions/18591924/how-to-use-bitmask
inline char getWriteFlags(const char type,
const char currentFlags) {
char flags = type;
if ((currentFlags & (kMemoryChanged)) == kMemoryChanged) {
// disable flag, leave rest untouched
flags &= ~kMemoryChanged;
} else {
// enable flag, leave rest untouched
flags ^= kMemoryChanged;
}
return flags;
}
inline void write(const std::string& string) {
char* memory = (char*) _memory.data();
// 1) copy change flag into buffer for change detection
char flags = getWriteFlags(kMemoryTypeString, ((char*) _memory.data())[0]);
std::memcpy(&memory[0], &flags, flagSize);
// 2) copy buffer size into buffer (meta data for deserializing)
const char *stringData = string.data();
const std::size_t bufferSize = string.size();
// write data
std::memcpy(&memory[flagSize], &bufferSize, bufferSizeSize);
// 3) copy stringData into memory buffer
std::memcpy(&memory[flagSize + bufferSizeSize], stringData, bufferSize);
}
// TODO: might wanna use template function here for numeric arrays,
// like void writeNumericArray(<T*> data, std::size_t length)
inline void write(float* data, std::size_t length) {
float* memory = (float*) _memory.data();
char flags = getWriteFlags(kMemoryTypeFloat, ((char*) _memory.data())[0]);
std::memcpy(&memory[0], &flags, flagSize);
// 2) copy buffer size into buffer (meta data for deserializing)
const std::size_t bufferSize = length * sizeOfOneFloat;
std::memcpy(&memory[flagSize], &bufferSize, bufferSizeSize);
// 3) copy float* into memory buffer
std::memcpy(&memory[flagSize + bufferSizeSize], data, bufferSize);
}
inline void write(double* data, std::size_t length) {
double* memory = (double*) _memory.data();
char flags = getWriteFlags(kMemoryTypeDouble, ((char*) _memory.data())[0]);
std::memcpy(&memory[0], &flags, flagSize);
// 2) copy buffer size into buffer (meta data for deserializing)
const std::size_t bufferSize = length * sizeOfOneDouble;
std::memcpy(&memory[flagSize], &bufferSize, bufferSizeSize);
// 3) copy double* into memory buffer
std::memcpy(&memory[flagSize + bufferSizeSize], data, bufferSize);
}
inline void destroy() {
_memory.destroy();
}
private:
Memory _memory;
};
}; // namespace lsm
#endif // INCLUDE_LIBSHAREDMEMORY_HPP_ | 29.218615 | 132 | 0.610786 | [
"object"
] |
99b06c1e9c015f9a6b6a5d1d9b84553d995795a1 | 2,857 | cpp | C++ | Sid's Levels/DPP/Graphs/Number Of Islands.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Levels/DPP/Graphs/Number Of Islands.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Levels/DPP/Graphs/Number Of Islands.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | //My soln -> 47/48 cases -> TLE
class Solution {
public:
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LASKHMI NARAYANA, BHADRE NARAYANA
int dirx[4] = {0, 1, 0, -1};
int diry[4] = {1, 0, -1, 0};
bool isValid(int r, int c, vector<vector<int>> visited, int m, int n, vector<vector<char>> grid)
{
if(r < 0 || c < 0 || r >= m || c >= n || visited[r][c] || grid[r][c] == '0')
return false;
return true;
}
void travel(int r, int c, vector<vector<int>> &visited, vector<vector<char>> grid, int m, int n)
{
queue<pair<int, int> > q;
q.push(make_pair(r, c));
visited[r][c] = true;
while(!q.empty())
{
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int i = 0; i < 4; i++)
{
int nx = x + dirx[i];
int ny = y + diry[i];
if(isValid(nx, ny, visited, m, n, grid))
{
visited[nx][ny] = true;
q.push(make_pair(nx, ny));
}
}
}
}
int numIslands(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> visited(m, vector<int>(n, false));
int islands = 0;
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n; j++)
{
if(grid[i][j] == '1' && !visited[i][j])
{
travel(i, j, visited, grid, m, n);
islands++;
}
}
}
return islands;
}
};
//Editorial
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0;
bool visited[1000][1000] ;
for(int i = 0; i < m; i++)
{
for(int j =0 ;j < n; j++)
visited[i][j] = false;
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1' && visited[i][j] == false) {
islands++;
eraseIslands(grid, i, j, visited);
}
}
}
return islands;
}
private:
void eraseIslands(vector<vector<char>>& grid, int i, int j, bool visited[][1000]) {
int m = grid.size(), n = grid[0].size();
if (i < 0 || i == m || j < 0 || j == n || grid[i][j] == '0' || visited[i][j] == true) {
return;
}
visited[i][j] = true;
eraseIslands(grid, i - 1, j, visited);
eraseIslands(grid, i + 1, j, visited);
eraseIslands(grid, i, j - 1, visited);
eraseIslands(grid, i, j + 1, visited);
}
};
| 31.054348 | 100 | 0.418971 | [
"vector"
] |
99b1700f09587d2ef91f67d7cf5e13f932d0505c | 2,955 | cpp | C++ | 202118/dec202118_1.cpp | jibsen/aocpp2021 | d3a26e7207de51bf6eeb0d6bcc8eddb2174f6a44 | [
"MIT"
] | null | null | null | 202118/dec202118_1.cpp | jibsen/aocpp2021 | d3a26e7207de51bf6eeb0d6bcc8eddb2174f6a44 | [
"MIT"
] | null | null | null | 202118/dec202118_1.cpp | jibsen/aocpp2021 | d3a26e7207de51bf6eeb0d6bcc8eddb2174f6a44 | [
"MIT"
] | null | null | null | //
// Advent of Code 2021, day 18, part one
//
// I feel like there should be some elegant solution using std::variant
// here, but since all the numbers are non-negative and the input does not
// grow exponentially, we opt for the simple representation as a vector of
// int using negative numbers for opening and closing parenthesis.
#include <iostream>
#include <string>
#include <vector>
constexpr int open_par = -1;
constexpr int close_par = -2;
using Number = std::vector<int>;
auto read_number(std::string_view sv)
{
Number res;
for (auto ch : sv) {
switch (ch) {
case '[':
res.push_back(open_par);
break;
case ']':
res.push_back(close_par);
break;
case ',':
break;
default:
res.push_back(ch - '0');
break;
}
}
return res;
}
void print_number(const Number &num)
{
for (int n : num) {
switch(n) {
case open_par:
std::cout << '[';
break;
case close_par:
std::cout << ']';
break;
default:
std::cout << n << ',';
}
}
std::cout << '\n';
}
bool explode_number(Number &num)
{
int nesting = 0;
for (std::size_t i = 0; i < num.size(); ++i) {
switch (num[i]) {
case open_par:
++nesting;
break;
case close_par:
--nesting;
break;
default:
if (nesting >= 5) {
for (std::size_t j = i - 1; j > 0; --j) {
if (num[j] >= 0) {
num[j] += num[i];
break;
}
}
for (std::size_t j = i + 2; j < num.size(); ++j) {
if (num[j] >= 0) {
num[j] += num[i + 1];
break;
}
}
num[i - 1] = 0;
num.erase(num.begin() + i, num.begin() + i + 3);
return true;
}
}
}
return false;
}
bool split_number(Number &num)
{
for (std::size_t i = 0; i < num.size(); ++i) {
if (num[i] > 9) {
num.insert(num.begin() + i + 1, {num[i] / 2, (num[i] + 1) / 2, close_par});
num[i] = open_par;
return true;
}
}
return false;
}
void reduce_number(Number &num)
{
while (explode_number(num) || split_number(num)) {
// nothing
}
}
Number add_numbers(const Number &lhs, const Number &rhs)
{
Number res;
res.reserve(lhs.size() + rhs.size() + 2);
res.push_back(open_par);
res.insert(res.end(), lhs.begin(), lhs.end());
res.insert(res.end(), rhs.begin(), rhs.end());
res.push_back(close_par);
reduce_number(res);
return res;
}
std::size_t magnitude_internal(const Number &num, int &pos)
{
if (num[pos] >= 0) {
return static_cast<std::size_t>(num[pos++]);
}
++pos;
std::size_t left_mag = magnitude_internal(num, pos);
std::size_t right_mag = magnitude_internal(num, pos);
++pos;
return 3 * left_mag + 2 * right_mag;
}
std::size_t magnitude(const Number &num)
{
int pos = 0;
return magnitude_internal(num, pos);
}
int main()
{
Number res;
for (std::string line; std::getline(std::cin, line); ) {
auto num = read_number(line);
if (res.empty()) {
res = num;
}
else {
res = add_numbers(res, num);
}
}
print_number(res);
std::cout << magnitude(res) << '\n';
}
| 16.789773 | 78 | 0.587817 | [
"vector"
] |
99b1dddb62552fb95d244d88515c915e2eb72cd1 | 15,027 | hpp | C++ | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/widgets/TextArea.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 12 | 2020-06-25T13:10:17.000Z | 2022-01-27T01:48:26.000Z | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/widgets/TextArea.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 2 | 2021-05-23T05:02:48.000Z | 2021-05-24T11:15:56.000Z | Middlewares/ST/touchgfx_backup/framework/include/touchgfx/widgets/TextArea.hpp | koson/car-dash | 7be8f02a243d43b4fd9fd33b0a160faa5901f747 | [
"MIT"
] | 7 | 2020-08-27T08:23:49.000Z | 2021-09-19T12:54:30.000Z | /**
******************************************************************************
* This file is part of the TouchGFX 4.13.0 distribution.
*
* <h2><center>© Copyright (c) 2019 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#ifndef TEXTAREA_HPP
#define TEXTAREA_HPP
#include <touchgfx/Font.hpp>
#include <touchgfx/FontManager.hpp>
#include <touchgfx/TypedText.hpp>
#include <touchgfx/Unicode.hpp>
#include <touchgfx/hal/Types.hpp>
#include <touchgfx/lcd/LCD.hpp>
#include <touchgfx/widgets/Widget.hpp>
namespace touchgfx
{
/**
* @class TextArea TextArea.hpp touchgfx/widgets/TextArea.hpp
*
* @brief This widget is capable of showing a text area on the screen.
*
* This widget is capable of showing a text area on the screen. A TextArea can display a
* TypedText. Optional configuration include text color.
*
* Example text_example shows how to use a TextArea.
*
* @note A TextArea just holds a pointer to the text displayed. The developer must ensure that the
* pointer remains valid when drawing.
*
* @see TypedText for information about text
* @see TextAreaWithOneWildcard, @see TextAreaWithTwoWildcards for displaying texts containing
* wildcards.
*/
class TextArea : public Widget
{
public:
/**
* @fn TextArea::TextArea()
*
* @brief Default constructor.
*
* Create an empty TextArea. Default color is black.
*/
TextArea()
: Widget(), typedText(TYPED_TEXT_INVALID), color(0), linespace(0), alpha(255), indentation(0), rotation(TEXT_ROTATE_0), wideTextAction(WIDE_TEXT_NONE)
{
}
/**
* @fn virtual Rect TextArea::getSolidRect() const
*
* @brief Gets solid rectangle.
*
* Gets solid rectangle.
*
* @return the largest solid rectangle for this widget. For a TextArea, this is an empty area.
*/
virtual Rect getSolidRect() const
{
return Rect(0, 0, 0, 0);
}
/**
* @fn inline void TextArea::setColor(colortype color)
*
* @brief Sets the color of the text.
*
* Sets the color of the text.
*
* @param color The color to use.
*/
inline void setColor(colortype color)
{
this->color = color;
}
/**
* @fn inline colortype TextArea::getColor() const
*
* @brief Gets the color of the text.
*
* Gets the color of the text.
*
* @return The color to used for drawing the text.
*/
inline colortype getColor() const
{
return color;
}
/**
* @fn void TextArea::setAlpha(uint8_t alpha)
*
* @brief Sets the alpha value of the text.
*
* Sets the alpha value of the text.
*
* @param alpha The alpha value. 255 = completely solid. 0 = invisible.
*/
void setAlpha(uint8_t alpha)
{
this->alpha = alpha;
}
/**
* @fn uint8_t TextArea::getAlpha() const
*
* @brief Gets the alpha value of the text.
*
* Gets the alpha value of the text.
*
* @return The alpha value. 255 = completely solid. 0 = invisible.
*/
uint8_t getAlpha() const
{
return alpha;
}
/**
* @fn virtual void TextArea::setBaselineY(int16_t baselineY)
*
* @brief Adjusts the TextArea y coordinate to place the text at the specified baseline.
*
* Adjusts the text areas y coordinate so the text will have its baseline at the
* specified value. The placements is relative to the specified TypedText so if this
* changes you have to set the baseline again. Note that setTypedText must be called
* prior to setting the baseline.
*
* @param baselineY The y coordinate of the baseline.
*/
virtual void setBaselineY(int16_t baselineY)
{
setY(baselineY - getTypedText().getFont()->getFontHeight());
}
/**
* @fn virtual void TextArea::setXBaselineY(int16_t x, int16_t baselineY)
*
* @brief Adjusts the TextArea y coordinate to place the text at the specified baseline.
*
* Adjusts the text areas y coordinate so the text will have its baseline at the
* specified value. The placements is relative to the specified TypedText so if this
* changes you have to set the baseline again. Note that setTypedText must be called
* prior to setting the baseline. The specified x coordinate will be used as the x
* coordinate of the TextArea.
*
* @param x The x coordinate of the TextArea.
* @param baselineY The y coordinate of the baseline.
*/
virtual void setXBaselineY(int16_t x, int16_t baselineY)
{
setX(x);
setBaselineY(baselineY);
}
/**
* @fn inline void TextArea::setLinespacing(int16_t space)
*
* @brief Sets the line spacing of the TextArea.
*
* Sets the line spacing of the TextArea.
*
* @param space The line spacing of use in the TextArea.
*/
inline void setLinespacing(int16_t space)
{
linespace = space;
}
/**
* @fn inline int16_t TextArea::getLinespacing() const
*
* @brief Gets the line spacing of the TextArea.
*
* Gets the line spacing of the TextArea.
*
* @return The line spacing.
*/
inline int16_t getLinespacing() const
{
return linespace;
}
/**
* @fn inline void TextArea::setIndentation(uint8_t indent)
*
* @brief Sets the indentation for the text.
*
* Sets the indentation for the text. This is very useful when a font is an italic
* font where letters such as "j" and "g" extend a lot to the left under the
* previous characters. if a line starts with a "j" or "g" this letter would either
* have to be pushed to the right to be able to see all of it, e.g. using spaces
* which would ruin a multi line text which is left aligned. This could be solved by
* changing a textarea.setPosition(50,50,100,100) to textarea.setPosition(45,50,110,
* 100) followed by a textarea.setIndentation(5). Characters that do not extend to
* the left under the previous characters will be drawn in the same position in
* either case, but "j" and "g" will be aligned with other lines.
*
* The function getMaxPixelsLeft() will give you the maximum number of pixels any
* glyph in the font extends to the left.
*
* @param indent The indentation from left (when left aligned text) and right (when right
* aligned text).
*
* @see getMaxPixelsLeft
*/
inline void setIndentation(uint8_t indent)
{
indentation = indent;
}
/**
* @fn inline uint8_t TextArea::getIndentation()
*
* @brief Gets the indentation.
*
* Gets the indentation.
*
* @return The indentation.
*
* @see setIndetation
*/
inline uint8_t getIndentation()
{
return indentation;
}
/**
* @fn virtual int16_t TextArea::getTextHeight();
*
* @brief Gets the total height needed by the text.
*
* Gets the total height needed by the text, taking number of lines and line spacing
* into consideration.
*
* @return the total height needed by the text.
*/
virtual int16_t getTextHeight();
/**
* @fn virtual uint16_t TextArea::getTextWidth() const;
*
* @brief Gets the width in pixels of the current associated text in the current selected
* language.
*
* Gets the width in pixels of the current associated text in the current selected
* language. In case of multi-lined text the width of the widest line is returned.
*
* @return The width in pixels of the current text.
*/
virtual uint16_t getTextWidth() const;
/**
* @fn virtual void TextArea::draw(const Rect& area) const;
*
* @brief Draws the text.
*
* Draws the text. Called automatically.
*
* @param area The invalidated area.
*/
virtual void draw(const Rect& area) const;
/**
* @fn void TextArea::setTypedText(TypedText t);
*
* @brief Sets the TypedText of the text area.
*
* Sets the TypedText of the text area. If no prior size has been set the TextArea
* will be resized to fit the new TypedText.
*
* @param t The TypedText for this widget to display.
*/
void setTypedText(TypedText t);
/**
* @fn TypedText TextArea::getTypedText() const
*
* @brief Gets the TypedText of the text area
*
* Gets the TypedText of the text area.
*
* @return The currently used TypedText.
*/
TypedText getTypedText() const
{
return typedText;
}
/**
* @fn void TextArea::setRotation(const TextRotation rotation)
*
* @brief Sets rotation of the text in the TextArea.
*
* Sets rotation of the text in the TextArea. The value TEXT_ROTATE_0 is the default
* for normal text. The value TEXT_ROTATE_90 will rotate the text clockwise, thus
* writing from the top of the display and down. Similarly TEXT_ROTATE_180 and
* TEXT_ROTATE_270 is further rotate 90 degrees clockwise.
*
* @param rotation The rotation of the text.
*/
void setRotation(const TextRotation rotation)
{
this->rotation = rotation;
}
/**
* @fn TextRotation TextArea::getRotation() const
*
* @brief Gets rotation of the text in the TextArea.
*
* Gets rotation of the text in the TextArea.
*
* @return The rotation of the text.
*/
TextRotation getRotation() const
{
return rotation;
}
/**
* @fn void TextArea::resizeToCurrentText();
*
* @brief Sets the dimensions of the TextArea.
*
* Sets the dimensions of the TextArea to match the width and height of the current
* associated text for the current selected language.
*
* Please note that if the current text rotation is either 90 or 270 degrees, the
* width of the text area will be set to the height of the text and vice versa, as
* the text is rotated.
*
* @see setRotation
* @see resizeHeightToCurrentText
*/
void resizeToCurrentText();
/**
* @fn void TextArea::resizeToCurrentTextWithAlignment();
*
* @brief Sets the dimensions of the TextArea.
*
* Sets the dimensions of the TextArea to match the width and height of the current
* associated text for the current selected language.
*
* When setting the width, the position of the TextArea might be changed in order to
* keep the text centered or right aligned.
*
* Please note that if the current text rotation is either 90 or 270 degrees, the width
* of the text area will be set to the height of the text and vice versa, as the text is
* rotated.
*
* @see setRotation
* @see resizeHeightToCurrentText
*/
void resizeToCurrentTextWithAlignment();
/**
* @fn void TextArea::resizeHeightToCurrentText();
*
* @brief Sets the height of the TextArea.
*
* Sets the height of the TextArea to match the height of the current associated
* text for the current selected language. This is especially useful for texts with
* WordWrap enabled.
*
* Please note that if the current text rotation is either 90 or 270 degrees, the
* width of the text area will be set and not the height, as the text is rotated.
*
* @see resizeToCurrentText
* @see setWordWrap
* @see setRotation
*/
void resizeHeightToCurrentText();
/**
* @fn void TextArea::setWideTextAction(WideTextAction action)
*
* @brief Sets wide text action.
*
* Sets wide text action. Defines what to do if a line of text is wider than the
* text area. Default action is WIDE_TEXT_NONE which means that text lines are only
* broken if there is a newline in the text.
*
* If wrapping is enabled and the text would occupy more lines than the size of the
* TextArea, the last line will get an ellipsis to signal that some text is missing.
* The character used for ellipsis is taken from the text spreadsheet.
*
* @param action The action to perform for wide lines of text.
*
* @see WideTextAction
* @see getWideTextAction
* @see resizeHeightToCurrentText
*/
void setWideTextAction(WideTextAction action)
{
wideTextAction = action;
}
/**
* @fn WideTextAction TextArea::getWideTextAction() const
*
* @brief Gets wide text action.
*
* Gets wide text action preciously set using setWideTextAction.
*
* @return current WideTextAction setting.
*
* @see setWideTextAction
*/
WideTextAction getWideTextAction() const
{
return wideTextAction;
}
/**
* @fn int16_t TextArea::calculateTextHeight(const Unicode::UnicodeChar* format, ...) const;
*
* @brief Gets the total height needed by the text.
*
* Gets the total height needed by the text. Determined by number of lines and
* linespace. The number of wildcards in the text should match the number of values
* for the wildcards.
*
* @param format The text containing %s wildcards.
* @param ... Variable arguments providing additional information.
*
* @return the total height needed by the text.
*/
virtual int16_t calculateTextHeight(const Unicode::UnicodeChar* format, ...) const;
protected:
TypedText typedText; ///< The TypedText to display
colortype color; ///< The color to use.
int16_t linespace; ///< The line spacing to use, in pixels, in case the text contains newlines.
uint8_t alpha; ///< The alpha to use.
uint8_t indentation; ///< The indentation of the text inside the text area
TextRotation rotation; ///< The text rotation to use
WideTextAction wideTextAction; ///< What to do if the text is wider than the text area
};
} // namespace touchgfx
#endif // TEXTAREA_HPP
| 32.953947 | 158 | 0.6113 | [
"solid"
] |
99b901072a6388b997ed98552a94726e5bb83256 | 10,930 | hpp | C++ | ReactNativeFrontend/ios/Pods/boost/boost/dll/import.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 106 | 2015-08-07T04:23:50.000Z | 2020-12-27T18:25:15.000Z | ReactNativeFrontend/ios/Pods/boost/boost/dll/import.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 130 | 2016-06-22T22:11:25.000Z | 2020-11-29T20:24:09.000Z | ReactNativeFrontend/ios/Pods/boost/boost/dll/import.hpp | Harshitha91/Tmdb-react-native-node | e06e3f25a7ee6946ef07a1f524fdf62e48424293 | [
"Apache-2.0"
] | 48 | 2015-08-21T00:16:15.000Z | 2022-03-15T03:11:17.000Z | // Copyright 2014 Renato Tegon Forti, Antony Polukhin.
// Copyright 2015-2021 Antony Polukhin.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_DLL_IMPORT_HPP
#define BOOST_DLL_IMPORT_HPP
#include <boost/dll/config.hpp>
#include <boost/core/addressof.hpp>
#include <boost/core/enable_if.hpp>
#include <boost/type_traits/is_object.hpp>
#include <boost/make_shared.hpp>
#include <boost/dll/shared_library.hpp>
#include <boost/move/move.hpp>
#if defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) || defined(BOOST_NO_CXX11_DECLTYPE) || defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
# include <boost/function.hpp>
#endif
#ifdef BOOST_HAS_PRAGMA_ONCE
# pragma once
#endif
/// \file boost/dll/import.hpp
/// \brief Contains all the boost::dll::import* reference counting
/// functions that hold a shared pointer to the instance of
/// boost::dll::shared_library.
namespace boost { namespace dll {
namespace detail {
template <class T>
class library_function {
// Copying of `boost::dll::shared_library` is very expensive, so we use a `shared_ptr` to make it faster.
boost::shared_ptr<T> f_;
public:
inline library_function(const boost::shared_ptr<shared_library>& lib, T* func_ptr) BOOST_NOEXCEPT
: f_(lib, func_ptr)
{}
#if defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) || defined(BOOST_NO_CXX11_DECLTYPE) || defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
operator T*() const BOOST_NOEXCEPT {
return f_.get();
}
#else
// Compilation error at this point means that imported function
// was called with unmatching parameters.
//
// Example:
// auto f = dll::import_symbol<void(int)>("function", "lib.so");
// f("Hello"); // error: invalid conversion from 'const char*' to 'int'
// f(1, 2); // error: too many arguments to function
// f(); // error: too few arguments to function
template <class... Args>
inline auto operator()(Args&&... args) const
-> decltype( (*f_)(static_cast<Args&&>(args)...) )
{
return (*f_)(static_cast<Args&&>(args)...);
}
#endif
};
template <class T, class = void>
struct import_type;
template <class T>
struct import_type<T, typename boost::disable_if<boost::is_object<T> >::type> {
typedef boost::dll::detail::library_function<T> base_type;
#if defined(BOOST_NO_CXX11_TRAILING_RESULT_TYPES) || defined(BOOST_NO_CXX11_DECLTYPE) || defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
typedef boost::function<T> type;
#else
typedef boost::dll::detail::library_function<T> type;
#endif
};
template <class T>
struct import_type<T, typename boost::enable_if<boost::is_object<T> >::type> {
typedef boost::shared_ptr<T> base_type;
typedef boost::shared_ptr<T> type;
};
} // namespace detail
#ifndef BOOST_DLL_DOXYGEN
# define BOOST_DLL_IMPORT_RESULT_TYPE inline typename boost::dll::detail::import_type<T>::type
#endif
/*!
* Returns callable object or boost::shared_ptr<T> that holds the symbol imported
* from the loaded library. Returned value refcounts usage
* of the loaded shared library, so that it won't get unload until all copies of return value
* are not destroyed.
*
* This call will succeed if call to \forcedlink{shared_library}`::has(const char* )`
* function with the same symbol name returned `true`.
*
* For importing symbols by \b alias names use \forcedlink{import_alias} method.
*
* \b Examples:
*
* \code
* boost::function<int(int)> f = import_symbol<int(int)>("test_lib.so", "integer_func_name");
*
* auto f_cpp11 = import_symbol<int(int)>("test_lib.so", "integer_func_name");
* \endcode
*
* \code
* boost::shared_ptr<int> i = import_symbol<int>("test_lib.so", "integer_name");
* \endcode
*
* \b Template \b parameter \b T: Type of the symbol that we are going to import. Must be explicitly specified.
*
* \param lib Path to shared library or shared library to load function from.
* \param name Null-terminated C or C++ mangled name of the function to import. Can handle std::string, char*, const char*.
* \param mode An mode that will be used on library load.
*
* \return callable object if T is a function type, or boost::shared_ptr<T> if T is an object type.
*
* \throw \forcedlinkfs{system_error} if symbol does not exist or if the DLL/DSO was not loaded.
* Overload that accepts path also throws std::bad_alloc in case of insufficient memory.
*/
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_symbol(const boost::dll::fs::path& lib, const char* name,
load_mode::type mode = load_mode::default_mode)
{
typedef typename boost::dll::detail::import_type<T>::base_type type;
boost::shared_ptr<boost::dll::shared_library> p = boost::make_shared<boost::dll::shared_library>(lib, mode);
return type(p, boost::addressof(p->get<T>(name)));
}
//! \overload boost::dll::import_symbol(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_symbol(const boost::dll::fs::path& lib, const std::string& name,
load_mode::type mode = load_mode::default_mode)
{
return dll::import_symbol<T>(lib, name.c_str(), mode);
}
//! \overload boost::dll::import_symbol(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_symbol(const shared_library& lib, const char* name) {
typedef typename boost::dll::detail::import_type<T>::base_type type;
boost::shared_ptr<boost::dll::shared_library> p = boost::make_shared<boost::dll::shared_library>(lib);
return type(p, boost::addressof(p->get<T>(name)));
}
//! \overload boost::dll::import_symbol(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_symbol(const shared_library& lib, const std::string& name) {
return dll::import_symbol<T>(lib, name.c_str());
}
//! \overload boost::dll::import_symbol(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_symbol(BOOST_RV_REF(shared_library) lib, const char* name) {
typedef typename boost::dll::detail::import_type<T>::base_type type;
boost::shared_ptr<boost::dll::shared_library> p = boost::make_shared<boost::dll::shared_library>(
boost::move(lib)
);
return type(p, boost::addressof(p->get<T>(name)));
}
//! \overload boost::dll::import_symbol(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_symbol(BOOST_RV_REF(shared_library) lib, const std::string& name) {
return dll::import_symbol<T>(boost::move(lib), name.c_str());
}
/*!
* Returns callable object or boost::shared_ptr<T> that holds the symbol imported
* from the loaded library. Returned value refcounts usage
* of the loaded shared library, so that it won't get unload until all copies of return value
* are not destroyed.
*
* This call will succeed if call to \forcedlink{shared_library}`::has(const char* )`
* function with the same symbol name returned `true`.
*
* For importing symbols by \b non \b alias names use \forcedlink{import} method.
*
* \b Examples:
*
* \code
* boost::function<int(int)> f = import_alias<int(int)>("test_lib.so", "integer_func_alias_name");
*
* auto f_cpp11 = import_alias<int(int)>("test_lib.so", "integer_func_alias_name");
* \endcode
*
* \code
* boost::shared_ptr<int> i = import_alias<int>("test_lib.so", "integer_alias_name");
* \endcode
*
* \code
* \endcode
*
* \b Template \b parameter \b T: Type of the symbol alias that we are going to import. Must be explicitly specified.
*
* \param lib Path to shared library or shared library to load function from.
* \param name Null-terminated C or C++ mangled name of the function or variable to import. Can handle std::string, char*, const char*.
* \param mode An mode that will be used on library load.
*
* \return callable object if T is a function type, or boost::shared_ptr<T> if T is an object type.
*
* \throw \forcedlinkfs{system_error} if symbol does not exist or if the DLL/DSO was not loaded.
* Overload that accepts path also throws std::bad_alloc in case of insufficient memory.
*/
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const boost::dll::fs::path& lib, const char* name,
load_mode::type mode = load_mode::default_mode)
{
typedef typename boost::dll::detail::import_type<T>::base_type type;
boost::shared_ptr<boost::dll::shared_library> p = boost::make_shared<boost::dll::shared_library>(lib, mode);
return type(p, p->get<T*>(name));
}
//! \overload boost::dll::import_alias(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const boost::dll::fs::path& lib, const std::string& name,
load_mode::type mode = load_mode::default_mode)
{
return dll::import_alias<T>(lib, name.c_str(), mode);
}
//! \overload boost::dll::import_alias(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const shared_library& lib, const char* name) {
typedef typename boost::dll::detail::import_type<T>::base_type type;
boost::shared_ptr<boost::dll::shared_library> p = boost::make_shared<boost::dll::shared_library>(lib);
return type(p, p->get<T*>(name));
}
//! \overload boost::dll::import_alias(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(const shared_library& lib, const std::string& name) {
return dll::import_alias<T>(lib, name.c_str());
}
//! \overload boost::dll::import_alias(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(BOOST_RV_REF(shared_library) lib, const char* name) {
typedef typename boost::dll::detail::import_type<T>::base_type type;
boost::shared_ptr<boost::dll::shared_library> p = boost::make_shared<boost::dll::shared_library>(
boost::move(lib)
);
return type(p, p->get<T*>(name));
}
//! \overload boost::dll::import_alias(const boost::dll::fs::path& lib, const char* name, load_mode::type mode)
template <class T>
BOOST_DLL_IMPORT_RESULT_TYPE import_alias(BOOST_RV_REF(shared_library) lib, const std::string& name) {
return dll::import_alias<T>(boost::move(lib), name.c_str());
}
#undef BOOST_DLL_IMPORT_RESULT_TYPE
}} // boost::dll
#endif // BOOST_DLL_IMPORT_HPP
| 39.316547 | 176 | 0.715645 | [
"object"
] |
99b9e44221e780874b4b6b9146a830989c1586ec | 12,786 | cpp | C++ | src/psvrservice/VirtualHMD/VirtualHMD.cpp | opendata26/PSVRTracker | dfd13e9ed0daa312ae71ce2a077209c4994659ab | [
"MIT"
] | null | null | null | src/psvrservice/VirtualHMD/VirtualHMD.cpp | opendata26/PSVRTracker | dfd13e9ed0daa312ae71ce2a077209c4994659ab | [
"MIT"
] | null | null | null | src/psvrservice/VirtualHMD/VirtualHMD.cpp | opendata26/PSVRTracker | dfd13e9ed0daa312ae71ce2a077209c4994659ab | [
"MIT"
] | null | null | null | //-- includes -----
#include "VirtualHMD.h"
#include "DeviceInterface.h"
#include "DeviceManager.h"
#include "HMDDeviceEnumerator.h"
#include "VirtualHMDDeviceEnumerator.h"
#include "MathUtility.h"
#include "Logger.h"
#include "Utility.h"
#include <vector>
#include <cstdlib>
#ifdef _WIN32
#define _USE_MATH_DEFINES
#endif
#include <math.h>
// -- constants -----
#define VIRTUAL_HMD_STATE_BUFFER_MAX 4
// -- private methods
// -- public interface
// -- Morpheus HMD Config
const int VirtualHMDConfig::CONFIG_VERSION = 1;
const configuru::Config
VirtualHMDConfig::writeToJSON()
{
configuru::Config pt{
{"is_valid", is_valid},
{"version", VirtualHMDConfig::CONFIG_VERSION},
{"Calibration.Position.VarianceExpFitA", position_variance_exp_fit_a},
{"Calibration.Position.VarianceExpFitB", position_variance_exp_fit_b},
{"Calibration.Time.MeanUpdateTime", mean_update_time_delta},
{"Calibration.Orientation.Variance", orientation_variance},
{"OrientationFilter.FilterType", orientation_filter_type},
{"PositionFilter.FilterType", position_filter_type},
{"PositionFilter.MaxVelocity", max_velocity},
{"prediction_time", prediction_time}
};
switch (trackingShape.shape_type)
{
case PSVRTrackingShape_Sphere:
pt["tracking_shape"] = "sphere";
pt["bulb.center.x"] = trackingShape.shape.sphere.center.x;
pt["bulb.center.y"] = trackingShape.shape.sphere.center.y;
pt["bulb.center.z"] = trackingShape.shape.sphere.center.z;
pt["bulb.radius"] = trackingShape.shape.sphere.radius;
break;
case PSVRTrackingShape_LightBar:
pt["tracking_shape"]= "light_bar";
pt["lightbar.quad.v0.x"]= trackingShape.shape.lightbar.quad[0].x;
pt["lightbar.quad.v0.y"]= trackingShape.shape.lightbar.quad[0].y;
pt["lightbar.quad.v0.z"]= trackingShape.shape.lightbar.quad[0].z;
pt["lightbar.quad.v1.x"]= trackingShape.shape.lightbar.quad[1].x;
pt["lightbar.quad.v1.y"]= trackingShape.shape.lightbar.quad[1].y;
pt["lightbar.quad.v1.z"]= trackingShape.shape.lightbar.quad[1].z;
pt["lightbar.quad.v2.x"]= trackingShape.shape.lightbar.quad[2].x;
pt["lightbar.quad.v2.y"]= trackingShape.shape.lightbar.quad[2].y;
pt["lightbar.quad.v2.z"]= trackingShape.shape.lightbar.quad[2].z;
pt["lightbar.quad.v3.x"]= trackingShape.shape.lightbar.quad[3].x;
pt["lightbar.quad.v3.y"]= trackingShape.shape.lightbar.quad[3].y;
pt["lightbar.quad.v3.z"]= trackingShape.shape.lightbar.quad[3].z;
pt["lightbar.triangle.v0.x"]= trackingShape.shape.lightbar.triangle[0].x;
pt["lightbar.triangle.v0.y"]= trackingShape.shape.lightbar.triangle[0].y;
pt["lightbar.triangle.v0.z"]= trackingShape.shape.lightbar.triangle[0].z;
pt["lightbar.triangle.v1.x"]= trackingShape.shape.lightbar.triangle[1].x;
pt["lightbar.triangle.v1.y"]= trackingShape.shape.lightbar.triangle[1].y;
pt["lightbar.triangle.v1.z"]= trackingShape.shape.lightbar.triangle[1].z;
pt["lightbar.triangle.v2.x"]= trackingShape.shape.lightbar.triangle[2].x;
pt["lightbar.triangle.v2.y"]= trackingShape.shape.lightbar.triangle[2].y;
pt["lightbar.triangle.v2.z"]= trackingShape.shape.lightbar.triangle[2].z;
break;
case PSVRTrackingShape_PointCloud:
pt["tracking_shape"]= "point_cloud";
pt["points.count"]= trackingShape.shape.pointcloud.point_count;
for (int point_index= 0; point_index < trackingShape.shape.pointcloud.point_count; ++point_index)
{
const char axis_label[3]= {'x', 'y', 'z'};
const float* axis_values= (const float *)&trackingShape.shape.pointcloud.points[point_index];
for (int axis_index = 0; axis_index < 3; ++axis_index)
{
char key[64];
Utility::format_string(key, sizeof(key), "points.v%d.%c", point_index, axis_label[axis_index]);
pt[key]= axis_values[axis_index];
}
}
break;
}
writeTrackingColor(pt, tracking_color_id);
return pt;
}
void
VirtualHMDConfig::readFromJSON(const configuru::Config &pt)
{
version = pt.get_or<int>("version", 0);
if (version == VirtualHMDConfig::CONFIG_VERSION)
{
is_valid = pt.get_or<bool>("is_valid", false);
prediction_time = pt.get_or<float>("prediction_time", 0.f);
position_variance_exp_fit_a = pt.get_or<float>("Calibration.Position.VarianceExpFitA", position_variance_exp_fit_a);
position_variance_exp_fit_b = pt.get_or<float>("Calibration.Position.VarianceExpFitB", position_variance_exp_fit_b);
mean_update_time_delta = pt.get_or<float>("Calibration.Time.MeanUpdateTime", mean_update_time_delta);
position_filter_type = pt.get_or<std::string>("PositionFilter.FilterType", position_filter_type);
max_velocity = pt.get_or<float>("PositionFilter.MaxVelocity", max_velocity);
orientation_variance = pt.get_or<float>("Calibration.Orientation.Variance", orientation_variance);
orientation_filter_type = pt.get_or<std::string>("OrientationFilter.FilterType", orientation_filter_type);
// Read the tracking color
tracking_color_id = static_cast<PSVRTrackingColorType>(readTrackingColor(pt));
std::string shape_type= pt.get_or<std::string>("tracking_shape", "sphere");
if (shape_type == "sphere")
trackingShape.shape_type= PSVRTrackingShape_Sphere;
else if (shape_type == "light_bar")
trackingShape.shape_type= PSVRTrackingShape_LightBar;
else if (shape_type == "point_cloud")
trackingShape.shape_type= PSVRTrackingShape_PointCloud;
switch (trackingShape.shape_type)
{
case PSVRTrackingShape_Sphere:
trackingShape.shape.sphere.radius= pt.get_or<float>("bulb.radius", 2.25f);
trackingShape.shape.sphere.center.x= pt.get_or<float>("bulb.center.x", 0.f);
trackingShape.shape.sphere.center.y= pt.get_or<float>("bulb.center.y", 0.f);
trackingShape.shape.sphere.center.z= pt.get_or<float>("bulb.center.z", 0.f);
break;
case PSVRTrackingShape_LightBar:
trackingShape.shape.lightbar.quad[0].x= pt.get_or<float>("lightbar.quad.v0.x", 0.0f);
trackingShape.shape.lightbar.quad[0].y= pt.get_or<float>("lightbar.quad.v0.y", 0.0f);
trackingShape.shape.lightbar.quad[0].z= pt.get_or<float>("lightbar.quad.v0.z", 0.0f);
trackingShape.shape.lightbar.quad[1].x= pt.get_or<float>("lightbar.quad.v1.x", 0.0f);
trackingShape.shape.lightbar.quad[1].y= pt.get_or<float>("lightbar.quad.v1.y", 0.0f);
trackingShape.shape.lightbar.quad[1].z= pt.get_or<float>("lightbar.quad.v1.z", 0.0f);
trackingShape.shape.lightbar.quad[2].x= pt.get_or<float>("lightbar.quad.v2.x", 0.0f);
trackingShape.shape.lightbar.quad[2].y= pt.get_or<float>("lightbar.quad.v2.y", 0.0f);
trackingShape.shape.lightbar.quad[2].z= pt.get_or<float>("lightbar.quad.v2.z", 0.0f);
trackingShape.shape.lightbar.quad[3].x= pt.get_or<float>("lightbar.quad.v3.x", 0.0f);
trackingShape.shape.lightbar.quad[3].y= pt.get_or<float>("lightbar.quad.v3.y", 0.0f);
trackingShape.shape.lightbar.quad[3].z= pt.get_or<float>("lightbar.quad.v3.z", 0.0f);
trackingShape.shape.lightbar.triangle[0].x= pt.get_or<float>("lightbar.triangle.v0.x", 0.0f);
trackingShape.shape.lightbar.triangle[0].y= pt.get_or<float>("lightbar.triangle.v0.y", 0.0f);
trackingShape.shape.lightbar.triangle[0].z= pt.get_or<float>("lightbar.triangle.v0.z", 0.0f);
trackingShape.shape.lightbar.triangle[1].x= pt.get_or<float>("lightbar.triangle.v1.x", 0.0f);
trackingShape.shape.lightbar.triangle[1].y= pt.get_or<float>("lightbar.triangle.v1.y", 0.0f);
trackingShape.shape.lightbar.triangle[1].z= pt.get_or<float>("lightbar.triangle.v1.z", 0.0f);
trackingShape.shape.lightbar.triangle[2].x= pt.get_or<float>("lightbar.triangle.v2.x", 0.0f);
trackingShape.shape.lightbar.triangle[2].y= pt.get_or<float>("lightbar.triangle.v2.y", 0.0f);
trackingShape.shape.lightbar.triangle[2].z= pt.get_or<float>("lightbar.triangle.v2.z", 0.0f);
break;
case PSVRTrackingShape_PointCloud:
trackingShape.shape.pointcloud.point_count= std::min(pt.get_or<int>("points.count", 0), (int)MAX_POINT_CLOUD_POINT_COUNT);
for (int point_index= 0; point_index < trackingShape.shape.pointcloud.point_count; ++point_index)
{
const char axis_label[3]= {'x', 'y', 'z'};
float* axis_values= (float *)&trackingShape.shape.pointcloud.points[point_index];
for (int axis_index = 0; axis_index < 3; ++axis_index)
{
char key[64];
Utility::format_string(key, sizeof(key), "points.v%d.%c", point_index, axis_label[axis_index]);
axis_values[axis_index]= pt.get_or<float>(key, 0.f);
}
}
break;
}
}
else
{
PSVR_LOG_WARNING("VirtualHMDConfig") <<
"Config version " << version << " does not match expected version " <<
VirtualHMDConfig::CONFIG_VERSION << ", Using defaults.";
}
}
// -- Virtual HMD -----
VirtualHMD::VirtualHMD()
: cfg()
, NextPollSequenceNumber(0)
, bIsOpen(false)
, bIsTracking(false)
{
}
VirtualHMD::~VirtualHMD()
{
if (getIsOpen())
{
PSVR_LOG_ERROR("~VirtualHMD") << "HMD deleted without calling close() first!";
}
}
bool VirtualHMD::open()
{
HMDDeviceEnumerator enumerator(HMDDeviceEnumerator::CommunicationType_VIRTUAL);
bool success = false;
if (enumerator.is_valid())
{
success = open(&enumerator);
}
return success;
}
bool VirtualHMD::open(
const DeviceEnumerator *enumerator)
{
const HMDDeviceEnumerator *pEnum = static_cast<const HMDDeviceEnumerator *>(enumerator);
const char *cur_dev_path = pEnum->get_path();
bool success = false;
if (getIsOpen())
{
PSVR_LOG_WARNING("VirtualHMD::open") << "VirtualHMD(" << cur_dev_path << ") already open. Ignoring request.";
success = true;
}
else
{
PSVR_LOG_INFO("VirtualHMD::open") << "Opening VirtualHMD(" << cur_dev_path << ").";
device_identifier = cur_dev_path;
bIsOpen= true;
// Load the config file
cfg = VirtualHMDConfig(pEnum->get_path());
cfg.load();
// Save it back out again in case any defaults changed
cfg.save();
// Reset the polling sequence counter
NextPollSequenceNumber = 0;
success = true;
}
return success;
}
void VirtualHMD::close()
{
if (bIsOpen)
{
device_identifier= "";
bIsOpen= true;
}
else
{
PSVR_LOG_INFO("VirtualHMD::close") << "MorpheusHMD already closed. Ignoring request.";
}
}
// Getters
bool
VirtualHMD::matchesDeviceEnumerator(const DeviceEnumerator *enumerator) const
{
// Down-cast the enumerator so we can use the correct get_path.
const HMDDeviceEnumerator *pEnum = static_cast<const HMDDeviceEnumerator *>(enumerator);
bool matches = false;
if (pEnum->get_device_type() == getDeviceType())
{
const char *enumerator_path = pEnum->get_path();
const char *dev_path = device_identifier.c_str();
#ifdef _WIN32
matches = _stricmp(dev_path, enumerator_path) == 0;
#else
matches = strcmp(dev_path, enumerator_path) == 0;
#endif
}
return matches;
}
std::string
VirtualHMD::getUSBDevicePath() const
{
return device_identifier;
}
bool
VirtualHMD::getIsOpen() const
{
return bIsOpen;
}
void
VirtualHMD::getTrackingShape(PSVRTrackingShape &outTrackingShape) const
{
outTrackingShape= cfg.trackingShape;
}
bool
VirtualHMD::setTrackingColorID(const PSVRTrackingColorType tracking_color_id)
{
bool bSuccess = false;
if (getIsOpen())
{
cfg.tracking_color_id = tracking_color_id;
cfg.save();
bSuccess = true;
}
return bSuccess;
}
bool
VirtualHMD::getTrackingColorID(PSVRTrackingColorType &out_tracking_color_id) const
{
out_tracking_color_id = cfg.tracking_color_id;
return true;
}
float
VirtualHMD::getPredictionTime() const
{
return getConfig()->prediction_time;
}
void VirtualHMD::setTrackingEnabled(bool bEnable)
{
if (!bIsTracking && bEnable)
{
bIsTracking = true;
}
else if (bIsTracking && !bEnable)
{
bIsTracking = false;
}
} | 36.741379 | 134 | 0.657438 | [
"shape",
"vector"
] |
99c71f0f2da9c644f1df6a35e461643339c7f749 | 1,805 | cpp | C++ | archive/3/rosnace_zdjecie.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | archive/3/rosnace_zdjecie.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | archive/3/rosnace_zdjecie.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef intmax_t I;
const I inf = 1e18;
struct Fragment {
I n;
bool cut_after;
Fragment(I n, bool c = false) : n(n), cut_after(c) {};
};
bool operator<(Fragment a, Fragment b) {
return (a.n != b.n ? a.n < b.n : (I)a.cut_after < (I)b.cut_after);
}
ostream &operator<<(ostream &o, Fragment f) {
o << f.n;
if(f.cut_after) o << "'";
return o;
}
int main()
{
cout.sync_with_stdio(false);
cin.tie(nullptr);
I m;
cin >> m;
vector<I> t;
for(I i = 0; i < m; ++i) {
I x;
cin >> x;
if(!t.empty() && t.back() == x) {
continue;
}
t.push_back(x);
}
I n = t.size();
//for(I i : t) cout << i << ' '; cout << '\n';
multiset<Fragment> s;
s.emplace(-inf, true);
s.emplace(inf, true);
for(I i = 0; i < n; ++i) {
auto hi = s.upper_bound(Fragment(t[i], true));
auto lo = prev(hi);
I lo_n = lo->n, hi_n = hi->n;
//for(auto f : s) cout << f << ' '; cout << '\n';
//cout << "lo: " << *lo << ", hi: " << *hi << '\n';
if(!lo->cut_after) {
//cout << "adding cut after " << *lo << '\n';
s.erase(lo);
s.emplace(lo_n, true);
}
I j = i;
while(j < n && (j == i || t[j - 1] <= t[j]) && t[j] <= hi_n) {
++j;
} --j;
//cout << "inserting strip " << i << ":" << j << '\n';
for(; i <= j - 1; ++i) {
s.emplace(t[i]);
}
s.emplace(t[j], true);
//cout << "jmp " << j << '\n';
i = j;
}
//for(auto f : s) cout << f << ' '; cout << '\n';
I c = 0;
for(auto f : s) {
c += f.cut_after;
};
c -= 3;
cout << c << '\n';
return 0;
}
| 20.055556 | 70 | 0.400554 | [
"vector"
] |
99c73e555c2df87a5f548bf37c2ffbb6faad9712 | 2,992 | cpp | C++ | src/fieldlimits.cpp | vieiramanoel/PVC_Final | acad658f6fcdb530a457046ea505fc9f88f498e6 | [
"MIT"
] | null | null | null | src/fieldlimits.cpp | vieiramanoel/PVC_Final | acad658f6fcdb530a457046ea505fc9f88f498e6 | [
"MIT"
] | 1 | 2016-06-12T16:56:51.000Z | 2016-06-12T16:56:51.000Z | src/fieldlimits.cpp | vieiramanoel/PVC_Final | acad658f6fcdb530a457046ea505fc9f88f498e6 | [
"MIT"
] | null | null | null | #include "fieldlimits.hpp"
FieldLimits::FieldLimits(){
cv::FileStorage paramReader("data.yml", cv::FileStorage::READ);
auto cannyParam = paramReader["canny_parameters"];
calibrating = cannyParam["Calibrating"];
_cannythresh1 = cannyParam["Thresh1"];
_cannythresh2 = cannyParam["Thresh2"];
counterAdjust_ = 0;
largestArea = 0;
largestAreaIndex = 0;
hasRectSetted_ = false;
}
FieldLimits::~FieldLimits(){
cv::FileStorage paramWriter("data.yml", cv::FileStorage::WRITE);
paramWriter << "canny_parameters";
paramWriter << "{" << "Thresh1" << _cannythresh1;
paramWriter << "Thresh2" << _cannythresh2;
paramWriter << "Calibrating" << calibrating << "}";
paramWriter.release();
}
void FieldLimits::calculateProb(cv::Mat input){
preProcessor(input);
if(not hasRectSetted_){
std::vector<std::vector<cv::Point>> newcontours;
std::vector<cv::Vec4i> newhierarchy;
cv::Rect newboundingRect;
cv::Mat test;
dst.copyTo(test);
cv::findContours(test, newcontours, newhierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
for (uint i = 0; i < newcontours.size(); ++i)
{
newboundingRect = cv::boundingRect(newcontours[i]);
double a = newboundingRect.area();
if(a > largestArea){
counterAdjust_ = 0;
largestArea = a;
largestAreaIndex = i;
boundingRect = newboundingRect;
contours = newcontours;
hierarchy = newhierarchy;
}
else
counterAdjust_++;
}
}
drawGreatLines(input);
}
void FieldLimits::drawGreatLines(cv::Mat input){
auto color = cv::Scalar::all(133);
cv::drawContours(input, contours, largestAreaIndex, color, 3, 8, hierarchy);
cv::rectangle(input, boundingRect, cv::Scalar(0,255,0),3, 8,0);
}
void FieldLimits::preProcessor(cv::Mat input){
cv::Mat cannyMat;
std::vector<cv::Mat> channels(3);
input.copyTo(cannyMat);
cv::cvtColor(cannyMat, cannyMat, CV_BGR2HSV);
cv::split(cannyMat, channels);
cv::Mat element = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(3, 3), cv::Point(1, 1));
cv::Canny(channels[2], dst, _cannythresh1, _cannythresh2, 3);
if(calibrating){
cv::imshow("Canny Out", dst);
cv::createTrackbar("Canny Threshold 1", "Canny Out", &_cannythresh1, 1000);
cv::createTrackbar("Canny Threshold 2", "Canny Out", &_cannythresh2, 1000);
}
}
limitsParameters FieldLimits::getResult(){
params.limits = boundingRect;
params.contours = contours;
params.hierarchy = hierarchy;
params.largestAreaIndex = largestAreaIndex;
return params;
}
std::vector<std::vector<cv::Point>> FieldLimits::getContours(){
return contours;
}
bool FieldLimits::isStable(){
return false;
return counterAdjust_ > 4000 ? true : false;
} | 29.92 | 100 | 0.623997 | [
"vector"
] |
99cbd5a1a9e8eeb207bc57d9b161d9dc514971d5 | 8,332 | hpp | C++ | components/rgbd-sources/include/ftl/rgbd/frame.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | 4 | 2020-12-28T15:29:15.000Z | 2021-06-27T12:37:15.000Z | components/rgbd-sources/include/ftl/rgbd/frame.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | null | null | null | components/rgbd-sources/include/ftl/rgbd/frame.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | 2 | 2021-01-13T05:28:39.000Z | 2021-05-04T03:37:11.000Z | #pragma once
#ifndef _FTL_RGBD_FRAME_HPP_
#define _FTL_RGBD_FRAME_HPP_
#include <ftl/configuration.hpp>
#include <ftl/exception.hpp>
#include <opencv2/core.hpp>
#include <opencv2/core/cuda.hpp>
#include <opencv2/core/cuda_stream_accessor.hpp>
#include <ftl/data/new_frame.hpp>
#include <ftl/codecs/channels.hpp>
#include <ftl/rgbd/format.hpp>
#include <ftl/rgbd/camera.hpp>
#include <ftl/codecs/codecs.hpp>
#include <ftl/codecs/packet.hpp>
#include <ftl/utility/vectorbuffer.hpp>
#include <ftl/cuda_common.hpp>
#include <ftl/rgbd/capabilities.hpp>
#include <type_traits>
#include <array>
#include <list>
#include <Eigen/Eigen>
namespace ftl {
namespace calibration {
struct CalibrationData;
}
namespace rgbd {
//typedef ftl::data::Frame Frame;
/*inline const ftl::rgbd::Camera &getLeftCamera(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration); }
inline const ftl::rgbd::Camera &getRightCamera(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration2); }
inline const ftl::rgbd::Camera &getLeft(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration); }
inline const ftl::rgbd::Camera &getRight(const Frame &f) { return f.get<ftl::rgbd::Camera>(ftl::codecs::Channel::Calibration2); }
inline const Eigen::Matrix4d &getPose(const Frame &f) { return f.get<Eigen::Matrix4d>(ftl::codecs::Channel::Pose); }*/
class VideoFrame {
public:
VideoFrame() {}
// Manually add copy constructor since default is removed
VideoFrame(const VideoFrame &);
VideoFrame &operator=(const VideoFrame &);
template <typename T>
ftl::cuda::TextureObject<T> &createTexture(const ftl::rgbd::Format<T> &f, bool interpolated);
template <typename T>
ftl::cuda::TextureObject<T> &createTexture(bool interpolated=false) const;
cv::cuda::GpuMat &createGPU();
cv::cuda::GpuMat &createGPU(const ftl::rgbd::FormatBase &f);
template <typename T> ftl::cuda::TextureObject<T> &getTexture(ftl::codecs::Channel) const;
cv::Mat &createCPU();
cv::Mat &createCPU(const ftl::rgbd::FormatBase &f);
const cv::Mat &getCPU() const;
const cv::cuda::GpuMat &getGPU() const;
/// gets cv::Mat for
cv::Mat &setCPU();
cv::cuda::GpuMat &setGPU();
inline bool isGPU() const { return isgpu; };
inline bool hasOpenGL() const { return opengl_id != 0; }
inline void setOpenGL(unsigned int id) { opengl_id = id; }
inline unsigned int getOpenGL() const { return opengl_id; }
private:
mutable ftl::cuda::TextureObjectBase tex;
cv::cuda::GpuMat gpu;
mutable cv::Mat host;
unsigned int opengl_id=0;
bool isgpu=false;
mutable bool validhost=false;
};
class Frame : public ftl::data::Frame {
public:
const ftl::rgbd::Camera &getLeftCamera() const;
const ftl::rgbd::Camera &getRightCamera() const;
inline const ftl::rgbd::Camera &getLeft() const { return getLeftCamera(); }
inline const ftl::rgbd::Camera &getRight() const { return getRightCamera(); }
const Eigen::Matrix4d &getPose() const;
ftl::rgbd::Camera &setLeft();
ftl::rgbd::Camera &setRight();
Eigen::Matrix4d &setPose();
cv::Size getSize(ftl::codecs::Channel c=ftl::codecs::Channel::Left) const;
ftl::calibration::CalibrationData& setCalibration();
const ftl::calibration::CalibrationData& getCalibration() const;
std::string serial() const;
std::string device() const;
/** Note, this throws exception if channel is missing */
const std::unordered_set<ftl::rgbd::Capability> &capabilities() const;
/** Does not throw exception */
bool hasCapability(ftl::rgbd::Capability) const;
inline bool isLive() const { return hasCapability(ftl::rgbd::Capability::LIVE); }
inline bool isVirtual() const { return hasCapability(ftl::rgbd::Capability::VIRTUAL); }
inline bool isMovable() const { return hasCapability(ftl::rgbd::Capability::MOVABLE); }
inline bool isTouchable() const { return hasCapability(ftl::rgbd::Capability::TOUCH); }
inline bool isVR() const { return hasCapability(ftl::rgbd::Capability::VR); }
inline bool is360() const { return hasCapability(ftl::rgbd::Capability::EQUI_RECT); }
inline bool isSideBySideStereo() const { return hasCapability(ftl::rgbd::Capability::STEREO); }
void upload(ftl::codecs::Channel c);
bool isGPU(ftl::codecs::Channel c) const;
bool hasOpenGL(ftl::codecs::Channel c) const;
unsigned int getOpenGL(ftl::codecs::Channel c) const;
template <typename T>
ftl::cuda::TextureObject<T> &getTexture(ftl::codecs::Channel c) { return this->get<VideoFrame>(c).getTexture<T>(c); }
template <typename T>
ftl::cuda::TextureObject<T> &createTexture(ftl::codecs::Channel c, bool interpolated=false) { return this->get<VideoFrame>(c).createTexture<T>(interpolated); }
template <typename T>
ftl::cuda::TextureObject<T> &createTexture(ftl::codecs::Channel c, const ftl::rgbd::Format<T> &fmt, bool interpolated=false) { return this->create<VideoFrame>(c).createTexture<T>(fmt, interpolated); }
};
template <typename T>
ftl::cuda::TextureObject<T> &VideoFrame::getTexture(ftl::codecs::Channel c) const {
if (!isgpu) throw FTL_Error("Texture channel is not on GPU");
if (tex.cvType() != ftl::traits::OpenCVType<T>::value || tex.width() != static_cast<size_t>(gpu.cols) || tex.height() != static_cast<size_t>(gpu.rows) || gpu.type() != tex.cvType()) {
throw FTL_Error("Texture has not been created properly " << int(c));
}
return ftl::cuda::TextureObject<T>::cast(tex);
}
template <typename T>
ftl::cuda::TextureObject<T> &VideoFrame::createTexture(const ftl::rgbd::Format<T> &f, bool interpolated) {
createGPU();
if (f.empty()) {
throw FTL_Error("createTexture needs a non-empty format");
} else {
gpu.create(f.size(), f.cvType);
}
if (gpu.type() != ftl::traits::OpenCVType<T>::value) {
throw FTL_Error("Texture type mismatch: " << gpu.type() << " != " << ftl::traits::OpenCVType<T>::value);
}
// TODO: Check tex cvType
if (tex.devicePtr() == nullptr) {
//LOG(INFO) << "Creating texture object";
tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
} else if (tex.cvType() != ftl::traits::OpenCVType<T>::value || tex.width() != static_cast<size_t>(gpu.cols) || tex.height() != static_cast<size_t>(gpu.rows)) {
//LOG(INFO) << "Recreating texture object for '" << ftl::codecs::name(c) << "'";
tex.free();
tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
}
return ftl::cuda::TextureObject<T>::cast(tex);
}
template <typename T>
ftl::cuda::TextureObject<T> &VideoFrame::createTexture(bool interpolated) const {
if (!isgpu && !host.empty()) {
//gpu.create(host.size(), host.type());
// TODO: Should this upload to GPU or not?
//gpu_ += c;
throw FTL_Error("Cannot create a texture on a host frame");
} else if (!isgpu || (isgpu && gpu.empty())) {
throw FTL_Error("createTexture needs a format if no memory is allocated");
}
if (gpu.type() != ftl::traits::OpenCVType<T>::value) {
throw FTL_Error("Texture type mismatch: " << gpu.type() << " != " << ftl::traits::OpenCVType<T>::value);
}
// TODO: Check tex cvType
if (tex.devicePtr() == nullptr) {
//LOG(INFO) << "Creating texture object";
tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
} else if (tex.cvType() != ftl::traits::OpenCVType<T>::value || tex.width() != static_cast<size_t>(gpu.cols) || tex.height() != static_cast<size_t>(gpu.rows) || tex.devicePtr() != gpu.data) {
//LOG(INFO) << "Recreating texture object for '" << ftl::codecs::name(c) << "'.";
tex.free();
tex = ftl::cuda::TextureObject<T>(gpu, interpolated);
}
return ftl::cuda::TextureObject<T>::cast(tex);
}
}
}
template <>
cv::Mat &ftl::data::Frame::create<cv::Mat, 0>(ftl::codecs::Channel c);
template <>
cv::cuda::GpuMat &ftl::data::Frame::create<cv::cuda::GpuMat, 0>(ftl::codecs::Channel c);
template <>
const cv::Mat &ftl::data::Frame::get<cv::Mat>(ftl::codecs::Channel c) const;
template <>
const cv::cuda::GpuMat &ftl::data::Frame::get<cv::cuda::GpuMat>(ftl::codecs::Channel c) const;
template <>
cv::Mat &ftl::data::Frame::set<cv::Mat, 0>(ftl::codecs::Channel c);
template <>
cv::cuda::GpuMat &ftl::data::Frame::set<cv::cuda::GpuMat, 0>(ftl::codecs::Channel c);
template <>
inline bool ftl::data::make_type<ftl::rgbd::VideoFrame>() {
return false;
}
template <>
inline bool ftl::data::decode_type<ftl::rgbd::VideoFrame>(std::any &a, const std::vector<uint8_t> &data) {
return false;
}
#endif // _FTL_RGBD_FRAME_HPP_
| 34.861925 | 201 | 0.698632 | [
"object",
"vector"
] |
99cfd49481fee5ea2442b2730e44b726c8d0aeb1 | 160,186 | hpp | C++ | Shared/rice.hpp | mdejong/MetalRice | bac112c4d6d151920cb24a7bb062ab6dde172e8c | [
"MIT"
] | 1 | 2022-01-08T06:01:59.000Z | 2022-01-08T06:01:59.000Z | Shared/rice.hpp | mdejong/MetalRice | bac112c4d6d151920cb24a7bb062ab6dde172e8c | [
"MIT"
] | null | null | null | Shared/rice.hpp | mdejong/MetalRice | bac112c4d6d151920cb24a7bb062ab6dde172e8c | [
"MIT"
] | null | null | null | //
// rice.hpp
//
// Created by Mo DeJong on 6/3/18.
// Copyright © 2018 helpurock. All rights reserved.
//
// The rice coder provides a fast and simple method of encoding
// prediction residuals as variable length binary codes.
#ifndef rice_hpp
#define rice_hpp
#if defined(DEBUG)
#include <unordered_map>
#endif // DEBUG
#include "byte_bit_stream.hpp"
#include "rice_util.hpp"
using namespace std;
class RiceEncoder
{
public:
bitset<8> bits;
unsigned int bitOffset;
vector<uint8_t> bytes;
unsigned int numEncodedBits;
// If true, then most significant bit ordering, defaults to lsb first
bool msb;
// unary repeating boolean value, defaults to true
bool unary1;
bool unary2;
RiceEncoder()
: bitOffset(0), numEncodedBits(0), msb(false), unary1(true), unary2(false) {
bytes.reserve(1024);
}
void reset() {
bits.reset();
bitOffset = 0;
bytes.clear();
numEncodedBits = 0;
}
void flushByte() {
const bool debug = false;
uint8_t byteVal = 0;
// Flush 8 bits to backing array of bytes.
// Note that bits can be written as either
// LSB first (reversed) or MSB first (not reversed).
if (msb) {
for ( int i = 0; i < 8; i++ ) {
unsigned int v = (bits.test(i) ? 0x1 : 0x0);
byteVal |= (v << (7 - i));
}
} else {
for ( int i = 0; i < 8; i++ ) {
unsigned int v = (bits.test(i) ? 0x1 : 0x0);
byteVal |= (v << i);
}
}
bits.reset();
bitOffset = 0;
bytes.push_back(byteVal);
if (debug) {
printf("emit byte 0x%02X aka %s\n", byteVal, get_code_bits_as_string64(byteVal, 8).c_str());
}
}
void encodeBit(bool bit) {
bits.set(bitOffset++, bit);
if (bitOffset == 8) {
numEncodedBits += 8;
flushByte();
}
}
// If any bits still need to be emitted, emit final byte.
void finish() {
if (bitOffset > 0) {
// Flush 1-8 bits to some external output.
// Note that all remaining bits must
// be flushed as true so that multiple
// symbols are not encoded at the end
// of the buffer.
numEncodedBits += bitOffset;
while (bitOffset < 8) {
// Emit bit that is consumed by the decoder
// until the end of the input stream.
bits.set(bitOffset++, unary1);
}
flushByte();
}
}
// Rice encode a byte symbol n with an encoding 2^k
// where k=0 uses 1 bit for the value zero.
void encode(uint8_t n, const unsigned int k)
{
const bool debug = false;
#if defined(DEBUG)
// In DEBUG mode, bits contains bits for this specific symbol.
vector<bool> bitsThisSymbol;
vector<bool> prefixBitsThisSymbol;
vector<bool> suffixBitsThisSymbol;
assert(unary1 != unary2);
#endif // DEBUG
const unsigned int m = (1 << k); // 2^k
const unsigned int q = pot_div_k(n, m);
if (debug) {
printf("n %3d : k %3d : m %3d : q = n / m = %d\n", n, k, m, q);
}
for (int i = 0; i < q; i++) {
encodeBit(unary1); // defaults to true
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(unary1);
bitsThisSymbol.push_back(unary1);
}
#endif // DEBUG
}
encodeBit(unary2); // defaults to false
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(unary2);
bitsThisSymbol.push_back(unary2);
}
#endif // DEBUG
for (int i = k - 1; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
encodeBit(bit);
#if defined(DEBUG)
if (debug) {
suffixBitsThisSymbol.push_back(bit);
bitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
if (debug) {
#if defined(DEBUG)
// Print bits that were emitted for this symbol,
// note the order from least to most significant
printf("bits for symbol (least -> most): ");
for ( bool bit : bitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf("\n");
printf("prefix bits for symbol (least -> most): ");
for ( bool bit : prefixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)prefixBitsThisSymbol.size());
printf("suffix bits for symbol (least -> most): ");
for ( bool bit : suffixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)suffixBitsThisSymbol.size());
#endif // DEBUG
}
return;
}
// Encode N symbols and emit any leftover bits
void encode(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
const bool debug = false;
for (int i = 0; i < numByteVals; i++) {
if (debug) {
printf("symboli %5d\n", i);
}
uint8_t byteVal = byteVals[i];
encode(byteVal, k);
}
finish();
}
// Pass k lookup table that has an entry for each byte
void encode(const uint8_t * byteVals, int numByteVals, const uint8_t * kLookupTable) {
const bool debug = false;
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
uint8_t k = kLookupTable[i];
if (debug) {
printf("symboli %5d : blocki %5d : k %2d\n", i, i, k);
}
encode(byteVal, k);
}
finish();
}
// Special case encoding method where an already calculated table
// of K encoding length values has been calculated for each symbol
// in the input. This encoding method can interleave bits encoded
// with different K value, it is typically used with a block by
// block encoding where the resulting outout should emit bits back
// to back and the decoder can lookup the k value for each pixel.
void encode(const uint8_t * byteVals, int numByteVals, const uint8_t * kLookupTable, const int kLookupEvery) {
const bool debug = false;
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
uint8_t k = kLookupTable[i/kLookupEvery];
if (debug) {
printf("symboli %5d : blocki %5d : k %2d\n", i, i/kLookupEvery, k);
}
encode(byteVal, k);
}
finish();
}
// Special case encoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
void encode(const uint8_t * byteVals, int numByteVals,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
assert(countTable.size() == nTable.size());
int symboli = 0;
int blocki = 0;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
for ( ; symboli < maxSymboli; symboli++) {
uint8_t byteVal = byteVals[symboli];
if (debug && 0) {
printf("symboli %5d : blocki %5d : k %2d\n", symboli, blocki, k);
}
encode(byteVal, k);
}
}
}
assert(symboli == numByteVals);
assert(blocki == (kLookupTableLength-1));
finish();
}
// Query number of bits needed to store symbol
// with the given k parameter. Note that this
// size query logic does not need to actually copy
// encoded bytes so it is much faster than encoding.
int numBits(unsigned char n, const unsigned int k) {
const unsigned int q = pot_div_k(n, k);
return q + 1 + k;
}
// Query the number of bits needed to store these symbols
int numBits(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
int totalNumBits = 0;
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
totalNumBits += numBits(byteVal, k);
}
return totalNumBits;
}
// Query the number of bits needed to store these symbols
int numBits(const uint8_t * byteVals, int numByteVals, const uint8_t * kLookupTable, const int kLookupEvery) {
int totalNumBits = 0;
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
uint8_t k = kLookupTable[i/kLookupEvery];
totalNumBits += numBits(byteVal, k);
}
return totalNumBits;
}
};
class RiceDecoder
{
public:
bitset<8> bits;
unsigned int bitOffset;
vector<uint8_t> bytes;
unsigned int byteOffset;
unsigned int numDecodedBits;
bool isFinishedReading;
// If true, then most significant bit ordering, defaults to lsb first
bool msb;
RiceDecoder()
:msb(false)
{
reset();
}
void reset() {
numDecodedBits = 0;
byteOffset = 0;
bits.reset();
bitOffset = 8;
isFinishedReading = false;
// msb not set here, it must be set after constructor
//msb = false;
}
void finish() {
}
bool decodeBit() {
const bool debug = false;
if (debug) {
printf("decodeBit() bitOffset %d\n", bitOffset);
}
if (bitOffset == 8) {
if (byteOffset == bytes.size()) {
// All bytes read and all bits read
isFinishedReading = true;
return false;
}
bits.reset();
uint8_t byteVal = bytes[byteOffset++];
if (debug) {
printf("decodeBit() loading new bitset from byte 0x%02X\n", byteVal);
}
if (msb) {
// Load MSB first
for ( int i = 0; i < 8; i++ ) {
bool bit = ((byteVal >> (7 - i)) & 0x1) ? true : false;
bits.set(i, bit);
}
} else {
// Load with LSB at bit position 0
for ( int i = 0; i < 8; i++ ) {
bool bit = ((byteVal >> i) & 0x1) ? true : false;
bits.set(i, bit);
}
}
bitOffset = 0;
}
if (debug) {
vector<bool> vecOfBool;
for ( int i = bitOffset; i < 8; i++ ) {
bool bit = bits.test(i);
vecOfBool.push_back(bit);
}
printf("pending bits: ");
for ( bool bit : vecOfBool ) {
vecOfBool.push_back(bit);
printf("%d", bit);
}
printf("\n");
}
bool bit = bits.test(bitOffset++);
if (debug) {
printf("decodeBit() returning %d\n", bit);
}
return bit;
}
// Copy input bytes to the input buffer
void copyInputBytes(const uint8_t * byteVals, const int numBytes) {
#if defined(DEBUG)
assert(numBytes > 0);
#endif // DEBUG
bytes.resize(numBytes);
memcpy(bytes.data(), byteVals, numBytes);
}
// Decode N symbols from the input stream and write decoded symbols
// to the output vector. Returns the number of symbols decoded.
virtual
int decodeSymbols(const unsigned int k, const int nsymbols, vector<uint8_t> & decodedBytes) {
const bool debug = false;
if (debug) {
printf("k = %d\n", k);
}
const unsigned int m = (1 << k);
int symboli = 0;
for ( ; symboli < nsymbols ; symboli++ ) {
unsigned int symbol;
unsigned int q = 0;
while (decodeBit()) {
q++;
}
symbol = m * q;
if (debug) {
printf("symbol : m * q : %d * %d : %d\n", m, q, symbol);
}
for ( int i = k - 1; i >= 0; i-- ) {
bool b = decodeBit();
symbol |= ((b ? 1 : 0) << i);
}
if (isFinishedReading) {
break;
}
if (debug) {
printf("append decoded symbol = %d\n", symbol);
}
decodedBytes.push_back(symbol);
numDecodedBits += (q + 1 + k);
}
return symboli;
}
// Decode symbols from a buffer of encoded bytes and
// return the results as a vector of decoded bytes.
// This method assumes that the k value is known.
vector<uint8_t> decode(const uint8_t * byteVals, const int numBytes, const unsigned int k) {
reset();
const bool debug = false;
copyInputBytes(byteVals, numBytes);
vector<uint8_t> decodedBytes;
if (debug) {
printf("k = %d\n", k);
}
int nsymbols = INT_MAX;
decodeSymbols(k, nsymbols, decodedBytes);
/*
const unsigned int m = (1 << k);
for ( ; 1 ; ) {
unsigned int symbol;
unsigned int q = 0;
while (decodeBit()) {
q++;
}
symbol = m * q;
if (debug) {
printf("symbol : m * q : %d * %d : %d\n", m, q, symbol);
}
for ( int i = k - 1; i >= 0; i-- ) {
bool b = decodeBit();
symbol |= ((b ? 1 : 0) << i);
}
if (isFinishedReading) {
break;
}
if (debug) {
printf("append decoded symbol = %d\n", symbol);
}
decodedBytes.push_back(symbol);
numDecodedBits += (q + 1 + k);
}
*/
return decodedBytes;
}
/*
// Decode symbols from a buffer of encoded bytes and
// return the results as a vector of decoded bytes.
// This method assumes that the k value is known.
vector<uint8_t> decode(const uint8_t * byteVals, const int numBytes, const uint8_t * kLookupTable, const int numBlocks, const unsigned int kLookupEvery) {
reset();
const bool debug = false;
vector<uint8_t> decodedBytes;
assert(numBytes > 0);
bytes.resize(numBytes);
memcpy(bytes.data(), byteVals, numBytes);
int symboli = 0;
int lookupCountdown = kLookupEvery;
for ( ; 1 ; symboli++ ) {
unsigned int symbol;
unsigned int q = 0;
// FIXME: non-optimal. Need to look block by block with constant k for each
// element in the block.
unsigned int k;
if (lookupCountdown == kLookupEvery) {
k = kLookupTable[numBlocks];
} else {
k = kLookupTable[symboli/kLookupEvery];
}
lookupCountdown -= 1;
if (lookupCountdown == 0) {
lookupCountdown = kLookupEvery;
}
const unsigned int m = (1 << k);
while (decodeBit()) {
q++;
}
symbol = m * q;
if (debug) {
printf("symbol : m * q : %d * %d : %d (k = %d)\n", m, q, symbol, k);
}
for ( int i = k - 1; i >= 0; i-- ) {
bool b = decodeBit();
symbol |= ((b ? 1 : 0) << i);
}
if (isFinishedReading) {
break;
}
if (debug) {
printf("append decoded symbol = %d\n", symbol);
}
decodedBytes.push_back(symbol);
numDecodedBits += (q + 1 + k);
}
return decodedBytes;
}
*/
/*
// If the K value differs from one symbol to the next, use this form which makes it possible
// to lookup the K value for every offset via a K table.
vector<uint8_t> decode(const uint8_t * byteVals, const int numBytes, const uint8_t * kLookupTable) {
reset();
const bool debug = false;
copyInputBytes(byteVals, numBytes);
vector<uint8_t> decodedBytes;
int symboli = 0;
for ( ; 1 ; symboli++ ) {
unsigned int symbol;
unsigned int q = 0;
// FIXME: non-optimal. Need to look block by block with constant k for each
// element in the block.
const unsigned int k = kLookupTable[symboli];
const unsigned int m = (1 << k);
while (decodeBit()) {
q++;
}
symbol = m * q;
if (debug) {
printf("symbol : m * q : %d * %d : %d (k = %d)\n", m, q, symbol, k);
}
for ( int i = k - 1; i >= 0; i-- ) {
bool b = decodeBit();
symbol |= ((b ? 1 : 0) << i);
}
if (isFinishedReading) {
break;
}
if (debug) {
printf("append decoded symbol = %d\n", symbol);
}
decodedBytes.push_back(symbol);
numDecodedBits += (q + 1 + k);
}
return decodedBytes;
}
*/
/*
void decode(const uint8_t * byteVals, int numByteVals, const uint8_t * kLookupTable, const int kLookupEvery) {
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
uint8_t k = kLookupTable[i/kLookupEvery];
decode(byteVal, numByteVals, k);
}
}
*/
/*
// This version of decode accepts a lookup table that is the same dimension
// as byteVals which means k is looked up for every value.
void decode(const uint8_t * byteVals, int numByteVals, const uint8_t * kLookupTable) {
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
uint8_t k = kLookupTable[i];
decode(byteVal, numByteVals, k);
}
}
*/
// Special case decoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
vector<uint8_t> decode(const uint8_t * bitBuff, int bitBuffN,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
reset();
#if defined(DEBUG)
assert(countTable.size() == nTable.size());
#endif // DEBUG
copyInputBytes(bitBuff, bitBuffN);
// FIXME: decode into known buffer of fixed size or loop over
// table entries once to allocate before push_back() calls.
vector<uint8_t> decodedBytes;
int symboli = 0;
int blocki = 0;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
int numSymbolsDecoded = decodeSymbols(k, numSymbolsPerBlock, decodedBytes);
#if defined(DEBUG)
assert(numSymbolsDecoded == numSymbolsPerBlock);
#endif // DEBUG
symboli += numSymbolsDecoded;
}
}
assert(blocki == (kLookupTableLength-1));
finish();
return decodedBytes;
}
};
// Store prefix, optional 8 bit escape, otherwise a rem of size k into one buffer.
template <const bool U1, const bool U2, class BWBS>
class RiceSplit16Encoder
{
public:
// Emit MSB bit order
BitWriter<true, BWBS> bitWriter;
// Defaults to emitting a word of zeros after
// the final full byte was emitted.
bool writeZeroPadding;
RiceSplit16Encoder() :writeZeroPadding(true) {
}
void reset() {
bitWriter.reset();
}
// If any bits still need to be emitted, emit final byte.
void finish() {
// Do not adjust numEncodedBits
unsigned int savedNumEncodedBits = bitWriter.numEncodedBits;
if (bitWriter.bitOffset > 0) {
// Flush 1-8 bits to some external output.
// Note that all remaining bits must
// be flushed as true so that multiple
// symbols are not encoded at the end
// of the buffer.
const int bitsUntilByte = 8 - bitWriter.bitOffset;
for ( int i = 0; i < bitsUntilByte; i++ ) {
// Emit bit that is consumed by the decoder
// until the end of the input stream.
bitWriter.writeBit(U1);
}
// Reset num bits so that it does not include
// the byte padding that was just emitted above.
bitWriter.numEncodedBits = savedNumEncodedBits;
}
// 32 bits of zero padding
if (writeZeroPadding) {
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
}
}
void encodeBit(const bool bit) {
bitWriter.writeBit(bit);
}
// Rice encode a byte symbol n with an encoding 2^k
// where k=0 uses 1 bit for the value zero. Note that
// if this method is invoked directly then finish()
// must be invoked after all symbols have been encoded.
void encode(uint8_t n, const unsigned int k)
{
const bool debug = false;
#if defined(DEBUG)
// In DEBUG mode, bits contains bits for this specific symbol.
vector<bool> bitsThisSymbol;
vector<bool> prefixBitsThisSymbol;
vector<bool> suffixBitsThisSymbol;
assert(U1 != U2);
#endif // DEBUG
const unsigned int m = (1 << k); // 2^k
const unsigned int q = pot_div_k(n, k);
const unsigned int unaryNumBits = q + 1;
if (debug) {
printf("n %3d : k %3d : m %3d : q = n / m = %d : unaryNumBits %d \n", n, k, m, q, unaryNumBits);
}
if (unaryNumBits > 16) {
// unary1 -> LITERAL : encoded as 16 zero bits in a row.
for (int i = 0; i < 16; i++) {
encodeBit(U1);
}
#if defined(DEBUG)
for (int i = 0; i < q; i++) {
if (debug) {
prefixBitsThisSymbol.push_back(U1);
bitsThisSymbol.push_back(U1);
}
}
#endif // DEBUG
// 8 bit literal appended to suffix buffer
for (int i = 7; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
encodeBit(bit);
#if defined(DEBUG)
if (debug) {
suffixBitsThisSymbol.push_back(bit);
bitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
} else {
// PREFIX -> SUFFIX
#if defined(DEBUG)
assert(q != 16);
#endif // DEBUG
for (int i = 0; i < q; i++) {
encodeBit(U1); // defaults to true
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(U1);
bitsThisSymbol.push_back(U1);
}
#endif // DEBUG
}
encodeBit(U2); // defaults to false
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(U2);
bitsThisSymbol.push_back(U2);
}
#endif // DEBUG
for (int i = k - 1; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
encodeBit(bit);
#if defined(DEBUG)
if (debug) {
suffixBitsThisSymbol.push_back(bit);
bitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
}
if (debug) {
#if defined(DEBUG)
// Print bits that were emitted for this symbol,
// note the order from least to most significant
printf("bits for symbol (least -> most): ");
for ( bool bit : bitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf("\n");
printf("prefix bits for symbol (least -> most): ");
for ( bool bit : prefixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)prefixBitsThisSymbol.size());
printf("suffix bits for symbol (least -> most): ");
for ( bool bit : suffixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)suffixBitsThisSymbol.size());
#endif // DEBUG
}
return;
}
// Encode N symbols and emit any leftover bits
void encode(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
const bool debug = false;
for (int i = 0; i < numByteVals; i++) {
if (debug) {
printf("symboli %5d\n", i);
}
uint8_t byteVal = byteVals[i];
encode(byteVal, k);
}
finish();
}
// Special case encoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
void encode(const uint8_t * byteVals, int numByteVals,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
assert(countTable.size() == nTable.size());
int symboli = 0;
int blocki = 0;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
for ( ; symboli < maxSymboli; symboli++) {
uint8_t byteVal = byteVals[symboli];
if (debug && 0) {
printf("symboli %5d : blocki %5d : k %2d\n", symboli, blocki, k);
}
encode(byteVal, k);
}
}
}
assert(symboli == numByteVals);
// Note that the table lookup should contain one additional padding zero value
assert(blocki == (kLookupTableLength-1));
finish();
}
// Query number of bits needed to store symbol
// with the given k parameter. Note that this
// size query logic does not need to actually copy
// encoded bytes so it is much faster than encoding.
int numBits(unsigned char n, const unsigned int k) {
const unsigned int q = pot_div_k(n, k);
const unsigned int unaryNumBits = q + 1;
if (unaryNumBits > 16) {
// 16 zeros = zero, special case to indicate literal 8 bits
return 16 + 8;
} else {
return unaryNumBits + k;
}
}
// Query the number of bits needed to store these symbols
int numBits(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
int totalNumBits = 0;
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
totalNumBits += numBits(byteVal, k);
}
return totalNumBits;
}
};
// Optimized split16 decoder, this decoder makes use of a 16 bit input buffer
// and when the special case of 16 input zero bits is found, it simply means
// that the literal value is stored as 24 bits in the remainder. This special
// case would only be activated for very large values so performance for
// data that is mostly very small but has a few large deltas should be better
// and this logic has a maximum prefix clz size of 16.
// This decoder assumes that that unary pattern is N false values terminated
// by a true value.
template <const bool U1, const bool U2, class BRBS>
class RiceSplit16Decoder
{
public:
// Input bits. A unary prefix has a maximum length of 16
// and in that case the suffix contains the 8 literal bits.
// All symbol decode operations can be executed as long
// as 24 bits are loaded.
uint32_t bits;
BitReader<true, BRBS, 24> bitsReader;
uint8_t *outputBytePtr;
int outputByteOffset;
int outputByteLength;
RiceSplit16Decoder()
:bits(0),
outputBytePtr(nullptr),
outputByteOffset(-1),
outputByteLength(-1)
{
bitsReader.setBitsPtr(&bits);
}
inline
void refillBits() {
bitsReader.refillBits();
}
// Store refs to input and output byte bufers
void setupInputOutput(const uint8_t * bitBuff, const int bitBuffN,
uint8_t * symbolBuff, const int symbolBuffN)
{
bitsReader.byteReader.setupInput(bitBuff, bitBuffN);
this->outputBytePtr = symbolBuff;
this->outputByteOffset = 0;
this->outputByteLength = symbolBuffN;
#if defined(DEBUG)
if (bitBuff != nullptr) {
uint8_t bVal = bitBuff[0];
bVal += bitBuff[bitBuffN-1];
outputBytePtr[0] = bVal;
outputBytePtr[symbolBuffN-1] = bVal;
}
#endif // DEBUG
}
// Decode N symbols from the input stream and write decoded symbols
// to the output vector. Returns the number of symbols decoded.
int decodeSymbols(const unsigned int k, const int nsymbols) {
const bool debug = false;
if (debug) {
printf("k = %d\n", k);
}
//const unsigned int m = (1 << k);
for ( int symboli = 0; symboli < nsymbols; symboli++ ) {
unsigned int symbol;
// Refill before reading a symbol
refillBits();
unsigned int q;
if ((bits >> 16) == 0) {
// Special case for 16 bits of zeros in high halfword
q = 0;
// FIXME: skip 16 zeros and set symbol to 8 bit literal
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= 24);
# endif // DEBUG
bits <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(bits, 32).c_str());
}
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= 8);
# endif // DEBUG
symbol = bits >> 24;
if (debug) {
printf("symbol : %s\n", get_code_bits_as_string64(symbol, 32).c_str());
}
bits <<= 8;
if (debug) {
printf("bits (del8) : %s\n", get_code_bits_as_string64(bits, 32).c_str());
}
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= 24);
# endif // DEBUG
bitsReader.bitsInRegister -= 24;
} else {
# if defined(DEBUG)
assert((bits & 0xFFFF0000) != 0);
# endif // DEBUG
//unsigned int lz = __builtin_clz(bits);
//q = 32 - lz;
//q = lz;
q = __builtin_clz(bits);
symbol = q << k;
if (debug) {
printf("q (num leading zeros): %d\n", q);
}
// Shift left to place MSB of remainder at the MSB of register
bits <<= (q + 1);
if (debug) {
printf("lshift %2d : %s\n", q, get_code_bits_as_string64(bits, 32).c_str());
}
// FIXME: shift right could use a mask based on k and a shift based
// on q to avoid using the result of the earlier left shift
// Shift right to place LSB of remainder at bit offset 0
uint32_t rem = (bits >> 16) >> (16 - k);
if (debug) {
printf("rem : %s\n", get_code_bits_as_string64(rem, 32).c_str());
}
symbol |= rem;
if (debug) {
printf("symbol : %s\n", get_code_bits_as_string64(symbol, 32).c_str());
}
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= (q + 1 + k));
# endif // DEBUG
bitsReader.bitsInRegister -= (q + 1 + k);
// was already shifted left by (q + 1) above, so shift left to consume rem bits
bits <<= k;
if (debug) {
printf("lshift2 %2d : %s\n", k, get_code_bits_as_string64(bits, 32).c_str());
}
}
if (debug) {
printf("append decoded symbol = %d\n", symbol);
}
#if defined(DEBUG)
assert(outputByteOffset < outputByteLength);
#endif // DEBUG
outputBytePtr[outputByteOffset++] = symbol;
}
return nsymbols;
}
// Decode symbols from a buffer of encoded bytes and
// return the results as a vector of decoded bytes.
// This method assumes that the k value is known.
void decode(const uint8_t * bitBuff, const int bitBuffN,
uint8_t * symbolBuff, const int symbolBuffN,
const unsigned int k)
{
setupInputOutput(bitBuff, bitBuffN, symbolBuff, symbolBuffN);
decodeSymbols(k, symbolBuffN);
return;
}
// Special case decoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
void decode(const uint8_t * bitBuff, int bitBuffN,
uint8_t * symbolBuff, const int symbolBuffN,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
setupInputOutput(bitBuff, bitBuffN, symbolBuff, symbolBuffN);
#if defined(DEBUG)
assert(countTable.size() == nTable.size());
#endif // DEBUG
int symboli = 0;
int blocki = 0;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
#if defined(DEBUG)
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
#endif // DEBUG
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
int numSymbolsDecoded = decodeSymbols(k, numSymbolsPerBlock);
#if defined(DEBUG)
assert(numSymbolsDecoded == numSymbolsPerBlock);
#endif // DEBUG
symboli += numSymbolsDecoded;
}
}
#if defined(DEBUG)
assert(blocki == (kLookupTableLength-1));
assert(symboli == symbolBuffN);
#endif // DEBUG
return;
}
};
// Special purpose split and block into groups of 4 encoding, where 4 values are
// processed at a time so that prefix P and suffix S are stored as (SSSS PPPP)
// 4 at a time. The prefix portion can contain OVER bits that do not fit into k.
template <const bool U1, const bool U2, class BWBS>
class RiceSplit16EncoderG4
{
public:
// Emit MSB bit order
BitWriter<true, BWBS> bitWriter;
// Defaults to emitting a word of zeros after
// the final full byte was emitted.
bool writeZeroPadding;
RiceSplit16EncoderG4() :writeZeroPadding(true) {
}
void reset() {
bitWriter.reset();
}
// If any bits still need to be emitted, emit final byte.
void finish() {
// Do not adjust numEncodedBits
unsigned int savedNumEncodedBits = bitWriter.numEncodedBits;
if (bitWriter.bitOffset > 0) {
// Flush 1-8 bits to some external output.
// Note that all remaining bits must
// be flushed as true so that multiple
// symbols are not encoded at the end
// of the buffer.
const int bitsUntilByte = 8 - bitWriter.bitOffset;
for ( int i = 0; i < bitsUntilByte; i++ ) {
// Emit bit that is consumed by the decoder
// until the end of the input stream.
bitWriter.writeBit(U1);
}
// Reset num bits so that it does not include
// the byte padding that was just emitted above.
bitWriter.numEncodedBits = savedNumEncodedBits;
}
// 32 bits of zero padding
if (writeZeroPadding) {
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
}
}
void encodeBit(const bool bit) {
bitWriter.writeBit(bit);
}
// Rice encode a byte symbol n with an encoding 2^k
// where k=0 uses 1 bit for the value zero. Note that
// if this method is invoked directly then finish()
// must be invoked after all symbols have been encoded.
void encode(uint8_t n,
const unsigned int k,
const bool emitPrefix,
const bool emitSuffix)
{
const bool debug = false;
#if defined(DEBUG)
// In DEBUG mode, bits contains bits for this specific symbol.
vector<bool> bitsThisSymbol;
vector<bool> prefixBitsThisSymbol;
vector<bool> suffixBitsThisSymbol;
assert(U1 != U2);
#endif // DEBUG
const unsigned int m = (1 << k); // 2^k
const unsigned int q = pot_div_k(n, k);
const unsigned int unaryNumBits = q + 1;
if (debug) {
printf("n %3d : k %3d : m %3d : q = n / m = %d : unaryNumBits %d \n", n, k, m, q, unaryNumBits);
}
if (unaryNumBits > 16) {
// unary1 -> LITERAL : encoded as 16 zero bits in a row.
if (emitPrefix) {
for (int i = 0; i < 16; i++) {
encodeBit(U1);
}
}
#if defined(DEBUG)
for (int i = 0; i < 16; i++) {
if (debug) {
prefixBitsThisSymbol.push_back(U1);
bitsThisSymbol.push_back(U1);
}
}
#endif // DEBUG
#if defined(DEBUG)
// Write all 8 bits to bitsThisSymbol debug vector
for (int i = 7; i >= 0; i--) {
if (debug) {
bool bit = (((n >> i) & 0x1) != 0);
bitsThisSymbol.push_back(bit);
}
}
#endif // DEBUG
// Emit OVER bits (not k) to prefix stream
uint8_t overBits = 0;
if (emitPrefix || debug) {
for (int i = 7; i >= (int)k; i--) {
bool bit = (((n >> i) & 0x1) != 0);
if (debug) {
overBits |= (bit << i);
}
if (emitPrefix) {
encodeBit(bit);
}
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
}
// Emit most significant k bits to suffix stream
uint8_t kBits = 0;
if (emitSuffix || debug) {
for (int i = k - 1; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
if (debug) {
kBits |= (bit << i);
}
if (emitSuffix) {
encodeBit(bit);
}
#if defined(DEBUG)
if (debug) {
suffixBitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
}
if (debug) {
printf("kBits %s (%d bits)\n", get_code_bits_as_string64(kBits, 8).c_str(), k);
printf("overBits %s (%d bits)\n", get_code_bits_as_string64(overBits,8).c_str(), 8-k);
#if defined(DEBUG)
// Combining overBits and q is simply a matter of ORing
// these values together, in decoding logic the MSB
// bits for overBits would need to be shifted left
// to mask off k bits.
assert(n == (overBits | kBits));
#endif // DEBUG
}
} else {
// emit PREFIX and or SUFFIX
#if defined(DEBUG)
// q can be in range (0, 15) : valid prefixCount range (1, 16)
assert(q < 16);
assert(unaryNumBits > 0);
assert(unaryNumBits < 17);
#endif // DEBUG
if (emitPrefix || debug) {
// Preix bits
for (int i = 0; i < q; i++) {
if (emitPrefix) {
encodeBit(U1); // defaults to true
}
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(U1);
bitsThisSymbol.push_back(U1);
}
#endif // DEBUG
}
if (emitPrefix) {
encodeBit(U2); // defaults to false
}
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(U2);
bitsThisSymbol.push_back(U2);
}
#endif // DEBUG
}
if (emitSuffix || debug) {
// suffix bits
for (int i = k - 1; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
if (emitSuffix) {
encodeBit(bit);
}
#if defined(DEBUG)
if (debug) {
suffixBitsThisSymbol.push_back(bit);
bitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
}
}
if (debug) {
#if defined(DEBUG)
// Print bits that were emitted for this symbol,
// note the order from least to most significant
printf("bits for symbol (least -> most): ");
for ( bool bit : bitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf("\n");
printf("prefix bits for symbol (least -> most): ");
for ( bool bit : prefixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)prefixBitsThisSymbol.size());
printf("suffix bits for symbol (least -> most): ");
for ( bool bit : suffixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)suffixBitsThisSymbol.size());
printf("\n");
#endif // DEBUG
}
return;
}
// Encode N symbols and emit any leftover bits
void encode(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
const bool debug = false;
for (int i = 0; i < numByteVals; i++) {
if (debug) {
printf("symboli %5d\n", i);
}
uint8_t byteVal = byteVals[i];
encode(byteVal, k);
}
finish();
}
// Special case encoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
void encode(const uint8_t * byteVals, int numByteVals,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
assert(countTable.size() == nTable.size());
int symboli = 0;
int blocki = 0;
const int pN = 4;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
// Block size must be a multiple of pN
assert((numSymbolsPerBlock % pN) == 0);
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
for ( ; symboli < maxSymboli; symboli += pN ) {
const int symboli4Max = symboli + pN;
// Prefix
for ( int i = symboli ; i < symboli4Max; i++ ) {
uint8_t byteVal = byteVals[i];
if (debug && 1) {
printf("symboli %5d : blocki %5d : k %2d : prefix bits\n", symboli, blocki, k);
}
encode(byteVal, k, true, false);
}
// Suffix
for ( int i = symboli ; i < symboli4Max; i++ ) {
uint8_t byteVal = byteVals[i];
if (debug && 1) {
printf("symboli %5d : blocki %5d : k %2d : suffix bits\n", symboli, blocki, k);
}
encode(byteVal, k, false, true);
}
}
}
}
assert(symboli == numByteVals);
// Note that the table lookup should contain one additional padding zero value
assert(blocki == (kLookupTableLength-1));
finish();
}
// Query number of bits needed to store symbol
// with the given k parameter. Note that this
// size query logic does not need to actually copy
// encoded bytes so it is much faster than encoding.
int numBits(unsigned char n, const unsigned int k) {
const unsigned int q = pot_div_k(n, k);
const unsigned int unaryNumBits = q + 1;
if (unaryNumBits > 16) {
// 16 zeros = zero, special case to indicate literal 8 bits
return 16 + 8;
} else {
return unaryNumBits + k;
}
}
// Query the number of bits needed to store these symbols
int numBits(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
int totalNumBits = 0;
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
totalNumBits += numBits(byteVal, k);
}
return totalNumBits;
}
};
// Split encoding where elements are broken into prefix and suffix and then
// grouped 4 at a time.
template <const bool U1, const bool U2, class BRBS>
class RiceSplit16DecoderG4
{
public:
// Input bits. A unary prefix has a maximum length of 16
// and in that case the suffix contains the 8 literal bits.
// All symbol decode operations can be executed as long
// as 24 bits are loaded.
uint32_t bits;
BitReader<true, BRBS, 24> bitsReader;
uint8_t *outputBytePtr;
int outputByteOffset;
int outputByteLength;
RiceSplit16DecoderG4()
:bits(0),
outputBytePtr(nullptr),
outputByteOffset(-1),
outputByteLength(-1)
{
bitsReader.setBitsPtr(&bits);
}
inline
void refillBits() {
bitsReader.refillBits();
}
// Store refs to input and output byte bufers
void setupInputOutput(const uint8_t * bitBuff, const int bitBuffN,
uint8_t * symbolBuff, const int symbolBuffN)
{
bitsReader.byteReader.setupInput(bitBuff, bitBuffN);
this->outputBytePtr = symbolBuff;
this->outputByteOffset = 0;
this->outputByteLength = symbolBuffN;
#if defined(DEBUG)
if (bitBuff != nullptr) {
uint8_t bVal = bitBuff[0];
bVal += bitBuff[bitBuffN-1];
outputBytePtr[0] = bVal;
outputBytePtr[symbolBuffN-1] = bVal;
}
#endif // DEBUG
}
// Decode prefix portion of symbol
uint8_t decodePrefix(const unsigned int k) {
const bool debug = false;
unsigned int symbol;
if ((bits >> 16) == 0) {
// Special case for 16 bits of zeros in high halfword
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= 24);
# endif // DEBUG
bits <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(bits, 32).c_str());
}
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= (8 - k));
# endif // DEBUG
symbol = (bits >> 24) >> k << k;
if (debug) {
printf("symbol : %s\n", get_code_bits_as_string64(symbol, 32).c_str());
}
bits <<= (8 - k);
if (debug) {
printf("bits (del pre) : %s\n", get_code_bits_as_string64(bits, 32).c_str());
}
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= (24 - k));
# endif // DEBUG
bitsReader.bitsInRegister -= (24 - k);
} else {
# if defined(DEBUG)
assert((bits & 0xFFFF0000) != 0);
# endif // DEBUG
//unsigned int lz = __builtin_clz(bits);
//q = 32 - lz;
//q = lz;
if (debug) {
printf("bits : %s\n", get_code_bits_as_string64(bits, 32).c_str());
}
unsigned int q;
q = __builtin_clz(bits);
symbol = q << k;
if (debug) {
printf("q (num leading zeros): %d\n", q);
}
// Shift left to place MSB of remainder at the MSB of register
bits <<= (q + 1);
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= (q + 1));
# endif // DEBUG
bitsReader.bitsInRegister -= (q + 1);
if (debug) {
printf("lshift %2d : %s\n", q, get_code_bits_as_string64(bits, 32).c_str());
}
}
return symbol;
}
uint8_t decodeSuffix(const unsigned int k) {
const bool debug = false;
unsigned int rem;
// Shift right to place LSB of remainder at bit offset 0
rem = (bits >> 16) >> (16 - k);
if (debug) {
printf("rem : %s\n", get_code_bits_as_string64(rem, 8).c_str());
}
# if defined(DEBUG)
assert(bitsReader.bitsInRegister >= k);
# endif // DEBUG
bitsReader.bitsInRegister -= k;
bits <<= k;
if (debug) {
printf("lshift2 %2d : %s\n", k, get_code_bits_as_string64(bits, 32).c_str());
}
return rem;
}
// Decode N symbols from the input stream and write decoded symbols
// to the output vector. Returns the number of symbols decoded.
int decodeSymbols(const unsigned int k, const int nsymbols) {
const bool debug = false;
if (debug) {
printf("k = %d\n", k);
}
//const unsigned int m = (1 << k);
const int N = 4;
unsigned int decodedSymbols[N];
assert((nsymbols % N) == 0);
for ( int symboli = 0; symboli < nsymbols; symboli += N ) {
for ( int si = 0 ; si < 4; si++ ) {
// Refill before reading a symbol
refillBits();
uint8_t prefix = decodePrefix(k);
//uint8_t rem = decodeSuffix(k);
unsigned int symbol;
symbol = prefix;
if (debug) {
printf("append decoded prefix symbol = %d\n", symbol);
}
decodedSymbols[si] = symbol;
}
for ( int si = 0 ; si < 4; si++ ) {
// Refill before reading a symbol
refillBits();
//uint8_t prefix = decodePrefix(k);
uint8_t rem = decodeSuffix(k);
unsigned int symbol = decodedSymbols[si];
symbol |= rem;
if (debug) {
printf("append decoded prefix|suffix symbol = %d\n", symbol);
}
decodedSymbols[si] = symbol;
}
// Emit each symbol
for ( int si = 0 ; si < 4; si++ ) {
unsigned int symbol = decodedSymbols[si];
#if defined(DEBUG)
assert(outputByteOffset < outputByteLength);
#endif // DEBUG
outputBytePtr[outputByteOffset++] = symbol;
}
}
return nsymbols;
}
// Decode symbols from a buffer of encoded bytes and
// return the results as a vector of decoded bytes.
// This method assumes that the k value is known.
void decode(const uint8_t * bitBuff, const int bitBuffN,
uint8_t * symbolBuff, const int symbolBuffN,
const unsigned int k)
{
setupInputOutput(bitBuff, bitBuffN, symbolBuff, symbolBuffN);
decodeSymbols(k, symbolBuffN);
return;
}
// Special case decoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
void decode(const uint8_t * bitBuff, int bitBuffN,
uint8_t * symbolBuff, const int symbolBuffN,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
setupInputOutput(bitBuff, bitBuffN, symbolBuff, symbolBuffN);
#if defined(DEBUG)
assert(countTable.size() == nTable.size());
#endif // DEBUG
int symboli = 0;
int blocki = 0;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
#if defined(DEBUG)
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
#endif // DEBUG
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
int numSymbolsDecoded = decodeSymbols(k, numSymbolsPerBlock);
#if defined(DEBUG)
assert(numSymbolsDecoded == numSymbolsPerBlock);
#endif // DEBUG
symboli += numSymbolsDecoded;
}
}
#if defined(DEBUG)
assert(blocki == (kLookupTableLength-1));
assert(symboli == symbolBuffN);
#endif // DEBUG
return;
}
};
// Special purpose "split" rice encoding where the bits that make up the unary
// prefix bits are stored in one buffer while the remainder bits are stored
// in a second buffer. This encoder checks for the case where the unary bits
// would take up more than 16 bits and in that case it will simply emit 16 zero
// bits and then store the 8 literal bits directly in the remainder. This produces
// an encoding that has a fixed 24 bit width but very very large values will not
// have a worst case that would require hundreds of bits.
// Note that the BWBS class indicated here must implement the API defined
// in BitWriterBitStream.
template <const bool U1, const bool U2, class BWBS>
class RiceSplit16x2Encoder
{
public:
// Emit MSB bit order
BitWriter<true, BWBS> prefixBitWriter;
BitWriter<true, BWBS> remBitWriter;
vector<uint8_t> unaryNBytes;
vector<uint8_t> remNBytes;
RiceSplit16x2Encoder() {
}
void reset() {
prefixBitWriter.reset();
remBitWriter.reset();
unaryNBytes.clear();
remNBytes.clear();
}
// If any bits still need to be emitted, emit final byte.
void finishPrefix() {
// Do not adjust numEncodedBits
auto & bitWriter = prefixBitWriter;
unsigned int savedNumEncodedBits = bitWriter.numEncodedBits;
if (bitWriter.bitOffset > 0) {
// Flush 1-8 bits to some external output.
// Note that all remaining bits must
// be flushed as true so that multiple
// symbols are not encoded at the end
// of the buffer.
const int bitsUntilByte = 8 - bitWriter.bitOffset;
for ( int i = 0; i < bitsUntilByte; i++ ) {
// Emit bit that is consumed by the decoder
// until the end of the input stream.
bitWriter.writeBit(U1);
}
// Reset num bits so that it does not include
// the byte padding that was just emitted above.
bitWriter.numEncodedBits = savedNumEncodedBits;
}
// 32 bits of zero padding
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
}
void finishRem() {
// Do not adjust numEncodedBits
auto & bitWriter = remBitWriter;
unsigned int savedNumEncodedBits = bitWriter.numEncodedBits;
if (bitWriter.bitOffset > 0) {
// Flush 1-8 bits to some external output.
// Note that all remaining bits must
// be flushed as true so that multiple
// symbols are not encoded at the end
// of the buffer.
const int bitsUntilByte = 8 - bitWriter.bitOffset;
for ( int i = 0; i < bitsUntilByte; i++ ) {
// Emit bit that is consumed by the decoder
// until the end of the input stream.
bitWriter.writeBit(U1);
}
// Reset num bits so that it does not include
// the byte padding that was just emitted above.
bitWriter.numEncodedBits = savedNumEncodedBits;
}
// 32 bits of zero padding
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
bitWriter.writeZeroByte();
}
void finish() {
finishPrefix();
finishRem();
}
void encodeBit(const bool isPrefix, const bool bit) {
if (isPrefix) {
prefixBitWriter.writeBit(bit);
} else {
remBitWriter.writeBit(bit);
}
}
// Rice encode a byte symbol n with an encoding 2^k
// where k=0 uses 1 bit for the value zero. Note that
// if this method is invoked directly then finish()
// must be invoked after all symbols have been encoded.
void encode(uint8_t n, const unsigned int k)
{
const bool debug = false;
#if defined(DEBUG)
// In DEBUG mode, bits contains bits for this specific symbol.
vector<bool> bitsThisSymbol;
vector<bool> prefixBitsThisSymbol;
vector<bool> suffixBitsThisSymbol;
assert(U1 != U2);
#endif // DEBUG
const unsigned int q = pot_div_k(n, k);
const unsigned int unaryNumBits = q + 1;
if (debug) {
const unsigned int m = (1 << k); // m = 2^k
printf("n %3d : k %3d : m %3d : q = n / m = %d : unaryNumBits %d \n", n, k, m, q, unaryNumBits);
}
if (unaryNumBits > 16) {
// unary1 -> LITERAL
unaryNBytes.push_back(17);
for (int i = 0; i < 16; i++) {
encodeBit(true, U1);
}
// Note that there is no trailing 1 in this case, 16 zeros
// in a row indicate that the 8 bits after it are always
// the 8 bits of the literal byte.
#if defined(DEBUG)
for (int i = 0; i < 16; i++) {
if (debug) {
prefixBitsThisSymbol.push_back(U1);
bitsThisSymbol.push_back(U1);
}
}
#endif // DEBUG
// 8 bit literal appended to suffix buffer
for (int i = 7; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
encodeBit(false, bit);
#if defined(DEBUG)
if (debug) {
suffixBitsThisSymbol.push_back(bit);
bitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
remNBytes.push_back(n);
} else {
// PREFIX -> SUFFIX
#if defined(DEBUG)
// q can be in range (0, 15) : valid prefixCount range (1, 16)
assert(unaryNumBits < 17);
#endif // DEBUG
unaryNBytes.push_back(unaryNumBits);
for (int i = 0; i < q; i++) {
encodeBit(true, U1); // defaults to true
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(U1);
bitsThisSymbol.push_back(U1);
}
#endif // DEBUG
}
encodeBit(true, U2); // defaults to false
#if defined(DEBUG)
if (debug) {
prefixBitsThisSymbol.push_back(U2);
bitsThisSymbol.push_back(U2);
}
#endif // DEBUG
for (int i = k - 1; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
encodeBit(false, bit);
#if defined(DEBUG)
if (debug) {
suffixBitsThisSymbol.push_back(bit);
bitsThisSymbol.push_back(bit);
}
#endif // DEBUG
}
// Save k bit remainder as a byte value
uint8_t rem = 0;
for (int i = k - 1; i >= 0; i--) {
bool bit = (((n >> i) & 0x1) != 0);
rem |= ((bit ? 0x1 : 0x0) << i);
}
remNBytes.push_back(rem);
#if defined(DEBUG)
assert(n == (rem | (q << k)));
#endif // DEBUG
}
if (debug) {
#if defined(DEBUG)
// Print bits that were emitted for this symbol,
// note the order from least to most significant
printf("bits for symbol (least -> most): ");
for ( bool bit : bitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf("\n");
printf("prefix bits for symbol (least -> most): ");
for ( bool bit : prefixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)prefixBitsThisSymbol.size());
printf("suffix bits for symbol (least -> most): ");
for ( bool bit : suffixBitsThisSymbol ) {
printf("%d", bit ? 1 : 0);
}
printf(" (%d)\n", (int)suffixBitsThisSymbol.size());
#endif // DEBUG
}
return;
}
// Encode N symbols and emit any leftover bits
void encode(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
const bool debug = false;
for (int i = 0; i < numByteVals; i++) {
if (debug) {
printf("symboli %5d\n", i);
}
uint8_t byteVal = byteVals[i];
encode(byteVal, k);
}
finish();
}
// Special case encoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
void encode(const uint8_t * byteVals, int numByteVals,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
assert(countTable.size() == nTable.size());
int symboli = 0;
int blocki = 0;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
for ( ; symboli < maxSymboli; symboli++) {
uint8_t byteVal = byteVals[symboli];
if (debug && 0) {
printf("symboli %5d : blocki %5d : k %2d\n", symboli, blocki, k);
}
encode(byteVal, k);
}
}
}
assert(symboli == numByteVals);
assert(blocki == (kLookupTableLength-1));
finish();
}
// Query number of bits needed to store symbol
// with the given k parameter. Note that this
// size query logic does not need to actually copy
// encoded bytes so it is much faster than encoding.
int numBits(unsigned char n, const unsigned int k) {
const unsigned int q = pot_div_k(n, k);
const unsigned int unaryNumBits = q + 1;
if (unaryNumBits > 16) {
// 16 zeros = zero, special case to indicate literal 8 bits
return 16 + 8;
} else {
return unaryNumBits + k;
}
}
// Query the number of bits needed to store these symbols
int numBits(const uint8_t * byteVals, int numByteVals, const unsigned int k) {
int totalNumBits = 0;
for (int i = 0; i < numByteVals; i++) {
uint8_t byteVal = byteVals[i];
totalNumBits += numBits(byteVal, k);
}
return totalNumBits;
}
};
// This optimized split16 decode will read from a prefix byte array source
// and from a rem suffix array source and reassemble symbols based on
// reading from the variable length symbols.
template <const bool U1, const bool U2, class BRBS>
class RiceSplit16x2Decoder
{
public:
// Input comes from two different arrays, one contains unary
// prefix bits and the second array contains remainder bits.
uint32_t prefixBits;
uint32_t suffixBits;
BitReader<true, BRBS, 24> prefixBitsReader;
BitReader<true, BRBS, 24> suffixBitsReader;
uint8_t *outputBytePtr;
int outputByteOffset;
int outputByteLength;
RiceSplit16x2Decoder()
: outputBytePtr(nullptr),
outputByteOffset(-1),
outputByteLength(-1)
{
prefixBitsReader.setBitsPtr(&prefixBits);
suffixBitsReader.setBitsPtr(&suffixBits);
}
void refillBits() {
prefixBitsReader.refillBits();
suffixBitsReader.refillBits();
}
// Store refs to input and output byte bufers
void setupInputOutput(const uint8_t * prefixBitBuff, const int prefixBitBuffN,
const uint8_t * suffixBitBuff, const int suffixitBuffN,
uint8_t * symbolBuff, const int symbolBuffN)
{
prefixBitsReader.byteReader.setupInput(prefixBitBuff, prefixBitBuffN);
suffixBitsReader.byteReader.setupInput(suffixBitBuff, suffixitBuffN);
this->outputBytePtr = symbolBuff;
this->outputByteOffset = 0;
this->outputByteLength = symbolBuffN;
#if defined(DEBUG)
uint8_t bVal = prefixBitBuff[0];
bVal += prefixBitBuff[prefixBitBuffN-1];
bVal += suffixBitBuff[0];
bVal += suffixBitBuff[suffixitBuffN-1];
outputBytePtr[0] = bVal;
outputBytePtr[symbolBuffN-1] = bVal;
#endif // DEBUG
}
// Decode N symbols from the input stream and write decoded symbols
// to the output vector. Returns the number of symbols decoded.
int decodeSymbols(const unsigned int k, const int nsymbols) {
const bool debug = false;
if (debug) {
printf("k = %d\n", k);
}
const unsigned int m = (1 << k);
int symboli = 0;
for ( ; symboli < nsymbols ; symboli++ ) {
unsigned int symbol;
// Refill before reading a symbol
refillBits();
unsigned int q;
if ((prefixBits >> 16) == 0) {
// Special case for 16 bits of zeros in high halfword
q = 0;
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= 16);
# endif // DEBUG
prefixBitsReader.bitsInRegister -= 16;
prefixBits <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(prefixBits, 32).c_str());
}
# if defined(DEBUG)
assert(suffixBitsReader.bitsInRegister >= 8);
# endif // DEBUG
suffixBitsReader.bitsInRegister -= 8;
symbol = suffixBits >> 24;
if (debug) {
printf("symbol : %s\n", get_code_bits_as_string64(symbol, 32).c_str());
}
suffixBits <<= 8;
if (debug) {
printf("bits (del8) : %s\n", get_code_bits_as_string64(suffixBits, 32).c_str());
}
} else {
# if defined(DEBUG)
assert((prefixBits & 0xFFFF0000) != 0);
# endif // DEBUG
q = __builtin_clz(prefixBits);
symbol = q << k;
if (debug) {
printf("q (num leading zeros): %d\n", q);
}
// Shift left to place MSB of remainder at the MSB of register
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= (q + 1));
# endif // DEBUG
prefixBitsReader.bitsInRegister -= (q + 1);
prefixBits <<= (q + 1);
if (debug) {
printf("lshift %2d : %s\n", q, get_code_bits_as_string64(prefixBits, 32).c_str());
}
# if defined(DEBUG)
assert(suffixBitsReader.bitsInRegister >= k);
# endif // DEBUG
suffixBitsReader.bitsInRegister -= k;
// Shift right to place LSB of remainder at bit offset 0
uint32_t rem = (suffixBits >> 16) >> (16 - k);
if (debug) {
printf("rem : %s\n", get_code_bits_as_string64(rem, 32).c_str());
}
symbol |= rem;
if (debug) {
printf("symbol : %s\n", get_code_bits_as_string64(symbol, 32).c_str());
}
suffixBits <<= k;
if (debug) {
printf("rem lshift : %s\n", get_code_bits_as_string64(suffixBits, 32).c_str());
}
}
//if (isFinishedReading) {
// break;
//}
if (debug) {
printf("append decoded symbol = %d\n", symbol);
}
#if defined(DEBUG)
assert(outputByteOffset < outputByteLength);
#endif // DEBUG
outputBytePtr[outputByteOffset++] = symbol;
}
return symboli;
}
// Decode symbols from a buffer of encoded bytes and
// return the results as a vector of decoded bytes.
// This method assumes that the k value is known.
void decode(const uint8_t * prefixBitBuff, const int prefixBitBuffN,
const uint8_t * suffixBitBuff, const int suffixitBuffN,
uint8_t * symbolBuff, const int symbolBuffN,
const unsigned int k)
{
setupInputOutput(prefixBitBuff, prefixBitBuffN, suffixBitBuff, suffixitBuffN, symbolBuff, symbolBuffN);
decodeSymbols(k, symbolBuffN);
return;
}
// Special case decoding method where the k value for a block of values is lookup
// up in tables. Pass count table which indicates how many blocks the corresponding
// n table entry corresponds to.
void decode(const uint8_t * prefixBitBuff, const int prefixBitBuffN,
const uint8_t * suffixBitBuff, const int suffixitBuffN,
uint8_t * symbolBuff, const int symbolBuffN,
const uint8_t * kLookupTable,
int kLookupTableLength,
const vector<uint32_t> & countTable,
const vector<uint32_t> & nTable)
{
const bool debug = false;
setupInputOutput(prefixBitBuff, prefixBitBuffN, suffixBitBuff, suffixitBuffN, symbolBuff, symbolBuffN);
#if defined(DEBUG)
assert(countTable.size() == nTable.size());
#endif // DEBUG
int symboli = 0;
int blocki = 0;
const int tableMax = (int) countTable.size();
for (int tablei = 0; tablei < tableMax; tablei++) {
// count indicates how many symbols are covered by block k
int numBlockCount = countTable[tablei];
int numSymbolsPerBlock = nTable[tablei];
#if defined(DEBUG)
assert(numBlockCount > 0);
assert(numSymbolsPerBlock > 0);
#endif // DEBUG
// The same number of symbols are used for numBlockCount blocks.
int maxBlocki = blocki + numBlockCount;
if (debug) {
printf("blocki range (%d, %d) numSymbolsPerBlock %d\n", blocki, maxBlocki, numSymbolsPerBlock);
}
for ( ; blocki < maxBlocki; blocki++ ) {
int k = kLookupTable[blocki];
int maxSymboli = symboli + numSymbolsPerBlock;
if (debug) {
printf("symboli range (%d, %d) k %d\n", symboli, maxSymboli, k);
}
int numSymbolsDecoded = decodeSymbols(k, numSymbolsPerBlock);
#if defined(DEBUG)
assert(numSymbolsDecoded == numSymbolsPerBlock);
#endif // DEBUG
symboli += numSymbolsDecoded;
}
}
#if defined(DEBUG)
assert(blocki == (kLookupTableLength-1));
assert(symboli == symbolBuffN);
#endif // DEBUG
return;
}
};
// This optimized split16 decoder will decode only the unary prefix bits that
// have been split into a stream. This unary prefix decode operation basically
// just loads data and then does a CLZ operation for each symbol. The critical
// performance issue with this code is in the execution of clz instructions
// since each one needs the previous one to complete before the next one can
// be executed.
template <const bool U1, const bool U2, class BRBS>
class RiceSplit16x2PrefixDecoder
{
public:
uint32_t prefixBits;
BitReader<true, BRBS, 16> prefixBitsReader;
uint8_t *outputBytePtr;
#if defined(DEBUG)
int outputByteOffset;
int outputByteLength;
#endif // DEBUG
RiceSplit16x2PrefixDecoder()
: outputBytePtr(nullptr)
#if defined(DEBUG)
,
outputByteOffset(-1),
outputByteLength(-1)
#endif // DEBUG
{
prefixBitsReader.setBitsPtr(&prefixBits);
}
inline
void refillBits() {
prefixBitsReader.refillBits();
}
// Store refs to input and output byte bufers
void setupInputOutput(const uint8_t * prefixBitBuff, const int prefixBitBuffN,
uint8_t * symbolBuff, const int symbolBuffN)
{
prefixBitsReader.byteReader.setupInput(prefixBitBuff, prefixBitBuffN);
this->outputBytePtr = symbolBuff;
#if defined(DEBUG)
this->outputByteOffset = 0;
this->outputByteLength = symbolBuffN;
#endif // DEBUG
#if defined(DEBUG)
uint8_t bVal = prefixBitBuff[0];
bVal += prefixBitBuff[prefixBitBuffN-1];
outputBytePtr[0] = bVal;
outputBytePtr[symbolBuffN-1] = bVal;
#endif // DEBUG
}
inline
void writeByte(const uint8_t prefixCount) {
// prefixCount minimum value is 1, it can never be zero.
#if defined(DEBUG)
assert(prefixCount > 0);
#endif // DEBUG
#if defined(DEBUG)
assert(outputByteOffset < outputByteLength);
outputBytePtr[outputByteOffset++] = prefixCount;
#else
*outputBytePtr++ = prefixCount;
#endif // DEBUG
}
// Decode N symbols from the input stream and write decoded symbols
// to the output vector. Returns the number of symbols decoded.
int decodeSymbols(const int nsymbols) {
const bool debug = false;
for ( int symboli = 0; symboli < nsymbols ; symboli++ ) {
refillBits();
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= 16);
# endif // DEBUG
unsigned int prefixCount;
if (debug) {
printf("symboli %5d\n", symboli);
}
const unsigned int top16 = (prefixBits >> 16);
if (top16 == 0) {
// Special case for 16 bits of zeros in high halfword
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= 16);
# endif // DEBUG
prefixBitsReader.bitsInRegister -= 16;
if (debug) {
printf("bits : %s\n", get_code_bits_as_string64(prefixBits, 32).c_str());
}
prefixBits <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(prefixBits, 32).c_str());
}
prefixCount = 17;
} else {
# if defined(DEBUG)
assert((prefixBits & 0xFFFF0000) != 0);
# endif // DEBUG
unsigned int q = __builtin_clz(prefixBits);
if (debug) {
printf("q (num leading zeros): %d\n", q);
}
# if defined(DEBUG)
// Valid CLZ+1 range is (1, 16)
assert(q >= 0 && q <= 15);
# endif // DEBUG
// Shift left to drop prefix bits from left side of register.
prefixCount = q + 1;
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= prefixCount);
# endif // DEBUG
prefixBitsReader.bitsInRegister -= prefixCount;
prefixBits <<= prefixCount;
if (debug) {
printf("lshift %2d : %s\n", q, get_code_bits_as_string64(prefixBits, 32).c_str());
}
}
if (debug) {
printf("append prefix count = %d\n", prefixCount);
}
writeByte(prefixCount);
}
return nsymbols;
}
// Decode symbols from a buffer of encoded bytes and
// return the results as a vector of decoded bytes.
// This method assumes that the k value is known.
void decode(const uint8_t * prefixBitBuff, const int prefixBitBuffN,
uint8_t * symbolBuff, const int symbolBuffN)
{
setupInputOutput(prefixBitBuff, prefixBitBuffN, symbolBuff, symbolBuffN);
decodeSymbols(symbolBuffN);
return;
}
};
// Prefix decoder built on top of byte reader interface
template <const bool U1, const bool U2, class BRBS>
class RiceSplit16x2PrefixDecoder64
{
public:
uint64_t outputBuffer;
uint8_t *outputBytePtr;
#if defined(DEBUG)
int outputByteOffset;
int outputByteLength;
#endif // DEBUG
uint32_t prefixBits;
BitReader<true, BRBS, 16> prefixBitsReader;
uint8_t outputBufferOffset;
RiceSplit16x2PrefixDecoder64()
: outputBytePtr(nullptr),
outputBuffer(0),
outputBufferOffset(0)
#if defined(DEBUG)
,
outputByteOffset(-1),
outputByteLength(-1)
#endif // DEBUG
{
prefixBitsReader.setBitsPtr(&prefixBits);
}
inline
void refillBits() {
prefixBitsReader.refillBits();
}
// Store refs to input and output byte bufers
void setupInputOutput(const uint8_t * prefixBitBuff, const int prefixBitBuffN,
uint8_t * symbolBuff, const int symbolBuffN)
{
prefixBitsReader.byteReader.setupInput(prefixBitBuff, prefixBitBuffN);
this->outputBytePtr = symbolBuff;
#if defined(DEBUG)
this->outputByteOffset = 0;
this->outputByteLength = symbolBuffN;
#endif // DEBUG
#if defined(DEBUG)
uint8_t bVal = prefixBitBuff[0];
bVal += prefixBitBuff[prefixBitBuffN-1];
outputBytePtr[0] = bVal;
outputBytePtr[symbolBuffN-1] = bVal;
#endif // DEBUG
}
inline
void writeByte(const uint8_t prefixCount) {
const bool debug = false;
if (debug) {
printf("append prefix count = %d\n", prefixCount);
}
// prefixCount minimum value is 1, it can never be zero.
#if defined(DEBUG)
assert(prefixCount > 0);
#endif // DEBUG
#if defined(DEBUG)
assert(outputByteOffset < outputByteLength);
outputBytePtr[outputByteOffset++] = prefixCount;
#else
// Write byte to outputBuffer, unless it is already full
if (debug) {
printf("outputBuffer %s\n", get_code_bits_as_string64(outputBuffer, 64).c_str());
}
if (outputBufferOffset == 8) {
#pragma unroll(8)
for ( int i = 0; i < 8; i++ ) {
uint8_t bVal = (outputBuffer >> (i * 8)) & 0xFF;
*outputBytePtr++ = bVal;
}
outputBuffer = prefixCount;
outputBufferOffset = 1;
} else {
// Append to next open slot
if (debug) {
printf("append to next open slot\n");
}
uint64_t prefixCount64 = prefixCount;
outputBuffer |= (prefixCount64 << (outputBufferOffset * 8));
outputBufferOffset += 1;
}
#endif // DEBUG
}
inline
void flushBufferedBytes() {
for ( int i = 0; i < 8; i++ ) {
uint8_t bVal = (outputBuffer >> (i * 8)) & 0xFF;
if (bVal == 0) {
break;
}
*outputBytePtr++ = bVal;
}
}
// Decode N symbols from the input stream and write decoded symbols
// to the output vector. Returns the number of symbols decoded.
int decodeSymbols(const int nsymbols) {
const bool debug = false;
for ( int symboli = 0; symboli < nsymbols ; symboli++ ) {
refillBits();
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= 16);
# endif // DEBUG
unsigned int prefixCount;
if (debug) {
printf("symboli %5d\n", symboli);
}
const unsigned int top16 = (prefixBits >> 16);
if (top16 == 0) {
// Special case for 16 bits of zeros in high halfword
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= 16);
# endif // DEBUG
prefixBitsReader.bitsInRegister -= 16;
if (debug) {
printf("bits : %s\n", get_code_bits_as_string64(prefixBits, 32).c_str());
}
prefixBits <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(prefixBits, 32).c_str());
}
prefixCount = 17;
} else {
# if defined(DEBUG)
assert((prefixBits & 0xFFFF0000) != 0);
# endif // DEBUG
unsigned int q = __builtin_clz(prefixBits);
if (debug) {
printf("q (num leading zeros): %d\n", q);
}
# if defined(DEBUG)
assert(q < 16);
# endif // DEBUG
// Shift left to drop prefix bits from left side of register.
prefixCount = q + 1;
# if defined(DEBUG)
assert(prefixCount < 17);
# endif // DEBUG
# if defined(DEBUG)
assert(prefixBitsReader.bitsInRegister >= prefixCount);
# endif // DEBUG
prefixBitsReader.bitsInRegister -= prefixCount;
prefixBits <<= prefixCount;
if (debug) {
printf("lshift %2d : %s\n", prefixCount, get_code_bits_as_string64(prefixBits, 32).c_str());
}
}
if (debug) {
printf("append prefix count = %d\n", prefixCount);
}
writeByte(prefixCount);
}
flushBufferedBytes();
return nsymbols;
}
// Decode symbols from a buffer of encoded bytes and
// return the results as a vector of decoded bytes.
// This method assumes that the k value is known.
void decode(const uint8_t * prefixBitBuff, const int prefixBitBuffN,
uint8_t * symbolBuff, const int symbolBuffN)
{
setupInputOutput(prefixBitBuff, prefixBitBuffN, symbolBuff, symbolBuffN);
decodeSymbols(symbolBuffN);
return;
}
};
#import "byte_bit_stream64.hpp"
// This split prefix decoder works on top of 64 bit read API.
// A decode invocation will read bits into a register and
// decode a prefix symbol. Note that this implementation
// assumes zero bits for the fill and a 1 bit to mark the
// end of a prefix encoding. While the input comes from
// a uint64_t the output is always written as a simple byte
// since this proves to be the fastest implementaiton.
template <class BRBS>
class RiceSplit16x2PrefixDecoder64Read64
{
public:
uint8_t *outputBytePtr;
BitReader64<BRBS, 16> prefixBitsReader;
RiceSplit16x2PrefixDecoder64Read64()
: outputBytePtr(nullptr)
{
}
inline
void refillBits() {
prefixBitsReader.refillBits();
}
// Define the output location where symbols will be written to
void setupOutput(uint8_t * symbolBuff)
{
this->outputBytePtr = symbolBuff;
}
inline
void writeByte(const uint8_t prefixCount) {
const bool debug = false;
if (debug) {
printf("append prefix count = %d\n", prefixCount);
}
// prefixCount minimum value is 1, it can never be zero.
#if defined(DEBUG)
assert(prefixCount > 0);
#endif // DEBUG
*outputBytePtr++ = prefixCount;
}
// Decode N symbols from the input stream and write decoded symbols
// to the output vector. Returns the number of symbols decoded.
int decodeSymbols(const uint64_t nsymbols) {
const bool debug = false;
for ( uint64_t symboli = 0; symboli < nsymbols ; symboli++ ) {
refillBits();
# if defined(DEBUG)
assert(prefixBitsReader.numBits1 >= 16);
# endif // DEBUG
uint64_t prefixCount;
if (debug) {
printf("symboli %5d\n", (int)symboli);
}
if ((prefixBitsReader.bits1 >> 32 >> 16) == 0) {
// Special case for 16 bits of zeros in high halfword
# if defined(DEBUG)
assert(prefixBitsReader.numBits1 >= 16);
# endif // DEBUG
prefixBitsReader.numBits1 -= 16;
if (debug) {
printf("bits : %s\n", get_code_bits_as_string64(prefixBitsReader.bits1, 64).c_str());
}
prefixBitsReader.bits1 <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(prefixBitsReader.bits1, 64).c_str());
}
prefixCount = 17;
} else {
# if defined(DEBUG)
assert((prefixBitsReader.bits1 >> 32 >> 16) != 0);
# endif // DEBUG
uint64_t q = __clz(prefixBitsReader.bits1);
if (debug) {
printf("q (num leading zeros): %d\n", (int)q);
}
# if defined(DEBUG)
assert(q < 16);
# endif // DEBUG
// Shift left to drop prefix bits from left side of register.
prefixCount = q + 1;
# if defined(DEBUG)
assert(prefixCount < 17);
# endif // DEBUG
# if defined(DEBUG)
assert(prefixBitsReader.numBits1 >= prefixCount);
# endif // DEBUG
prefixBitsReader.numBits1 -= prefixCount;
prefixBitsReader.bits1 <<= prefixCount;
if (debug) {
printf("lshift %2d : %s\n", (int)prefixCount, get_code_bits_as_string64(prefixBitsReader.bits1, 64).c_str());
}
}
if (debug) {
printf("append prefix count = %d\n", (int)prefixCount);
}
writeByte((uint8_t) prefixCount);
}
return (int) nsymbols;
}
};
// Generate a num symbols per block lookup table for a given
// number of block vecs as a fixed block size.
static inline
vector<uint32_t> MakeFixedKBlockTable(const vector<uint8_t> & kBlockVec,
const int blockSize)
{
// Sub 1 to ignore padding byte at end of kBlockVec
int nBlocks = (int)kBlockVec.size() - 1;
vector<uint32_t> table(nBlocks);
for (int i = 0; i < nBlocks; i++) {
table[i] = blockSize;
}
return table;
}
// Rewrite prefix bits as 64 bit values after padding to 8 byte bound
static inline
vector<uint8_t> PrefixBitStreamRewrite64(const vector<uint8_t> & prefixBits)
{
const bool debug = false;
// Pad until a whole 64 bit read would read until the end of the vector
vector<uint8_t> result = prefixBits;
while (1) {
uint32_t numBytes = (uint32_t) result.size();
if ((numBytes % sizeof(uint64_t)) == 0) {
break;
}
result.push_back(0);
}
// Output has been padded to a whole 64 bit value, now add one more
// padding 64 bit value to take care of reading ahead by 1.
for (int i = 0; i < sizeof(uint64_t); i++) {
result.push_back(0);
}
int numBytes = (int) result.size();
// Output from prefix stage must be in terms of whole dwords
if ((numBytes % sizeof(uint64_t)) != 0) {
assert(0);
}
uint64_t *ptr64 = (uint64_t *) result.data();
// Now read each set of 8 bytes into a uint64_t and store
// with a single write so that when read with uint64_t
// little endian reads the bytes are in the proper order.
int numDWords = numBytes / sizeof(uint64_t);
for (int i = 0; i < numDWords; i++) {
uint8_t buffer[8];
memcpy(&buffer[0], ptr64, sizeof(buffer));
if (debug) {
for (int i = 0; i < 8; i++) {
printf("buffer[%3d] = %3d\n", i, buffer[i]);
}
}
// Reverse the byte order in memory
swap(buffer[0], buffer[7]);
swap(buffer[1], buffer[6]);
swap(buffer[2], buffer[5]);
swap(buffer[3], buffer[4]);
// Write 64 bit number so that it is read in big endian form
// by the native little endian 64 bit read.
if (debug) {
printf("--------\n");
for (int i = 0; i < 8; i++) {
printf("buffer[%3d] = %3d\n", i, buffer[i]);
}
}
uint64_t val;
assert(sizeof(uint64_t) == sizeof(buffer));
memcpy(&val, &buffer[0], sizeof(val));
*ptr64++ = val;
}
return result;
}
// Rewrite prefix bits as 32 bit values after padding to 4 byte bound
static inline
vector<uint8_t> PrefixBitStreamRewrite32(const vector<uint8_t> & prefixBits)
{
const bool debug = false;
// Pad until a whole 64 bit read would read until the end of the vector
vector<uint8_t> result = prefixBits;
while (1) {
uint32_t numBytes = (uint32_t) result.size();
if ((numBytes % sizeof(uint32_t)) == 0) {
break;
}
result.push_back(0);
}
// Output has been padded to a whole 32 bit values, now add one more
// padding 32 bit value to take care of reading ahead by 1 word.
for (int i = 0; i < sizeof(uint32_t); i++) {
result.push_back(0);
}
int numBytes = (int) result.size();
// Output from prefix stage must be in terms of whole dwords
if ((numBytes % sizeof(uint32_t)) != 0) {
assert(0);
}
uint32_t *ptr32 = (uint32_t *) result.data();
// Now read each set of 4 bytes into a uint32_t and store
// with a single write so that when read with uint32_t
// little endian reads the bytes are in the proper order.
int numWords = numBytes / sizeof(uint32_t);
for (int i = 0; i < numWords; i++) {
uint8_t buffer[4];
memcpy(&buffer[0], ptr32, sizeof(buffer));
if (debug) {
for (int i = 0; i < sizeof(uint32_t); i++) {
printf("buffer[%3d] = %3d\n", i, buffer[i]);
}
}
// Reverse the byte order in memory
swap(buffer[0], buffer[3]);
swap(buffer[1], buffer[2]);
// Write 64 bit number so that it is read in big endian form
// by the native little endian 64 bit read.
if (debug) {
printf("--------\n");
for (int i = 0; i < sizeof(uint32_t); i++) {
printf("buffer[%3d] = %3d\n", i, buffer[i]);
}
}
uint32_t val;
assert(sizeof(uint32_t) == sizeof(buffer));
memcpy(&val, &buffer[0], sizeof(val));
*ptr32++ = val;
}
return result;
}
// Encode N byte streams as prefix only encoded bits written
// as 64 bit LE streams. Returns a vector of split prefix bit
// streams.
static inline
void SplitPrefix64Encoding(const vector<vector<uint8_t> > & vecOfVecs,
const vector<uint8_t> & kBlockVec,
const unsigned int numSymbolsInKBlock,
vector<vector<uint8_t> > & prefixVecOfVecs,
vector<vector<uint8_t> > & suffixVecOfVecs)
{
prefixVecOfVecs.clear();
suffixVecOfVecs.clear();
// // Output destination for byte writes from N input streams
// vector<uint8_t> bytes;
int numStreams = (int) vecOfVecs.size();
int numSymbols = -1;
// All vectors must be the same length
for ( const vector<uint8_t> & vec : vecOfVecs ) {
if (numSymbols != -1) {
assert(numSymbols == (int)vec.size());
} else {
numSymbols = (int)vec.size();
}
}
const int numKBlockEachStream = numSymbols / numSymbolsInKBlock;
#if defined(DEBUG)
assert((numSymbols % numSymbolsInKBlock) == 0);
#endif // DEBUG
// Encode vector of bytes using split encoding so that prefix
// and suffix bytes are split into different streams.
vector<RiceSplit16x2Encoder<false, true, BitWriterByteStream> > encoderVec;
encoderVec.resize(numStreams);
int blocki = 0;
int numSymbolsi = 0;
// Vector of the k values for each input stream
vector<vector<uint8_t> > decoderKVecOfVecs;
// The number of symbols in each block
//vector<uint32_t> decoderNumSymbolsVecs;
for (int encoderi = 0; encoderi < encoderVec.size(); encoderi++ ) {
auto & encoder = encoderVec[encoderi];
// Encode all symbols in this stream, note that each block
// can have a different k value. and that a table is constructed
// and passed to encode this entire input stream with a
// set of k values.
const vector<uint8_t> & inByteVec = vecOfVecs[encoderi];
#if defined(DEBUG)
int blockiStart = blocki;
#endif // DEBUG
vector<uint8_t> encodeKTable(numKBlockEachStream+1);
for (int i = 0; i < numKBlockEachStream; i++) {
#if defined(DEBUG)
int maxSizeWoPadding = (int)kBlockVec.size() - 1;
assert(blocki < maxSizeWoPadding);
assert(i < encodeKTable.size());
#endif // DEBUG
encodeKTable[i] = kBlockVec[blocki++];
}
encodeKTable[numKBlockEachStream] = 0;
#if defined(DEBUG)
if ((0)) {
printf("for unmux input blocki range (%d, %d), k lookup table is:\n", blockiStart, blocki);
for (int i = 0; i < (int)encodeKTable.size(); i++ ) {
uint8_t k = encodeKTable[i];
printf("encodeKTable[%3d] = %3d\n", i, k);
}
}
#endif // DEBUG
decoderKVecOfVecs.push_back(encodeKTable);
//decoderNumSymbolsVecs.push_back(numSymbolsInKBlock);
vector<uint32_t> countTable(1);
vector<uint32_t> nTable(1);
// Number of blocks in the input, corresponds to encodeKTable.size()-1
countTable[0] = numKBlockEachStream;
// Num symbols per block
nTable[0] = numSymbolsInKBlock;
encoder.encode(inByteVec.data(), (int)inByteVec.size(),
encodeKTable.data(), (int)encodeKTable.size(),
countTable,
nTable
);
if ((0)) {
for (int i = 0; i < (int)inByteVec.size(); i++ ) {
uint8_t symbol = inByteVec[i];
printf("encoded symbol %3d with encoder for stream %d\n", symbol, encoderi);
}
}
}
// Collect rice prefix and suffix output into different result vectors
// vector<vector<uint8_t> > vecOfRiceVecs;
for ( auto & encoder : encoderVec ) {
//auto vec = encoder.bitWriter.moveBytes();
//vecOfRiceVecs.push_back(vec);
auto prefixBitsByteVec = encoder.prefixBitWriter.moveBytes();
auto prefixBitsByteVec64 = PrefixBitStreamRewrite64(prefixBitsByteVec);
prefixVecOfVecs.push_back(std::move(prefixBitsByteVec64));
// Suffix bits
auto suffixBitsByteVec = encoder.remBitWriter.moveBytes();
suffixVecOfVecs.push_back(std::move(suffixBitsByteVec));
}
/*
// Setup decoding from vector of encoded streams. Each time a byte
// is read from one of the vector of encoded streams that byte
// is emitted to a multiplexed stream of bytes.
// Configure RiceSplit16Decoder for each stream
vector<RiceSplit16Decoder<false, true, BitReaderByteStreamMultiplexer> > decoderVec;
decoderVec.resize(numStreams);
vector<vector<uint8_t> > vecOfDecodeVecs;
vecOfDecodeVecs.resize(numStreams);
{
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
auto & decoder = decoderVec[decoderi];
decoder.bitsReader.byteReader.setBytesPtr(&bytes);
auto & riceVec = vecOfRiceVecs[decoderi];
auto & decodeVec = vecOfDecodeVecs[decoderi];
decodeVec.resize(numSymbols);
decoder.setupInputOutput(riceVec.data(), (int)riceVec.size(),
decodeVec.data(), (int)decodeVec.size());
}
}
// Decode one symbols at a time with each decoder, this will
// pull byte values from N streams as the decoding operation
// progresses. Each time a byte value is pulled from the
// N input rice streams it gets appended to the mux stream.
for (int symboli = 0; symboli < numSymbols; symboli++) {
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
// Get decoder for next stream
auto & decoder = decoderVec[decoderi];
// Lookup k for corresponding input block
vector<uint8_t> & kVec = decoderKVecOfVecs[decoderi];
// FIXME: divide op is not fast!
int blockiBasedOnSymboli;
if (numSymbolsInKBlock == 64) {
blockiBasedOnSymboli = symboli / 64;
} else {
blockiBasedOnSymboli = symboli / numSymbolsInKBlock;
}
int k = kVec[blockiBasedOnSymboli];
#if defined(DEBUG)
if ((0)) {
printf("decoder %3d contains %d bits in register\n", decoderi, decoder.bitsReader.bitsInRegister);
}
int numSymbolsDecoded = decoder.decodeSymbols(k, 1);
assert(numSymbolsDecoded == 1);
auto & decodeVec = vecOfDecodeVecs[decoderi];
int symbol = decodeVec[symboli];
if ((0)) {
printf("decoded symbol %3d for stream %d\n", symbol, decoderi);
}
// Compre decoded symbol to original
const vector<uint8_t> & origByteVec = vecOfVecs[decoderi];
int origSymbol = origByteVec[symboli];
if ((0)) {
printf("original symbol %3d for stream %d\n", origSymbol, decoderi);
}
assert(symbol == origSymbol);
#else
decoder.decodeSymbols(k, 1);
#endif // DEBUG
}
}
return bytes;
*/
}
// Multiplexer rice16 encoder, encode N byte streams
// so that reads return needed bytes for each stream.
// The kBlockVec argument is a table of k values
// arranged so that each set of N entries corresponds
// to N streams. The number of symbols indicated in
// numSymbolsInKBlockVec corresponds to the block size
// in each multiplexed stream where N blocks in a row
// indicate the k value for each block in a given stream.
// Note that for best performance, the numSymbolsInKBlock
// argument should be a POT, each block must contain the
// exact same number of symbols.
static inline
vector<uint8_t> ByteStreamMultiplexer(const vector<vector<uint8_t> > & vecOfVecs,
const vector<uint8_t> & kBlockVec,
const unsigned int numSymbolsInKBlock)
{
// Output destination for byte writes from N input streams
vector<uint8_t> bytes;
int numStreams = (int) vecOfVecs.size();
int numSymbols = -1;
// All vectors must be the same length
for ( const vector<uint8_t> & vec : vecOfVecs ) {
if (numSymbols != -1) {
assert(numSymbols == (int)vec.size());
} else {
numSymbols = (int)vec.size();
}
}
const int numKBlockEachStream = numSymbols / numSymbolsInKBlock;
#if defined(DEBUG)
assert((numSymbols % numSymbolsInKBlock) == 0);
#endif // DEBUG
// Encode a vector of symbols using standard split16 method
vector<RiceSplit16Encoder<false, true, BitWriterByteStream> > encoderVec;
encoderVec.resize(numStreams);
int blocki = 0;
int numSymbolsi = 0;
// Vector of the k values for each input stream
vector<vector<uint8_t> > decoderKVecOfVecs;
// The number of symbols in each block
//vector<uint32_t> decoderNumSymbolsVecs;
for (int encoderi = 0; encoderi < encoderVec.size(); encoderi++ ) {
auto & encoder = encoderVec[encoderi];
// Encode all symbols in this stream, note that each block
// can have a different k value. and that a table is constructed
// and passed to encode this entire input stream with a
// set of k values.
const vector<uint8_t> & inByteVec = vecOfVecs[encoderi];
#if defined(DEBUG)
int blockiStart = blocki;
#endif // DEBUG
vector<uint8_t> encodeKTable(numKBlockEachStream+1);
for (int i = 0; i < numKBlockEachStream; i++) {
#if defined(DEBUG)
int maxSizeWoPadding = (int)kBlockVec.size() - 1;
assert(blocki < maxSizeWoPadding);
assert(i < encodeKTable.size());
#endif // DEBUG
encodeKTable[i] = kBlockVec[blocki++];
}
encodeKTable[numKBlockEachStream] = 0;
#if defined(DEBUG)
if ((0)) {
printf("for unmux input blocki range (%d, %d), k lookup table is:\n", blockiStart, blocki);
for (int i = 0; i < (int)encodeKTable.size(); i++ ) {
uint8_t k = encodeKTable[i];
printf("encodeKTable[%3d] = %3d\n", i, k);
}
}
#endif // DEBUG
decoderKVecOfVecs.push_back(encodeKTable);
//decoderNumSymbolsVecs.push_back(numSymbolsInKBlock);
vector<uint32_t> countTable(1);
vector<uint32_t> nTable(1);
// Number of blocks in the input, corresponds to encodeKTable.size()-1
countTable[0] = numKBlockEachStream;
// Num symbols per block
nTable[0] = numSymbolsInKBlock;
encoder.encode(inByteVec.data(), (int)inByteVec.size(),
encodeKTable.data(), (int)encodeKTable.size(),
countTable,
nTable
);
if ((0)) {
for (int i = 0; i < (int)inByteVec.size(); i++ ) {
uint8_t symbol = inByteVec[i];
printf("encoded symbol %3d with encoder for stream %d\n", symbol, encoderi);
}
}
}
// Collect each rice encoded stream into a vector
vector<vector<uint8_t> > vecOfRiceVecs;
for ( auto & encoder : encoderVec ) {
auto vec = encoder.bitWriter.moveBytes();
vecOfRiceVecs.push_back(vec);
}
// Setup decoding from vector of encoded streams. Each time a byte
// is read from one of the vector of encoded streams that byte
// is emitted to a multiplexed stream of bytes.
// Configure RiceSplit16Decoder for each stream
vector<RiceSplit16Decoder<false, true, BitReaderByteStreamMultiplexer> > decoderVec;
decoderVec.resize(numStreams);
vector<vector<uint8_t> > vecOfDecodeVecs;
vecOfDecodeVecs.resize(numStreams);
{
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
auto & decoder = decoderVec[decoderi];
decoder.bitsReader.byteReader.setBytesPtr(&bytes);
auto & riceVec = vecOfRiceVecs[decoderi];
auto & decodeVec = vecOfDecodeVecs[decoderi];
decodeVec.resize(numSymbols);
decoder.setupInputOutput(riceVec.data(), (int)riceVec.size(),
decodeVec.data(), (int)decodeVec.size());
}
}
// Decode one symbols at a time with each decoder, this will
// pull byte values from N streams as the decoding operation
// progresses. Each time a byte value is pulled from the
// N input rice streams it gets appended to the mux stream.
for (int symboli = 0; symboli < numSymbols; symboli++) {
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
// Get decoder for next stream
auto & decoder = decoderVec[decoderi];
// Lookup k for corresponding input block
vector<uint8_t> & kVec = decoderKVecOfVecs[decoderi];
// FIXME: divide op is not fast!
int blockiBasedOnSymboli;
if (numSymbolsInKBlock == 64) {
blockiBasedOnSymboli = symboli / 64;
} else {
blockiBasedOnSymboli = symboli / numSymbolsInKBlock;
}
int k = kVec[blockiBasedOnSymboli];
#if defined(DEBUG)
if ((0)) {
printf("decoder %3d contains %d bits in register\n", decoderi, decoder.bitsReader.bitsInRegister);
}
int numSymbolsDecoded = decoder.decodeSymbols(k, 1);
assert(numSymbolsDecoded == 1);
auto & decodeVec = vecOfDecodeVecs[decoderi];
int symbol = decodeVec[symboli];
if ((0)) {
printf("decoded symbol %3d for stream %d\n", symbol, decoderi);
}
// Compre decoded symbol to original
const vector<uint8_t> & origByteVec = vecOfVecs[decoderi];
int origSymbol = origByteVec[symboli];
if ((0)) {
printf("original symbol %3d for stream %d\n", origSymbol, decoderi);
}
assert(symbol == origSymbol);
#else
decoder.decodeSymbols(k, 1);
#endif // DEBUG
}
}
return bytes;
}
// Given a multiplexed stream and N indicating the number of decoders
// that will decode symbols from this stream, decode and copy
// symbols to the indicated output buffer. The outputValues
// array is known to be of size (N * N) so that each decoded
// symbol is read and written into the matrix column by column.
// This decoder requires that the number of symbols in each
// block of decoded data is constant.
static inline
void ByteStreamDemultiplexer(const unsigned int numSymbolsToDecode,
const unsigned int numStreams,
const uint8_t * inputStream,
const int inputStreamNumBytes,
uint8_t * outputValues,
const vector<uint8_t> & kBlockVec,
const unsigned int numSymbolsPerBlock)
{
// A single BitReaderByteStream object holds the decode
// state for the input multiplexed bytes. A decoder
// object pulls the next byte as needed during decoding.
BitReaderByteStream brbs;
brbs.setupInput(inputStream, inputStreamNumBytes);
// Configure RiceSplit16Decoder for each stream
vector<RiceSplit16Decoder<false, true, BitReaderByteStreamDemultiplexer> > decoderVec;
decoderVec.resize(numStreams);
{
for ( int decoderi = 0; decoderi < numStreams; decoderi++ ) {
auto & decoder = decoderVec[decoderi];
decoder.bitsReader.byteReader.setBitReaderPtr(&brbs);
uint8_t *outputPtr = &outputValues[decoderi * numSymbolsToDecode];
decoder.setupInputOutput(nullptr, -1,
outputPtr, numSymbolsToDecode);
}
}
// Create a lookup table to map each symbol in a block to the
// k value for that block. This logic only looks up a k
// value during the first symbol of a block.
unsigned int numSymbolsLeftInBlock = 0;
// This table is used to lookup k based on the decoderi
// and the blocki in the stream.
const int numSymbolsEachStream = numSymbolsToDecode / numSymbolsPerBlock;
vector<uint8_t> kLookup(numStreams);
// uint8_t kLookup[numStreams];
// Decode each symbol in each stream. This is the memory and CPU
// intensive portion of the decoding operation.
int blocki = 0;
for ( int symboli = 0; symboli < numSymbolsToDecode; symboli++ ) {
if (numSymbolsLeftInBlock == 0) {
for ( int decoderi = 0; decoderi < numStreams; decoderi++ ) {
int offset = (decoderi * numSymbolsEachStream) + blocki;
#if defined(DEBUG)
assert(decoderi < numStreams);
assert(offset < (kBlockVec.size()-1));
#endif // DEBUG
kLookup[decoderi] = kBlockVec[offset];
}
numSymbolsLeftInBlock = numSymbolsPerBlock;
blocki += 1;
}
for ( int decoderi = 0; decoderi < numStreams; decoderi++ ) {
// For each stream, decode 1 symbol. This logic
// loads multiplexed bytes from the combined
// stream as needed for different streams.
int k = kLookup[decoderi];
auto & decoder = decoderVec[decoderi];
#if defined(DEBUG)
int numSymbols = decoder.decodeSymbols(k, 1);
assert(numSymbols == 1);
uint8_t *outputPtr = &outputValues[decoderi * numSymbolsToDecode];
int symbol = outputPtr[symboli];
if ((0)) {
printf("decoded symbol %3d with decoder for stream %d and k %d\n", symbol, decoderi, k);
}
#else
decoder.decodeSymbols(k, 1);
#endif // DEBUG
}
numSymbolsLeftInBlock -= 1;
}
return;
}
// 4x decoder implementation where a vector of bit reader objects
// are passed in and the decoding loop approach pulls 64 bit
// word values based on decoding multiple symbols at the same time.
template<class BRBS>
void reader_process_zero16_or_regular(
uint8_t* & outBytes, // ref to pointer
BitReader64<BRBS, 16> & reader)
{
const bool debug = false;
if ((reader.bits1 >> (32+16)) == (uint64_t)0) {
// Special case for 16 bits of zeros in high halfword
# if defined(DEBUG)
assert(reader.numBits1 >= 16);
# endif // DEBUG
reader.numBits1 -= (uint64_t)16;
if (debug) {
printf("bits : %s\n", get_code_bits_as_string64(reader.numBits1, 64).c_str());
}
reader.bits1 <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(reader.bits1, 64).c_str());
}
*outBytes++ = (uint64_t)17;
} else {
# if defined(DEBUG)
const uint16_t top16 = (reader.bits1 >> (32+16));
assert(top16 != 0);
# endif // DEBUG
uint64_t q = __clz(reader.bits1);
if (debug) {
printf("q (num leading zeros): %d\n", (int)q);
}
// Shift left to drop prefix bits from left side of register.
uint64_t prefixCount = q + (uint64_t)1;
# if defined(DEBUG)
assert(reader.numBits1 >= prefixCount);
# endif // DEBUG
reader.numBits1 -= prefixCount;
reader.bits1 <<= prefixCount;
if (debug) {
printf("lshift %2d : %s\n", (int)prefixCount, get_code_bits_as_string64(reader.bits1, 64).c_str());
}
*outBytes++ = prefixCount;
}
return;
}
template <class T>
void stream_part_process_zero16_or_regular(
uint8_t* & outBytes, // ref to pointer
T & sp)
{
const bool debug = false;
if ((sp.bits >> (32+16)) == (uint64_t)0) {
// Special case for 16 bits of zeros in high halfword
# if defined(DEBUG)
assert(sp.numBits >= 16);
# endif // DEBUG
sp.numBits -= (uint64_t)16;
if (debug) {
printf("bits : %s\n", get_code_bits_as_string64(sp.numBits, 64).c_str());
}
sp.bits <<= 16;
if (debug) {
printf("bits (del16): %s\n", get_code_bits_as_string64(sp.bits, 64).c_str());
}
*outBytes++ = (uint64_t)17;
} else {
# if defined(DEBUG)
const uint16_t top16 = (sp.bits >> (32+16));
assert(top16 != 0);
# endif // DEBUG
uint64_t q = __clz(sp.bits);
if (debug) {
printf("q (num leading zeros): %d\n", (int)q);
}
// Shift left to drop prefix bits from left side of register.
uint64_t prefixCount = q + (uint64_t)1;
# if defined(DEBUG)
assert(sp.numBits >= prefixCount);
# endif // DEBUG
sp.numBits -= prefixCount;
sp.bits <<= prefixCount;
if (debug) {
printf("lshift %2d : %s\n", (int)prefixCount, get_code_bits_as_string64(sp.bits, 64).c_str());
}
*outBytes++ = prefixCount;
}
return;
}
template<class BRBS>
void rice_decode_prefix_bits_4x_both_interleaved_readers(
vector<BitReader64<BRBS, 16> > & readers,
uint64_t numSymbolsToDecode,
uint8_t *outBytes)
{
#pragma unroll(1)
for ( ; numSymbolsToDecode != 0 ; ) {
//dual_dword_refill_lt16(inBytesLE64, s1PrefixBits1, s1PrefixBits2, s1PrefixNumBits1, s1PrefixNumBits2);
//dual_dword_refill_lt16(inBytesLE64, s2PrefixBits1, s2PrefixBits2, s2PrefixNumBits1, s2PrefixNumBits2);
//dual_dword_refill_lt16(inBytesLE64, s3PrefixBits1, s3PrefixBits2, s3PrefixNumBits1, s3PrefixNumBits2);
//dual_dword_refill_lt16(inBytesLE64, s4PrefixBits1, s4PrefixBits2, s4PrefixNumBits1, s4PrefixNumBits2);
readers[0].refillBits();
readers[1].refillBits();
readers[2].refillBits();
readers[3].refillBits();
// Process special case of 16 zero bits or the next symbol for each stream.
reader_process_zero16_or_regular(outBytes, readers[0]);
reader_process_zero16_or_regular(outBytes, readers[1]);
reader_process_zero16_or_regular(outBytes, readers[2]);
reader_process_zero16_or_regular(outBytes, readers[3]);
numSymbolsToDecode -= 1;
// Combined loop that decodes 1 symbol from each stream
#pragma unroll(1)
while (((readers[0].bits1 >> (32+16)) != (uint64_t)0) &&
((readers[1].bits1 >> (32+16)) != (uint64_t)0) &&
((readers[2].bits1 >> (32+16)) != (uint64_t)0) &&
((readers[3].bits1 >> (32+16)) != (uint64_t)0)) {
# if defined(DEBUG)
{
const uint16_t top16 = (readers[0].bits1 >> (32+16));
assert(top16 != 0);
}
{
const uint16_t top16 = (readers[1].bits1 >> (32+16));
assert(top16 != 0);
}
{
const uint16_t top16 = (readers[2].bits1 >> (32+16));
assert(top16 != 0);
}
{
const uint16_t top16 = (readers[3].bits1 >> (32+16));
assert(top16 != 0);
}
# endif // DEBUG
uint64_t prefixCount1 = __clz(readers[0].bits1);
uint64_t prefixCount2 = __clz(readers[1].bits1);
uint64_t prefixCount3 = __clz(readers[2].bits1);
uint64_t prefixCount4 = __clz(readers[3].bits1);
prefixCount1 += 1;
prefixCount2 += 1;
prefixCount3 += 1;
prefixCount4 += 1;
// Shift left to drop prefix bits from left side of register.
# if defined(DEBUG)
assert(prefixCount1 < 17);
assert(prefixCount2 < 17);
assert(prefixCount3 < 17);
assert(prefixCount4 < 17);
# endif // DEBUG
# if defined(DEBUG)
assert(readers[0].numBits1 >= prefixCount1);
assert(readers[1].numBits1 >= prefixCount2);
assert(readers[2].numBits1 >= prefixCount3);
assert(readers[3].numBits1 >= prefixCount4);
# endif // DEBUG
numSymbolsToDecode -= 1;
readers[0].bits1 <<= prefixCount1;
readers[1].bits1 <<= prefixCount2;
readers[2].bits1 <<= prefixCount3;
readers[3].bits1 <<= prefixCount4;
*outBytes++ = (uint8_t) prefixCount1;
readers[0].numBits1 -= prefixCount1;
*outBytes++ = (uint8_t) prefixCount2;
readers[1].numBits1 -= prefixCount2;
*outBytes++ = (uint8_t) prefixCount3;
readers[2].numBits1 -= prefixCount3;
*outBytes++ = (uint8_t) prefixCount4;
readers[3].numBits1 -= prefixCount4;
}
}
return;
}
// This logic implements interleaved reading with one 64 bit reader and an approach
// that inserts the exact number of bits into each bits register so that the
// register is completely full. This logic does not maintain
static inline
void rice_decode_prefix_bits_n_both_interleaved_readers_bit_insert(
vector<BitReader64ReaderPart<BitReaderStream64> > & readerPartVec,
vector<BitReader64StreamPart<BitReaderStream64> > & streamPartVec,
uint64_t numSymbolsToDecode,
uint8_t *outBytes
#if defined(DEBUG)
,
unordered_map<string, int> * countMapPtr
#endif // DEBUG
)
{
assert(readerPartVec.size() == streamPartVec.size());
assert(readerPartVec.size() > 1);
#pragma unroll(1)
for ( ; numSymbolsToDecode != 0 ; ) {
//dual_dword_refill_lt16(inBytesLE64, s1PrefixBits1, s1PrefixBits2, s1PrefixNumBits1, s1PrefixNumBits2);
//dual_dword_refill_lt16(inBytesLE64, s2PrefixBits1, s2PrefixBits2, s2PrefixNumBits1, s2PrefixNumBits2);
//dual_dword_refill_lt16(inBytesLE64, s3PrefixBits1, s3PrefixBits2, s3PrefixNumBits1, s3PrefixNumBits2);
//dual_dword_refill_lt16(inBytesLE64, s4PrefixBits1, s4PrefixBits2, s4PrefixNumBits1, s4PrefixNumBits2);
for (int i = 0; i < readerPartVec.size(); i++) {
streamPartVec[i].refillBits(readerPartVec[i]);
}
#if defined(DEBUG)
if (countMapPtr) {
(*countMapPtr)["refill64"] += readerPartVec.size();
}
#endif // DEBUG
// Process special case of 16 zero bits or the next symbol for each stream.
for (int i = 0; i < readerPartVec.size(); i++) {
stream_part_process_zero16_or_regular(outBytes, streamPartVec[i]);
}
#if defined(DEBUG)
if (countMapPtr) {
(*countMapPtr)["zero16OrSymbol"] += readerPartVec.size();
}
#endif // DEBUG
numSymbolsToDecode -= 1;
// Combined loop that decodes 1 symbol from each stream
#pragma unroll(1)
while (1) {
bool hasZeros = false;
for (int i = 0; i < readerPartVec.size(); i++) {
if ((streamPartVec[i].bits >> (32+16)) == (uint64_t)0) {
// break out of while loop and refill once one of the stream has 16 zeros
hasZeros = true;
break;
}
}
if (hasZeros) {
#if defined(DEBUG)
if (countMapPtr) {
(*countMapPtr)["zero16FoundReload"] += 1;
}
#endif // DEBUG
break;
}
# if defined(DEBUG)
for (int i = 0; i < readerPartVec.size(); i++) {
const uint16_t top16 = (streamPartVec[i].bits >> (32+16));
assert(top16 != 0);
}
# endif // DEBUG
#if defined(DEBUG)
// Incr +1 for each block of N symbols
if (countMapPtr) {
(*countMapPtr)["processBlockOfSymbols"] += 1;
}
#endif // DEBUG
for (int i = 0; i < readerPartVec.size(); i++) {
stream_part_process_zero16_or_regular(outBytes, streamPartVec[i]);
# if defined(DEBUG)
// Should never execute first branch of if
assert(*(outBytes - 1) != 17);
# endif // DEBUG
}
numSymbolsToDecode -= 1;
/*
// FIXME: would need a vec of each prefixCount, bits, output byte
uint64_t prefixCount1 = __clz(streamPartVec[0].bits);
uint64_t prefixCount2 = __clz(streamPartVec[1].bits);
uint64_t prefixCount3 = __clz(streamPartVec[2].bits);
uint64_t prefixCount4 = __clz(streamPartVec[3].bits);
prefixCount1 += 1;
prefixCount2 += 1;
prefixCount3 += 1;
prefixCount4 += 1;
// Shift left to drop prefix bits from left side of register.
# if defined(DEBUG)
assert(prefixCount1 < 17);
assert(prefixCount2 < 17);
assert(prefixCount3 < 17);
assert(prefixCount4 < 17);
# endif // DEBUG
# if defined(DEBUG)
assert(streamPartVec[0].numBits >= prefixCount1);
assert(streamPartVec[1].numBits >= prefixCount2);
assert(streamPartVec[2].numBits >= prefixCount3);
assert(streamPartVec[3].numBits >= prefixCount4);
# endif // DEBUG
numSymbolsToDecode -= 1;
streamPartVec[0].bits <<= prefixCount1;
streamPartVec[1].bits <<= prefixCount2;
streamPartVec[2].bits <<= prefixCount3;
streamPartVec[3].bits <<= prefixCount4;
*outBytes++ = (uint8_t) prefixCount1;
streamPartVec[0].numBits -= prefixCount1;
*outBytes++ = (uint8_t) prefixCount2;
streamPartVec[1].numBits -= prefixCount2;
*outBytes++ = (uint8_t) prefixCount3;
streamPartVec[2].numBits -= prefixCount3;
*outBytes++ = (uint8_t) prefixCount4;
streamPartVec[3].numBits -= prefixCount4;
*/
}
}
return;
}
// 64 bit stream multiplexer, this logic splits rice encoding into prefix and suffix
// streams and then the prefix bit streams are mixed together into a multiplexed stream.
// FIXME: return vector of suffix bytes and k vector split into N segments ?
static inline
vector<uint64_t> ByteStreamMultiplexer64(
const vector<vector<uint8_t> > & vecOfVecs,
const vector<uint8_t> & kBlockVec,
const unsigned int numSymbolsInKBlock)
{
// Output destination for byte writes from N input streams
vector<uint64_t> multiplexVec;
int numStreams = (int) vecOfVecs.size();
int numSymbols = -1;
// All vectors must be the same length
for ( const vector<uint8_t> & vec : vecOfVecs ) {
if (numSymbols != -1) {
assert(numSymbols == (int)vec.size());
} else {
numSymbols = (int)vec.size();
}
}
// Actual encoded num bytes will be smaller that this max size
multiplexVec.reserve(((numSymbols * numStreams) / sizeof(uint64_t)));
const int numKBlockEachStream = numSymbols / numSymbolsInKBlock;
#if defined(DEBUG)
assert((numSymbols % numSymbolsInKBlock) == 0);
#endif // DEBUG
// Encode a vector of symbols using standard split16 method
// and a split into prefix and suffix buffers.
vector<RiceSplit16x2Encoder<false, true, BitWriterByteStream> > encoderVec;
encoderVec.resize(numStreams);
int blocki = 0;
//int numSymbolsi = 0;
// Vector of the k values for each input stream
vector<vector<uint8_t> > decoderKVecOfVecs;
// The number of symbols in each block
//vector<uint32_t> decoderNumSymbolsVecs;
for (int encoderi = 0; encoderi < encoderVec.size(); encoderi++ ) {
auto & encoder = encoderVec[encoderi];
// Encode all symbols in this stream, note that each block
// can have a different k value. and that a table is constructed
// and passed to encode this entire input stream with a
// set of k values.
const vector<uint8_t> & inByteVec = vecOfVecs[encoderi];
#if defined(DEBUG)
int blockiStart = blocki;
#endif // DEBUG
vector<uint8_t> encodeKTable(numKBlockEachStream+1);
for (int i = 0; i < numKBlockEachStream; i++) {
#if defined(DEBUG)
int maxSizeWoPadding = (int)kBlockVec.size() - 1;
assert(blocki < maxSizeWoPadding);
assert(i < encodeKTable.size());
#endif // DEBUG
encodeKTable[i] = kBlockVec[blocki++];
}
encodeKTable[numKBlockEachStream] = 0;
#if defined(DEBUG)
if ((0)) {
printf("for unmux input blocki range (%d, %d), k lookup table is:\n", blockiStart, blocki);
for (int i = 0; i < (int)encodeKTable.size(); i++ ) {
uint8_t k = encodeKTable[i];
printf("encodeKTable[%3d] = %3d\n", i, k);
}
}
#endif // DEBUG
decoderKVecOfVecs.push_back(encodeKTable);
//decoderNumSymbolsVecs.push_back(numSymbolsInKBlock);
vector<uint32_t> countTable(1);
vector<uint32_t> nTable(1);
// Number of blocks in the input, corresponds to encodeKTable.size()-1
countTable[0] = numKBlockEachStream;
// Num symbols per block
nTable[0] = numSymbolsInKBlock;
encoder.encode(inByteVec.data(), (int)inByteVec.size(),
encodeKTable.data(), (int)encodeKTable.size(),
countTable,
nTable
);
if ((0)) {
for (int i = 0; i < (int)inByteVec.size(); i++ ) {
uint8_t symbol = inByteVec[i];
printf("encoded symbol %3d with encoder for stream %d\n", symbol, encoderi);
}
}
}
// Collect each rice encoded stream into a vector
vector<vector<uint8_t> > prefixVecOfVecs;
vector<vector<uint8_t> > suffixVecOfVecs;
// Decoded unary values as bytes (1, 17)
vector<vector<uint8_t> > prefixUnaryVecOfVecs;
for ( auto & encoder : encoderVec ) {
auto prefixBitsByteVec = encoder.prefixBitWriter.moveBytes();
// FIXME: does this additional zero padding on the stream
// actually mess up the mixed streams?
// Convert to LE 64 read ordering and add zero padding
auto prefixBitsByteVec64 = PrefixBitStreamRewrite64(prefixBitsByteVec);
prefixVecOfVecs.push_back(std::move(prefixBitsByteVec64));
// Suffix bits
auto suffixBitsByteVec = encoder.remBitWriter.moveBytes();
suffixVecOfVecs.push_back(std::move(suffixBitsByteVec));
// Store encoded prefix byte values for decode comparison
prefixUnaryVecOfVecs.push_back(std::move(encoder.unaryNBytes));
}
// Vector of bytes is already formatted as 64 bit values, but
// it must be explicitly converted to make C++ happy.
vector<vector<uint64_t> > prefixVecOfVec64;
prefixVecOfVec64.resize(numStreams);
{
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
vector<uint8_t> prefixByteVecBytes = prefixVecOfVecs[decoderi];
// Vector of bytes is already formatted as 64 bit values, but
// it must be explicitly converted to make C++ happy.
vector<uint64_t> & vec64 = prefixVecOfVec64[decoderi];
uint64_t numDwords = prefixByteVecBytes.size() / sizeof(uint64_t);
#if defined(DEBUG)
assert((prefixByteVecBytes.size() % sizeof(uint64_t)) == 0);
#endif // DEBUG
vec64.resize((int)numDwords);
memcpy(vec64.data(), prefixByteVecBytes.data(), prefixByteVecBytes.size());
}
}
// The next phase decodes from N prefix streams. Each time
// a prefix stream runs low on bits a 64 bit read is executed
// and this operation indicates the ordering of 64 bit values
// in the multiplexed stream.
//typedef RiceSplit16x2PrefixDecoder64Read64<BitReaderStream64> Decoder64T;
typedef RiceSplit16x2PrefixDecoder64Read64<BitReaderByteStreamMultiplexer64> Decoder64T;
vector<Decoder64T> decoderVec;
decoderVec.resize(numStreams);
vector<vector<uint8_t> > vecOfDecodedSymbolsVec;
vecOfDecodedSymbolsVec.resize(numStreams);
{
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
auto & decoder = decoderVec[decoderi];
// Invoke setupOutput() to store output buffer pointer
auto & decodedSymbolsVec = vecOfDecodedSymbolsVec[decoderi];
decodedSymbolsVec.resize(numSymbols);
decoder.setupOutput(decodedSymbolsVec.data());
// Prefix bits encoded as LE 64 bit padded read stream.
vector<uint64_t> & vec64 = prefixVecOfVec64[decoderi];
decoder.prefixBitsReader.byteReader64.setupInput(vec64.data());
// In addition, BitReaderByteStreamMultiplexer64 requires that an
// output stream that interleaves 64 bit writes be defined.
decoder.prefixBitsReader.byteReader64.setMultiplexVecPtr(&multiplexVec);
}
}
// For each symbol to be decoded, pull prefix value from each stream.
// This logic interleaves 64 bit reads from N streams into a combined
// stream that can then be decoded by reading in the same order.
/*
#if defined(DEBUG)
int totalDecodedNumSymbols = 0;
#endif // DEBUG
for (int symboli = 0; symboli < numSymbols; symboli++) {
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
// Get decoder for next stream
auto & decoder = decoderVec[decoderi];
#if defined(DEBUG)
int numSymbolsDecoded = decoder.decodeSymbols(1);
assert(numSymbolsDecoded == 1);
totalDecodedNumSymbols += 1;
auto & decodedSymbolsVec = vecOfDecodedSymbolsVec[decoderi];
int symbol = decodedSymbolsVec[symboli];
if ((0)) {
printf("decoded symbol %3d for stream %d\n", symbol, decoderi);
}
// Compare decoded prefix to original value
const vector<uint8_t> & origPrefixUnaryVec = prefixUnaryVecOfVecs[decoderi];
int origPrefixSymbol = origPrefixUnaryVec[symboli];
if ((0)) {
printf("original symbol %3d for stream %d\n", origPrefixSymbol, decoderi);
}
assert(symbol == origPrefixSymbol);
#else
decoder.decodeSymbols(1);
#endif // DEBUG
}
}
*/
vector<BitReader64<BitReaderByteStreamMultiplexer64, 16> > vecOfReaders;
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
auto & decoder = decoderVec[decoderi];
vecOfReaders.push_back(decoder.prefixBitsReader);
}
vector<uint8_t> outputInterleavedVec;
outputInterleavedVec.resize(numSymbols * 4);
rice_decode_prefix_bits_4x_both_interleaved_readers(vecOfReaders, numSymbols, outputInterleavedVec.data());
/*
// FIXME: Decode symbols from this mixed stream format using a decoder
// and verify that the decoded symbols are exactly as expected.
vector<RiceSplit16x2PrefixDecoder64Read64<BitReaderStream64>> demuxDecoderVec;
demuxDecoderVec.resize(numStreams);
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
auto & decoder = demuxDecoderVec[decoderi];
// Invoke setupOutput() to store output buffer pointer
auto & decodedSymbolsVec = vecOfDecodedSymbolsVec[decoderi];
memset(decodedSymbolsVec.data(), 0, decodedSymbolsVec.size());
decoder.setupOutput(decodedSymbolsVec.data());
// Input is mixed 64 bit stream where each 64 bit read is done
// by different decoders.
// vector<uint64_t> & vec64 = prefixVecOfVec64[decoderi];
// decoder.prefixBitsReader.byteReader64.setupInput(vec64.data());
// In addition, BitReaderByteStreamMultiplexer64 requires that an
// output stream that interleaves 64 bit writes be defined.
// decoder.prefixBitsReader.byteReader64.setMultiplexVecPtr(&multiplexVec);
}
for (int symboli = 0; symboli < numSymbols; symboli++) {
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
// Get decoder for next stream
auto & decoder = demuxDecoderVec[decoderi];
#if defined(DEBUG)
int numSymbolsDecoded = decoder.decodeSymbols(1);
assert(numSymbolsDecoded == 1);
totalDecodedNumSymbols += 1;
auto & decodedSymbolsVec = vecOfDecodedSymbolsVec[decoderi];
int symbol = decodedSymbolsVec[symboli];
if ((0)) {
printf("decoded symbol %3d for stream %d\n", symbol, decoderi);
}
// Compare decoded prefix to original value
const vector<uint8_t> & origPrefixUnaryVec = prefixUnaryVecOfVecs[decoderi];
int origPrefixSymbol = origPrefixUnaryVec[symboli];
if ((0)) {
printf("original symbol %3d for stream %d\n", origPrefixSymbol, decoderi);
}
assert(symbol == origPrefixSymbol);
#else
decoder.decodeSymbols(1);
#endif // DEBUG
}
}
*/
// Output should be exactly as the decoder needs it taking padding
// and read 1 ahead into account.
// Add 1 unit of zero padding at the end for each stream
// for (int decoderi = 0; decoderi < numStreams; decoderi++) {
// multiplexVec.push_back(0);
// }
return multiplexVec;
}
// Given a stream of bytes interleaved as (S0, S1, ..., SN-1) deinterleave
// the values and return in original order.
static inline
vector<uint8_t> ByteStreamDeinterleaveN(const vector<uint8_t> & inBytes, const int N)
{
vector<vector<uint8_t> > vecOfVecs;
vecOfVecs.resize(N);
assert(((int) inBytes.size() % N) == 0);
const int numIters = (int) inBytes.size() / N;
assert(numIters > 0);
for (int i = 0; i < N; i++) {
vecOfVecs[i].reserve(numIters);
}
const uint8_t *bytePtr = inBytes.data();
for (int segi = 0; segi < numIters; segi++) {
for (int i = 0; i < N; i++) {
uint8_t bVal = *bytePtr++;
vecOfVecs[i].push_back(bVal);
}
}
// Concat each entry in vecOfVecs
vector<uint8_t> combined;
combined.reserve(N * numIters);
for ( auto & vec : vecOfVecs ) {
for ( uint8_t bVal : vec ) {
combined.push_back(bVal);
}
}
assert(combined.size() == inBytes.size());
return combined;
}
// New interleaved approach where variable bit width interleaving is used to fully
// refill each bit buffer with no second overflow fill buffer.
static inline
vector<uint64_t> ByteStreamMultiplexer64InterleavedN(
const vector<vector<uint8_t> > & vecOfVecs,
const vector<uint8_t> & kBlockVec,
const unsigned int numSymbolsInKBlock,
// The split encoding output
vector<vector<uint8_t> > & prefixVecOfVecs,
vector<vector<uint8_t> > & suffixVecOfVecs,
vector<vector<uint8_t> > & kTableVecOfVecs,
vector<vector<uint8_t> > & prefixUnaryNVecOfVecs
)
{
// Output destination for byte writes from N input streams
vector<uint64_t> multiplexVec;
int numStreams = (int) vecOfVecs.size();
int numSymbols = -1;
// All vectors must be the same length
for ( const vector<uint8_t> & vec : vecOfVecs ) {
if (numSymbols != -1) {
assert(numSymbols == (int)vec.size());
} else {
numSymbols = (int)vec.size();
}
}
// Actual encoded num bytes will be smaller that this max size
//multiplexVec.reserve(((numSymbols * numStreams) / sizeof(uint64_t)));
const int numKBlockEachStream = numSymbols / numSymbolsInKBlock;
#if defined(DEBUG)
assert((numSymbols % numSymbolsInKBlock) == 0);
#endif // DEBUG
// Encode a subrange of symbols using standard split16 method
// and a split into prefix and suffix buffers.
vector<RiceSplit16x2Encoder<false, true, BitWriterByteStream> > encoderVec;
encoderVec.resize(numStreams);
int blocki = 0;
//int numSymbolsi = 0;
// Vector of the k values for each input stream
vector<vector<uint8_t> > decoderKVecOfVecs;
// The number of symbols in each block
//vector<uint32_t> decoderNumSymbolsVecs;
for (int encoderi = 0; encoderi < encoderVec.size(); encoderi++ ) {
auto & encoder = encoderVec[encoderi];
// Encode all symbols in this stream, note that each block
// can have a different k value. and that a table is constructed
// and passed to encode this entire input stream with a
// set of k values.
const vector<uint8_t> & inByteVec = vecOfVecs[encoderi];
#if defined(DEBUG)
int blockiStart = blocki;
#endif // DEBUG
vector<uint8_t> encodeKTable(numKBlockEachStream+1);
for (int i = 0; i < numKBlockEachStream; i++) {
#if defined(DEBUG)
int maxSizeWoPadding = (int)kBlockVec.size() - 1;
assert(blocki < maxSizeWoPadding);
assert(i < encodeKTable.size());
#endif // DEBUG
encodeKTable[i] = kBlockVec[blocki++];
}
encodeKTable[numKBlockEachStream] = 0;
#if defined(DEBUG)
if ((0)) {
printf("for unmux input blocki range (%d, %d), k lookup table is:\n", blockiStart, blocki);
for (int i = 0; i < (int)encodeKTable.size(); i++ ) {
uint8_t k = encodeKTable[i];
printf("encodeKTable[%3d] = %3d\n", i, k);
}
}
#endif // DEBUG
decoderKVecOfVecs.push_back(encodeKTable);
//decoderNumSymbolsVecs.push_back(numSymbolsInKBlock);
vector<uint32_t> countTable(1);
vector<uint32_t> nTable(1);
// Number of blocks in the input, corresponds to encodeKTable.size()-1
countTable[0] = numKBlockEachStream;
// Num symbols per block
nTable[0] = numSymbolsInKBlock;
kTableVecOfVecs.push_back(encodeKTable); // save sub ktable
encoder.encode(inByteVec.data(), (int)inByteVec.size(),
encodeKTable.data(), (int)encodeKTable.size(),
countTable,
nTable
);
if ((0)) {
for (int i = 0; i < (int)inByteVec.size(); i++ ) {
uint8_t symbol = inByteVec[i];
printf("encoded symbol %3d with encoder for stream %d\n", symbol, encoderi);
}
}
}
for ( auto & encoder : encoderVec ) {
auto prefixBitsByteVec = encoder.prefixBitWriter.moveBytes();
// FIXME: does this additional zero padding on the stream
// actually mess up the mixed streams?
// Convert to LE 64 read ordering and add zero padding
auto prefixBitsByteVec64 = PrefixBitStreamRewrite64(prefixBitsByteVec);
prefixVecOfVecs.push_back(std::move(prefixBitsByteVec64));
// Suffix bits
auto suffixBitsByteVec = encoder.remBitWriter.moveBytes();
suffixVecOfVecs.push_back(std::move(suffixBitsByteVec));
// Store encoded prefix byte values for decode comparison
prefixUnaryNVecOfVecs.push_back(std::move(encoder.unaryNBytes));
}
// Vector of bytes is already formatted as 64 bit values, but
// it must be explicitly converted to make C++ happy.
vector<vector<uint64_t> > prefixVecOfVec64;
prefixVecOfVec64.resize(numStreams);
{
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
vector<uint8_t> prefixByteVecBytes = prefixVecOfVecs[decoderi];
// Vector of bytes is already formatted as 64 bit values, but
// it must be explicitly converted to make C++ happy.
vector<uint64_t> & vec64 = prefixVecOfVec64[decoderi];
uint64_t numDwords = prefixByteVecBytes.size() / sizeof(uint64_t);
#if defined(DEBUG)
assert((prefixByteVecBytes.size() % sizeof(uint64_t)) == 0);
#endif // DEBUG
vec64.resize((int)numDwords);
memcpy(vec64.data(), prefixByteVecBytes.data(), prefixByteVecBytes.size());
}
}
// This multiplexing implementation encodes with variable width bit buffers
// needed to fully fill the bit buffer for each of N streams. Unlike a fixed
// read approach, this encoding minimized read buffering for each stream.
vector<BitReader64ReaderPart<BitReaderStream64>> readerPartVec(numStreams);
vector<BitReader64StreamPart<BitReaderStream64>> streamPartVec(numStreams);
vector<vector<uint8_t> > vecOfDecodedSymbolsVec;
vecOfDecodedSymbolsVec.resize(numStreams);
// Interleaved bit writer
BitWriter<true,BitWriterByteStream> bitWriter;
{
for (int decoderi = 0; decoderi < numStreams; decoderi++) {
//auto & decoder = decoderVec[decoderi];
// Invoke setupOutput() to store output buffer pointer
//auto & decodedSymbolsVec = vecOfDecodedSymbolsVec[decoderi];
//decodedSymbolsVec.resize(numSymbols);
//decoder.setupOutput(decodedSymbolsVec.data());
// Prefix bits encoded as LE 64 bit padded read stream.
// Setup a reader for each encoded prefix bits stream
vector<uint64_t> & vec64 = prefixVecOfVec64[decoderi];
auto & rp = readerPartVec[decoderi];
rp.byteReader64.setupInput(vec64.data());
printf("in bytes vec %d\n", (int)(vec64.size()*sizeof(uint64_t)));
rp.initBits();
// Configure stream by connecting bit interleaving output
auto & sp = streamPartVec[decoderi];
sp.bitWriterPtr = &bitWriter;
}
}
vector<uint8_t> outputInterleavedVec;
outputInterleavedVec.resize(numSymbols * numStreams);
#if defined(DEBUG)
unordered_map<string, int> countMap;
#endif // DEBUG
rice_decode_prefix_bits_n_both_interleaved_readers_bit_insert(readerPartVec,
streamPartVec,
numSymbols,
outputInterleavedVec.data()
#if defined(DEBUG)
,
&countMap
#endif // DEBUG
);
#if defined(DEBUG)
for ( auto & pair : countMap ) {
printf("%8d <- %s\n", pair.second, pair.first.c_str());
}
#endif // DEBUG
#if defined(DEBUG)
// Examine interleaved decoded unary byte values and make sure
// these value match the original unary N values from the encoder.
// These values are interleaved as (S0, S1, S2, ...)
vector<uint8_t> recombinedUnary;
for ( auto & vec : prefixUnaryNVecOfVecs ) {
for ( uint8_t bVal : vec ) {
recombinedUnary.push_back(bVal);
}
}
vector<uint8_t> streamOrder = ByteStreamDeinterleaveN(outputInterleavedVec, numStreams);
assert(streamOrder.size() == outputInterleavedVec.size());
assert(streamOrder.size() == recombinedUnary.size());
for ( int i = 0; i < streamOrder.size(); i++) {
int v1 = streamOrder[i];
int v2 = recombinedUnary[i];
assert(v1 == v2);
}
#endif // DEBUG
// Bit writes sent to bitWriter, but need to convert back to
// 64 bit values in order to return in acceptable form.
bitWriter.flushByte();
printf("num bits encoded interleaved %d : num bytes %d\n", bitWriter.numEncodedBits, bitWriter.numEncodedBits/8);
// FIXME: Verify that output number of bits exactly matches the input number of bits
// from N different streams?
// Copy bytes padded to whole 64 bit bound
vector<uint8_t> multiplexedByteVec = bitWriter.moveBytes();
// int numBytes = (int) byteVector.size();
//
// while ((numBytes % sizeof(uint64_t)) != 0) {
// numBytes++;
// }
//
// multiplexVec.resize(numBytes);
//
// memcpy(multiplexVec.data(), byteVector.data(), byteVector.size());
// Rewrite byte ordering to LE 64 bit ordering so that native read in
// gets bytes in proper MSB ordering directly.
vector<uint8_t> bytes64 = PrefixBitStreamRewrite64(multiplexedByteVec);
assert((bytes64.size() % sizeof(uint64_t)) == 0);
// Reformatted bytes now in terms of 64 bit chunks
multiplexVec.resize(bytes64.size() / sizeof(uint64_t));
memcpy(multiplexVec.data(), bytes64.data(), bytes64.size());
// FIXME: bits were readd from 64 bit stream layout but are no longer
// in LE ordering. Need to reorder them as 64 bit LE again before using.
return multiplexVec;
}
// Generate 32 bit k table offsets from a zero terminated table
static inline
void
GenerateSuffixBlockStartTable(uint8_t *blockOptimalKTable,
int blockOptimalKTableLength,
uint32_t *offsets,
const int blockDim)
{
uint32_t offset = 0;
offsets[0] = 0;
int kBitWidth = blockOptimalKTable[0];
// Next block starts at the k bit width times the number of symbols in one block
kBitWidth *= (blockDim * blockDim);
offset += kBitWidth;
for (int i = 1; i < blockOptimalKTableLength-1; i++) {
offsets[i] = offset;
int kBitWidth = blockOptimalKTable[i];
// Next block starts at the k bit width times the number of symbols in one block
kBitWidth *= (blockDim * blockDim);
#if defined(DEBUG)
{
uint64_t offset64 = offset;
offset64 += kBitWidth;
assert(offset64 <= 0xFFFFFFFF);
}
#endif // DEBUG
offset += kBitWidth;
}
return;
}
// Generate table with 6 bit key that covers 64 values. The lookup
// table contains 16 bit entries with a maximum of 4 nibble values
// in the range (0, 15)
static inline
vector<uint16_t>
PrefixBitStreamGenerateLookupTable64K6Bits()
{
const bool debug = false;
// 64 entries for 6 bits
vector<uint16_t> generatedTable;
const int tableSize = 64;
generatedTable.resize(tableSize);
for ( int i = 0; i < tableSize; i++) {
if (debug) {
printf("table entry i %d\n", i);
}
uint32_t keyBits = ((uint32_t)i) << (32 - 8) << 2;
if (debug) {
uint32_t keyBits6 = ((uint32_t)i);
printf("bits %s for i %d\n", get_code_bits_as_string64(keyBits, 32).c_str(), i);
printf("keyBits6 %s for i %d\n", get_code_bits_as_string64((keyBits6), 6).c_str(), i);
}
// loop N times, max of 4 lookup values in 16 bits
unsigned int q;
unsigned int bi = 0;
uint16_t bits16 = 0;
while (keyBits != 0) {
if (bi >= 4) {
break;
}
if (debug) {
printf("bits %s from i %d\n", get_code_bits_as_string64(keyBits, 32).c_str(), i);
}
unsigned int clz = __clz(keyBits);
q = clz + 1;
assert(q >= 1 && q <= 16);
assert(clz >= 0 && clz <= 15);
if (debug)
{
uint32_t keyBits6 = keyBits >> (32 - 8) >> 2;
printf("keyBits6 %s : q %d\n", get_code_bits_as_string64(keyBits6, 6).c_str(), q);
}
bits16 |= (q << (bi * 4));
keyBits <<= q;
bi += 1;
}
assert(i < generatedTable.size());
uint8_t offset8 = i;
// Offset into table is a byte
generatedTable[offset8] = bits16;
if (debug) {
printf("generatedTable[%3d] : bits %s : bits16-q %s\n", i, get_code_bits_as_string64(offset8, 6).c_str(), get_code_bits_as_string64(bits16, 16).c_str());
printf("offset8 %s\n", get_code_bits_as_string64(offset8, 8).c_str());
}
}
return generatedTable;
}
#endif // rice_hpp
| 31.323035 | 165 | 0.536426 | [
"object",
"vector",
"3d"
] |
99d1a91b88ed5d5810cb5892259a14888fe2fec8 | 546 | cpp | C++ | algo/cpp/107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II/Binary Tree Level Order Traversal II.cpp | fenglin9102/ARTS | 47cd09a7c414171c4495a15e0e1367a76330271c | [
"MIT"
] | 1 | 2019-08-22T08:13:46.000Z | 2019-08-22T08:13:46.000Z | algo/cpp/107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II/Binary Tree Level Order Traversal II.cpp | fenglin9102/ARTS | 47cd09a7c414171c4495a15e0e1367a76330271c | [
"MIT"
] | 1 | 2019-08-21T07:18:23.000Z | 2019-08-21T07:18:23.000Z | algo/cpp/107. Binary Tree Level Order Traversal II/107. Binary Tree Level Order Traversal II/Binary Tree Level Order Traversal II.cpp | fenglin9102/ARTS | 47cd09a7c414171c4495a15e0e1367a76330271c | [
"MIT"
] | 1 | 2019-08-21T05:04:09.000Z | 2019-08-21T05:04:09.000Z | //
// Binary Tree Level Order Traversal II.cpp
// 107. Binary Tree Level Order Traversal II
//
// Created by 张枫林 on 2019/8/18.
// Copyright © 2019 张枫林. All rights reserved.
//
#include "Binary Tree Level Order Traversal II.hpp"
void Solution::test(){
TreeNode *root = new TreeNode(3);
root->left = new TreeNode(9);
TreeNode *right = new TreeNode(20);
right->right = new TreeNode(7);
right->left = new TreeNode(15);
root->right = right;
vector<vector<int>> res = levelOrderBottom(root);
printf("--");
}
| 24.818182 | 54 | 0.642857 | [
"vector"
] |
99d26af7ef2e546b683929b412d15876bb10bc45 | 413 | cpp | C++ | arrays/containsDuplicate.cpp | Gooner1886/DSA-101 | 44092e10ad39bebbf7da93e897927106d5a45ae7 | [
"MIT"
] | 20 | 2022-01-04T19:36:14.000Z | 2022-03-21T15:35:09.000Z | arrays/containsDuplicate.cpp | Gooner1886/DSA-101 | 44092e10ad39bebbf7da93e897927106d5a45ae7 | [
"MIT"
] | null | null | null | arrays/containsDuplicate.cpp | Gooner1886/DSA-101 | 44092e10ad39bebbf7da93e897927106d5a45ae7 | [
"MIT"
] | null | null | null | // Contains Duplicate - Leetcode
bool containsDuplicate(vector<int>& nums) {
unordered_map<int, int> _map;
for (int i =0; i < nums.size(); i++) {
int num = nums[i];
int duplicate = num;
auto it = _map.find(duplicate);
if(it != _map.end()) {
return true;
}
_map[num] = i;
}
return false;
} | 27.533333 | 46 | 0.457627 | [
"vector"
] |
99dc059cc839d38930bb9aa739229691b2ca4f61 | 3,403 | cpp | C++ | srcs/common/moviebox.cpp | brooklet/heif | 87d0427d750d882acba5f31bae697fe9a433ab50 | [
"BSD-3-Clause"
] | 1 | 2019-12-27T00:55:05.000Z | 2019-12-27T00:55:05.000Z | srcs/common/moviebox.cpp | brooklet/heif | 87d0427d750d882acba5f31bae697fe9a433ab50 | [
"BSD-3-Clause"
] | null | null | null | srcs/common/moviebox.cpp | brooklet/heif | 87d0427d750d882acba5f31bae697fe9a433ab50 | [
"BSD-3-Clause"
] | null | null | null | /* This file is part of Nokia HEIF library
*
* Copyright (c) 2015-2018 Nokia Corporation and/or its subsidiary(-ies). All rights reserved.
*
* Contact: heif@nokia.com
*
* This software, including documentation, is protected by copyright controlled by Nokia Corporation and/ or its
* subsidiaries. All rights are reserved.
*
* Copying, including reproducing, storing, adapting or translating, any or all of this material requires the prior
* written consent of Nokia.
*/
#include "moviebox.hpp"
#include "bitstream.hpp"
#include "log.hpp"
MovieBox::MovieBox()
: Box("moov")
, mMovieHeaderBox()
, mTracks()
, mIsOzoPreviewFile(false)
{
}
void MovieBox::clear()
{
mMovieHeaderBox = {};
mTracks.clear();
mIsOzoPreviewFile = false;
}
MovieHeaderBox& MovieBox::getMovieHeaderBox()
{
return mMovieHeaderBox;
}
const MovieHeaderBox& MovieBox::getMovieHeaderBox() const
{
return mMovieHeaderBox;
}
const Vector<UniquePtr<TrackBox>>& MovieBox::getTrackBoxes() const
{
return mTracks;
}
TrackBox* MovieBox::getTrackBox(uint32_t trackId)
{
for (auto& track : mTracks)
{
if (track.get()->getTrackHeaderBox().getTrackID() == trackId)
{
return track.get();
}
}
return nullptr;
}
void MovieBox::addTrackBox(UniquePtr<TrackBox> trackBox)
{
mTracks.push_back(std::move(trackBox));
}
bool MovieBox::isOzoPreviewFile() const
{
return mIsOzoPreviewFile;
}
void MovieBox::writeBox(ISOBMFF::BitStream& bitstr) const
{
writeBoxHeader(bitstr);
mMovieHeaderBox.writeBox(bitstr);
for (auto& track : mTracks)
{
track->writeBox(bitstr);
}
updateSize(bitstr);
}
void MovieBox::parseBox(ISOBMFF::BitStream& bitstr)
{
parseBoxHeader(bitstr);
while (bitstr.numBytesLeft() > 0)
{
FourCCInt boxType;
BitStream subBitstr = bitstr.readSubBoxBitStream(boxType);
if (boxType == "mvhd")
{
mMovieHeaderBox.parseBox(subBitstr);
}
else if (boxType == "trak")
{
UniquePtr<TrackBox> trackBox(CUSTOM_NEW(TrackBox, ()));
trackBox->parseBox(subBitstr);
// Ignore box if the handler type is not pict
FourCCInt handlerType = trackBox->getMediaBox().getHandlerBox().getHandlerType();
if (handlerType == "pict" || // Image Sequence track
handlerType == "auxv" || // Auxiliary Image Sequence track
handlerType == "soun" || // Audio track
handlerType == "vide") // Video track
{
mTracks.push_back(move(trackBox));
}
}
else if (boxType == "udta")
{
unsigned int udtaSize = subBitstr.read32Bits();
if (udtaSize < 200)
{
String udtaData;
subBitstr.readStringWithLen(udtaData, static_cast<unsigned int>(subBitstr.numBytesLeft()));
std::size_t found = udtaData.find("NokiaPC");
if (found != String::npos)
{
// this is Ozo Preview file with "NokiaPC" in udta
mIsOzoPreviewFile = true;
}
}
}
else
{
logWarning() << "Skipping an unsupported box '" << boxType.getString() << "' inside movie box." << std::endl;
}
}
}
| 25.780303 | 121 | 0.598589 | [
"vector"
] |
99df4613ba87a8990ad0f88756691aac555a5fd4 | 1,566 | cpp | C++ | Lab5/src/lab5.cpp | DavidePistilli173/Computer-Vision | 4066a99f6f6fdc941829d3cd3015565ec0046a2f | [
"Apache-2.0"
] | null | null | null | Lab5/src/lab5.cpp | DavidePistilli173/Computer-Vision | 4066a99f6f6fdc941829d3cd3015565ec0046a2f | [
"Apache-2.0"
] | null | null | null | Lab5/src/lab5.cpp | DavidePistilli173/Computer-Vision | 4066a99f6f6fdc941829d3cd3015565ec0046a2f | [
"Apache-2.0"
] | null | null | null | #include "lab5.hpp"
#include <opencv2/imgproc.hpp>
using namespace lab5;
std::mutex Log::mtx_;
Window::Window(std::string_view name) :
name_{ name.data() }
{
cv::namedWindow(name.data(), cv::WINDOW_NORMAL | cv::WINDOW_KEEPRATIO | cv::WINDOW_GUI_EXPANDED);
trckBarVals_.reserve(max_trckbar_num); // Reserve space for the maximum number of trackbars.
}
Window::~Window()
{
cv::destroyWindow(name_);
}
bool Window::addTrackBar(std::string_view name, int maxVal)
{
return addTrackBar(name, 0, maxVal);
}
bool Window::addTrackBar(std::string_view name, int startVal, int maxVal)
{
if (trckBarVals_.size() == max_trckbar_num)
{
Log::warn("Maximum number of trackbars reached.");
return false;
}
if (startVal > maxVal)
{
Log::warn("Initial trackbar value too high. Setting it to 0.");
startVal = 0;
}
int* valPtr{ &trckBarVals_.emplace_back(startVal) };
cv::createTrackbar(
name.data(),
name_,
valPtr,
maxVal,
trckCallbck_,
this
);
return true;
}
std::vector<int> Window::fetchTrckVals()
{
/* Return the current values and reset the modification flag. */
trckModified_ = false;
return trckBarVals_;
}
bool Window::modified() const
{
return trckModified_;
}
void Window::showImg(const cv::Mat& img) const
{
cv::imshow(name_, img);
}
void Window::trckCallbck_(int val, void* ptr)
{
Window* winPtr{ reinterpret_cast<Window*>(ptr) };
winPtr->trckModified_ = true; // Set the modification flag.
}
| 21.162162 | 101 | 0.650702 | [
"vector"
] |
99e3152a1524efb278bb9986303a185b84fb06ff | 1,961 | cpp | C++ | AusEngine/ModuleImGui.cpp | auusi9/AusEngine | d9eafd9f8ffb1d13e1ca3f3af85c95b7f3e6ed0d | [
"MIT"
] | null | null | null | AusEngine/ModuleImGui.cpp | auusi9/AusEngine | d9eafd9f8ffb1d13e1ca3f3af85c95b7f3e6ed0d | [
"MIT"
] | 1 | 2016-10-16T13:22:46.000Z | 2016-10-16T16:55:32.000Z | AusEngine/ModuleImGui.cpp | auusi9/AusEngine | d9eafd9f8ffb1d13e1ca3f3af85c95b7f3e6ed0d | [
"MIT"
] | null | null | null | #include "Globals.h"
#include "Application.h"
#include "ModuleImGui.h"
#include "Imgui\imgui.h"
#include "Imgui\imgui_impl_sdl_gl3.h"
#include "Glew\include\glew.h"
#pragma comment (lib, "Glew/libx86/glew32.lib")
ModuleImGui::ModuleImGui(Application* app, bool start_enabled) : Module(app, start_enabled)
{
}
ModuleImGui::~ModuleImGui()
{}
// Load assets
bool ModuleImGui::Init()
{
bool ret = true;
glewInit();
ImGui_ImplSdlGL3_Init(App->window->window);
return ret;
}
// Clean up ImGui
bool ModuleImGui::CleanUp()
{
LOG("Unloading Intro scene");
ImGui_ImplSdlGL3_Shutdown();
return true;
}
void ModuleImGui::HandleInput(SDL_Event * event)
{
ImGui_ImplSdlGL3_ProcessEvent(event);
}
bool ModuleImGui::UsingKeyboard()
{
return capture_keyboard;
}
bool ModuleImGui::UsingMouse()
{
return capture_mouse;
}
update_status ModuleImGui::PreUpdate(float dt)
{
ImGui_ImplSdlGL3_NewFrame(App->window->window);
ImGuiIO& io = ImGui::GetIO();
capture_keyboard = io.WantCaptureKeyboard;
capture_mouse = io.WantCaptureMouse;
return UPDATE_CONTINUE;
}
// Update: draw background
update_status ModuleImGui::Update(float dt)
{
update_status ret = UPDATE_CONTINUE;
static bool show_test_window = true;
static bool show_menu = true;
if (show_menu == true)
{
if (ImGui::BeginMainMenuBar())
{
bool selected = false;
if (ImGui::BeginMenu("File"))
{
/*ImGui::MItenuItem("New");
ImGui::Menuem("Save");*/
if (ImGui::MenuItem("Quit"))
ret = UPDATE_STOP;
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Window"))
{
if (ImGui::MenuItem("Open test window"))
{
if (show_test_window)
show_test_window = false;
else
show_test_window = true;
}
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
if (show_test_window)
{
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver);
ImGui::ShowTestWindow(&show_test_window);
}
ImGui::Render();
return ret;
}
| 18.67619 | 91 | 0.696583 | [
"render"
] |
99ea792675725bf3caf1f3ef42958e49972b7126 | 1,068 | cpp | C++ | Qt/15_qsqlquerymodel/mainwindow.cpp | de-souza/embedded-cpp-training | 370225ea95e5b61f52203761c01a8daaa0909fc0 | [
"Apache-2.0"
] | null | null | null | Qt/15_qsqlquerymodel/mainwindow.cpp | de-souza/embedded-cpp-training | 370225ea95e5b61f52203761c01a8daaa0909fc0 | [
"Apache-2.0"
] | null | null | null | Qt/15_qsqlquerymodel/mainwindow.cpp | de-souza/embedded-cpp-training | 370225ea95e5b61f52203761c01a8daaa0909fc0 | [
"Apache-2.0"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlQuery>
#include <QSqlQueryModel>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->comboBox, &QComboBox::currentTextChanged, this, &MainWindow::mOnChange);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("communes.db");
if (!db.open())
exit(EXIT_FAILURE);
auto model = new QSqlQueryModel(this);
model->setQuery("SELECT DISTINCT dep FROM communes");
ui->comboBox->setModel(model);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::mOnChange(const QString& rText)
{
delete mpCitesModel;
mpCitesModel = new QSqlQueryModel(this);
mpCitesModel->setQuery(QString("SELECT libelle FROM communes WHERE dep='%1'").arg(rText));
ui->listView->setModel(mpCitesModel);
QSqlQuery query(QString("SELECT COUNT(libelle) FROM communes WHERE dep='%1'").arg(rText));
query.next();
ui->lineEdit->setText(query.value(0).toString());
}
| 28.864865 | 94 | 0.696629 | [
"model"
] |
99f5f56ed4b02dcf18f1d297b2281f7896e7c55b | 4,601 | cxx | C++ | applications/rtkosem/rtkosem.cxx | vlibertiaux/RTK | 0965dfe680e7993141898af13425ae2afb98d319 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | applications/rtkosem/rtkosem.cxx | vlibertiaux/RTK | 0965dfe680e7993141898af13425ae2afb98d319 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | applications/rtkosem/rtkosem.cxx | vlibertiaux/RTK | 0965dfe680e7993141898af13425ae2afb98d319 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*=========================================================================
*
* Copyright RTK Consortium
*
* 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.txt
*
* 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 "rtkosem_ggo.h"
#include "rtkGgoFunctions.h"
#include "rtkThreeDCircularProjectionGeometryXMLFile.h"
#include "rtkOSEMConeBeamReconstructionFilter.h"
#include "rtkPhaseGatingImageFilter.h"
#include "rtkIterationCommands.h"
#ifdef RTK_USE_CUDA
# include "itkCudaImage.h"
#endif
#include <itkImageFileWriter.h>
int
main(int argc, char * argv[])
{
GGO(rtkosem, args_info);
using OutputPixelType = float;
constexpr unsigned int Dimension = 3;
#ifdef RTK_USE_CUDA
using OutputImageType = itk::CudaImage<OutputPixelType, Dimension>;
#else
using OutputImageType = itk::Image<OutputPixelType, Dimension>;
#endif
// Projections reader
using ReaderType = rtk::ProjectionsReader<OutputImageType>;
ReaderType::Pointer reader = ReaderType::New();
rtk::SetProjectionsReaderFromGgo<ReaderType, args_info_rtkosem>(reader, args_info);
// Geometry
if (args_info.verbose_flag)
std::cout << "Reading geometry information from " << args_info.geometry_arg << "..." << std::endl;
rtk::ThreeDCircularProjectionGeometryXMLFileReader::Pointer geometryReader;
geometryReader = rtk::ThreeDCircularProjectionGeometryXMLFileReader::New();
geometryReader->SetFilename(args_info.geometry_arg);
TRY_AND_EXIT_ON_ITK_EXCEPTION(geometryReader->GenerateOutputInformation())
// Create input: either an existing volume read from a file or a blank image
itk::ImageSource<OutputImageType>::Pointer inputFilter;
if (args_info.input_given)
{
// Read an existing image to initialize the volume
using InputReaderType = itk::ImageFileReader<OutputImageType>;
InputReaderType::Pointer inputReader = InputReaderType::New();
inputReader->SetFileName(args_info.input_arg);
inputFilter = inputReader;
}
else
{
// Create new empty volume
using ConstantImageSourceType = rtk::ConstantImageSource<OutputImageType>;
ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();
rtk::SetConstantImageSourceFromGgo<ConstantImageSourceType, args_info_rtkosem>(constantImageSource, args_info);
constantImageSource->SetConstant(1.);
inputFilter = constantImageSource;
}
itk::ImageSource<OutputImageType>::Pointer attenuationFilter;
if (args_info.attenuationmap_given)
{
// Read an existing image to initialize the attenuation map
using AttenuationReaderType = itk::ImageFileReader<OutputImageType>;
AttenuationReaderType::Pointer attenuationReader = AttenuationReaderType::New();
attenuationReader->SetFileName(args_info.attenuationmap_arg);
attenuationFilter = attenuationReader;
}
// OSEM reconstruction filter
rtk::OSEMConeBeamReconstructionFilter<OutputImageType>::Pointer osem =
rtk::OSEMConeBeamReconstructionFilter<OutputImageType>::New();
// Set the forward and back projection filters
SetForwardProjectionFromGgo(args_info, osem.GetPointer());
SetBackProjectionFromGgo(args_info, osem.GetPointer());
osem->SetInput(inputFilter->GetOutput());
osem->SetInput(1, reader->GetOutput());
if (args_info.attenuationmap_given)
osem->SetInput(2, attenuationFilter->GetOutput());
if (args_info.sigmazero_given)
osem->SetSigmaZero(args_info.sigmazero_arg);
if (args_info.alphapsf_given)
osem->SetAlpha(args_info.alphapsf_arg);
osem->SetGeometry(geometryReader->GetOutputObject());
osem->SetNumberOfIterations(args_info.niterations_arg);
osem->SetNumberOfProjectionsPerSubset(args_info.nprojpersubset_arg);
REPORT_ITERATIONS(osem, rtk::OSEMConeBeamReconstructionFilter<OutputImageType>, OutputImageType)
// Write
using WriterType = itk::ImageFileWriter<OutputImageType>;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(args_info.output_arg);
writer->SetInput(osem->GetOutput());
TRY_AND_EXIT_ON_ITK_EXCEPTION(writer->Update())
return EXIT_SUCCESS;
}
| 38.024793 | 115 | 0.747229 | [
"geometry"
] |
99f6af1c182cc353ad0faf1fa9e46c6b3203515a | 4,295 | cc | C++ | src/serializer/merger.cc | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/serializer/merger.cc | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | src/serializer/merger.cc | sauter-hq/rethinkdb | f34541d501bcf109c2825a7a1b67cf8fd39b9133 | [
"Apache-2.0"
] | null | null | null | // Copyright 2010-2014 RethinkDB, all rights reserved.
#include "serializer/merger.hpp"
#include <functional>
#include "errors.hpp"
#include "arch/runtime/coroutines.hpp"
#include "concurrency/new_mutex.hpp"
#include "config/args.hpp"
#include "serializer/types.hpp"
merger_serializer_t::merger_serializer_t(scoped_ptr_t<serializer_t> _inner,
int _max_active_writes) :
inner(std::move(_inner)),
block_writes_io_account(make_io_account(MERGER_BLOCK_WRITE_IO_PRIORITY)),
write_committer(std::bind(&merger_serializer_t::do_index_write, this),
_max_active_writes) { }
merger_serializer_t::~merger_serializer_t() {
assert_thread();
rassert(outstanding_index_write_ops.empty());
}
counted_t<standard_block_token_t> merger_serializer_t::index_read(block_id_t block_id) {
// First check if there is an updated entry for the block id...
const auto write_op = outstanding_index_write_ops.find(block_id);
if (write_op != outstanding_index_write_ops.end()) {
if (static_cast<bool>(write_op->second.token)) {
return *write_op->second.token;
}
}
// ... otherwise pass this request on to the underlying serializer.
return inner->index_read(block_id);
}
void merger_serializer_t::index_write(new_mutex_in_line_t *mutex_acq,
const std::function<void()> &on_writes_reflected,
const std::vector<index_write_op_t> &write_ops) {
rassert(coro_t::self() != nullptr);
assert_thread();
// Apply our set of write ops atomically
{
new_mutex_acq_t outstanding_mutex_acq(&outstanding_index_write_mutex);
for (auto op = write_ops.begin(); op != write_ops.end(); ++op) {
push_index_write_op(*op);
}
}
// Changes are now visible for subsequent `index_read()` calls.
on_writes_reflected();
// The caller is "in line" for this merger serializer -- subsequent index_write
// calls will get logically committed after ours, and subsequent index_read
// calls are going to see the changes.
mutex_acq->reset();
// Wait for the write to complete
write_committer.notify();
cond_t non_interruptor;
write_committer.flush(&non_interruptor);
}
void merger_serializer_t::do_index_write() {
assert_thread();
// Pause changes to outstanding_index_write_ops
new_mutex_in_line_t outstanding_mutex_acq(&outstanding_index_write_mutex);
outstanding_mutex_acq.acq_signal()->wait_lazily_unordered();
// Assemble the currently outstanding index writes into
// a vector of index_write_op_t-s.
std::vector<index_write_op_t> write_ops;
write_ops.reserve(outstanding_index_write_ops.size());
for (auto op_pair = outstanding_index_write_ops.begin();
op_pair != outstanding_index_write_ops.end();
++op_pair) {
write_ops.push_back(op_pair->second);
}
new_mutex_in_line_t mutex_acq(&inner_index_write_mutex);
mutex_acq.acq_signal()->wait();
inner->index_write(
&mutex_acq,
[&]() {
// Once the writes are reflected in future calls to `inner->index_read()`,
// we can reset outstanding_index_write_ops and allow new write ops to
// get in line.
outstanding_index_write_ops.clear();
outstanding_mutex_acq.reset();
},
write_ops);
}
void merger_serializer_t::merge_index_write_op(const index_write_op_t &to_be_merged,
index_write_op_t *into_out) const {
rassert(to_be_merged.block_id == into_out->block_id);
if (to_be_merged.token.is_initialized()) {
into_out->token = to_be_merged.token;
}
if (to_be_merged.recency.is_initialized()) {
into_out->recency = to_be_merged.recency;
}
}
void merger_serializer_t::push_index_write_op(const index_write_op_t &op) {
auto existing_pair =
outstanding_index_write_ops.insert(
std::pair<block_id_t, index_write_op_t>(op.block_id, op));
if (!existing_pair.second) {
// new op could not be inserted because it already exists. Merge instead.
merge_index_write_op(op, &existing_pair.first->second);
}
}
| 35.791667 | 88 | 0.678929 | [
"vector"
] |
99f7ca2f19dbfd2f8834c59be657c80cf04008c1 | 6,148 | cpp | C++ | 3dEngine/src/scene/ui/widget/window/Window.cpp | petitg1987/UrchinEngine | 32d4b62b1ab7e2aa781c99de11331e3738078b0c | [
"MIT"
] | 24 | 2015-10-05T00:13:57.000Z | 2020-05-06T20:14:06.000Z | 3dEngine/src/scene/ui/widget/window/Window.cpp | petitg1987/UrchinEngine | 32d4b62b1ab7e2aa781c99de11331e3738078b0c | [
"MIT"
] | 1 | 2019-11-01T08:00:55.000Z | 2019-11-01T08:00:55.000Z | 3dEngine/src/scene/ui/widget/window/Window.cpp | petitg1987/UrchinEngine | 32d4b62b1ab7e2aa781c99de11331e3738078b0c | [
"MIT"
] | 10 | 2015-11-25T07:33:13.000Z | 2020-03-02T08:21:10.000Z | #include <memory>
#include <utility>
#include <UrchinCommon.h>
#include <scene/ui/widget/window/Window.h>
#include <scene/InputDeviceKey.h>
#include <api/render/GenericRendererBuilder.h>
namespace urchin {
Window::Window(Position position, Size size, std::string skinName, std::string titleKey) :
Widget(position, size),
skinName(std::move(skinName)),
titleKey(std::move(titleKey)),
mousePositionX(0),
mousePositionY(0),
state(DEFAULT),
title(nullptr) {
}
std::shared_ptr<Window> Window::create(Widget* parent, Position position, Size size, std::string skinName, std::string titleKey) {
return Widget::create<Window>(new Window(position, size, std::move(skinName), std::move(titleKey)), parent);
}
void Window::createOrUpdateWidget() {
//detach children
detachChild(title.get());
//skin information
auto windowChunk = UISkinService::instance().getSkinReader().getFirstChunk(true, "window", UdaAttribute("skin", skinName));
auto skinChunk = UISkinService::instance().getSkinReader().getFirstChunk(true, "skin", UdaAttribute(), windowChunk);
texWindow = UISkinService::instance().createWidgetTexture((unsigned int)getWidth(), (unsigned int)getHeight(), skinChunk, &widgetOutline);
if (!titleKey.empty()) {
auto textSkinChunk = UISkinService::instance().getSkinReader().getFirstChunk(true, "textSkin", UdaAttribute(), windowChunk);
title = Text::create(this, Position(0.0f, 0.0f, LengthType::PIXEL), textSkinChunk->getStringValue(), i18n(titleKey));
title->updatePosition(Position(0.0f, -((float)widgetOutline.topWidth + title->getHeight()) / 2.0f, LengthType::PIXEL));
}
//visual
std::vector<Point2<float>> vertexCoord = {
Point2<float>(0.0f, 0.0f), Point2<float>(getWidth(), 0.0f), Point2<float>(getWidth(), getHeight()),
Point2<float>(0.0f, 0.0f), Point2<float>(getWidth(), getHeight()), Point2<float>(0.0f, getHeight())
};
std::vector<Point2<float>> textureCoord = {
Point2<float>(0.0f, 0.0f), Point2<float>(1.0f, 0.0f), Point2<float>(1.0f, 1.0f),
Point2<float>(0.0f, 0.0f), Point2<float>(1.0f, 1.0f), Point2<float>(0.0f, 1.0f)
};
windowRenderer = setupUiRenderer("window", ShapeType::TRIANGLE, false)
->addData(vertexCoord)
->addData(textureCoord)
->addUniformTextureReader(TextureReader::build(texWindow, TextureParam::build(TextureParam::EDGE_CLAMP, TextureParam::LINEAR, getTextureAnisotropy()))) //binding 3
->build();
}
WidgetType Window::getWidgetType() const {
return WidgetType::WINDOW;
}
bool Window::onKeyPressEvent(unsigned int key) {
bool propagateEvent = true;
if (key == (int)InputDeviceKey::MOUSE_LEFT) {
Rectangle2D titleZone(Point2<int>((int)getGlobalPositionX(), (int)getGlobalPositionY()),
Point2<int>((int)getGlobalPositionX() + ((int) getWidth() - widgetOutline.rightWidth), (int)getGlobalPositionY() + widgetOutline.topWidth));
Rectangle2D closeZone(Point2<int>((int)getGlobalPositionX() + ((int) getWidth() - widgetOutline.rightWidth), (int)getGlobalPositionY()),
Point2<int>((int)getGlobalPositionX() + (int) getWidth(), (int)getGlobalPositionY() + widgetOutline.topWidth));
if (!getUi3dData() && titleZone.collideWithPoint(Point2<int>(getMouseX(), getMouseY()))) {
mousePositionX = getMouseX() - MathFunction::roundToInt(getPositionX());
mousePositionY = getMouseY() - MathFunction::roundToInt(getPositionY());
state = MOVING;
}
if (closeZone.collideWithPoint(Point2<int>(getMouseX(), getMouseY()))) {
state = CLOSING;
}
if (widgetRectangle().collideWithPoint(Point2<int>(getMouseX(), getMouseY()))) {
notifyObservers(this, SET_IN_FOREGROUND);
propagateEvent = false;
}
}
return propagateEvent;
}
bool Window::onKeyReleaseEvent(unsigned int key) {
Rectangle2D closeZone(Point2<int>((int)getGlobalPositionX() + ((int)getWidth() - widgetOutline.rightWidth), (int)getGlobalPositionY()),
Point2<int>((int)getGlobalPositionX() + (int)getWidth(), (int)getGlobalPositionY() + widgetOutline.topWidth));
if (key == (int)InputDeviceKey::MOUSE_LEFT && state == CLOSING && closeZone.collideWithPoint(Point2<int>(getMouseX(), getMouseY()))) {
setIsVisible(false);
}
state = DEFAULT;
return true;
}
bool Window::onMouseMoveEvent(int mouseX, int mouseY) {
bool propagateEvent = true;
if (state == MOVING) {
auto positionPixelX = (float)(mouseX - mousePositionX);
auto positionLengthX = widthPixelToLength(positionPixelX, getPosition().getXType());
auto positionPixelY = (float)(mouseY - mousePositionY);
auto positionLengthY = heightPixelToLength(positionPixelY, getPosition().getYType());
updatePosition(Position(positionLengthX, getPosition().getXType(),
positionLengthY, getPosition().getYType(),
getPosition().getRelativeTo(), getPosition().getReferencePoint()));
propagateEvent = false;
} else if (widgetRectangle().collideWithPoint(Point2<int>(mouseX, mouseY))) {
propagateEvent = false;
}
return propagateEvent;
}
void Window::onResetStateEvent() {
state = DEFAULT;
}
void Window::prepareWidgetRendering(float, unsigned int& renderingOrder, const Matrix4<float>& projectionViewMatrix) {
updateProperties(windowRenderer.get(), projectionViewMatrix, Vector2<float>(getGlobalPositionX(), getGlobalPositionY()));
windowRenderer->enableRenderer(renderingOrder);
}
}
| 46.931298 | 179 | 0.626057 | [
"render",
"vector"
] |
99f8a48e7236e13b127dbfd667768a205b94036e | 20,660 | cpp | C++ | src/monitor.cpp | Flowdalic/herbstluftwm | a4705f3247eef3ba388daaae04191d805fcb8f91 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/monitor.cpp | Flowdalic/herbstluftwm | a4705f3247eef3ba388daaae04191d805fcb8f91 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | src/monitor.cpp | Flowdalic/herbstluftwm | a4705f3247eef3ba388daaae04191d805fcb8f91 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "monitor.h"
#include <X11/Xlib.h>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <sstream>
#include <vector>
#include "client.h"
#include "clientmanager.h"
#include "completion.h"
#include "ewmh.h"
#include "floating.h"
#include "frametree.h"
#include "globals.h"
#include "hook.h"
#include "ipc-protocol.h"
#include "layout.h"
#include "monitormanager.h"
#include "root.h"
#include "settings.h"
#include "stack.h"
#include "tag.h"
#include "tagmanager.h"
#include "utils.h"
using std::endl;
using std::string;
using std::stringstream;
using std::vector;
extern MonitorManager* g_monitors;
Monitor::Monitor(Settings* settings_, MonitorManager* monman_, Rectangle rect_, HSTag* tag_)
: tag(tag_)
, tag_previous(tag_)
, name (this, "name", "",
[monman_](string n) { return monman_->isValidMonitorName(n); })
, index (this, "index", 0)
, tag_string(this, "tag", &Monitor::getTagString, &Monitor::setTagString)
, pad_up (this, "pad_up", 0)
, pad_right (this, "pad_right", 0)
, pad_down (this, "pad_down", 0)
, pad_left (this, "pad_left", 0)
, lock_tag (this, "lock_tag", false)
, pad_automatically_set ({false, false, false, false})
, dirty(true)
, lock_frames(false)
, mouse { 0, 0 }
, rect(this, "geometry", rect_, &Monitor::atLeastMinWindowSize)
, settings(settings_)
, monman(monman_)
{
// explicitly set members writable such that gendoc.py recognizes it
pad_up.setWritable();
pad_right.setWritable();
pad_down.setWritable();
pad_left.setWritable();
lock_tag.setWritable();
for (auto i : {&pad_up, &pad_left, &pad_right, &pad_down}) {
i->changed().connect(this, &Monitor::applyLayout);
}
rect.changedByUser().connect(this, &Monitor::applyLayout);
rect.setDoc("the outer geometry of the monitor");
stacking_window = XCreateSimpleWindow(g_display, g_root,
42, 42, 42, 42, 1, 0, 0);
setDoc("The monitor is a rectangular part on the screen that holds "
"precisely one tag at a time. The pad attributes reserve "
"space on the monitor\'s edge for panels, so this space "
"(given in number of pixels) is never occupied by tiled clients.");
name.setDoc("the monitor\'s name (can be empty)");
index.setDoc("the monitor\'s index (starts at index 0)");
tag_string.setDoc("the name of the tag viewed here");
pad_up.setDoc("space for panels at the monitor\'s upper edge");
pad_right.setDoc("space for panels at the monitor\'s right edge");
pad_down.setDoc("space for panels at the monitor\'s lower edge");
pad_left.setDoc("space for panels at the monitor\'s left edge");
lock_tag.setDoc("if activated, then it it is not possible to switch "
"this monitor to a different tag.");
}
Monitor::~Monitor() {
XDestroyWindow(g_display, stacking_window);
}
string Monitor::getTagString() {
return tag->name();
}
string Monitor::setTagString(string new_tag_string) {
HSTag* new_tag = find_tag(new_tag_string.c_str());
if (!new_tag) {
return "no tag named \"" + new_tag_string + "\" exists.";
}
if (new_tag == tag) {
return ""; // nothing to do
}
bool success = this->setTag(new_tag);
if (!success) {
return "tag \"" + new_tag_string + "\" is already on another monitor";
/* Note: To change this to tag-swapping between monitors, implement a method
* MonitorManager::stealTag() that will fetch the corresponding monitor
* and perform the swap */
}
return "to be implemented"; // TODO: implement in setTag()
}
void Monitor::setIndexAttribute(unsigned long new_index) {
index = new_index;
}
int Monitor::lock_tag_cmd(Input, Output) {
lock_tag = true;
return 0;
}
int Monitor::unlock_tag_cmd(Input, Output) {
lock_tag = false;
return 0;
}
void Monitor::noComplete(Completion &complete)
{
complete.none();
}
int Monitor::list_padding(Input, Output output) {
output << pad_up()
<< " " << pad_right()
<< " " << pad_down()
<< " " << pad_left()
<< "\n";
return 0;
}
/** Set the tag shown on the monitor.
* Return false if tag is already shown on another monitor.
*/
// TODO this is the job of monitormanager
bool Monitor::setTag(HSTag* new_tag) {
auto owner = find_monitor_with_tag(new_tag);
if (!owner || owner != this) {
// TODO do the work!
return true;
}
return owner == this;
}
void Monitor::applyLayout() {
if (settings->monitors_locked) {
dirty = true;
return;
}
dirty = false;
Rectangle cur_rect = rect;
// apply pad
// FIXME: why does the following + work for attributes pad_* ?
cur_rect.x += pad_left();
cur_rect.width -= (pad_left() + pad_right());
cur_rect.y += pad_up();
cur_rect.height -= (pad_up() + pad_down());
if (!g_settings->smart_frame_surroundings() || tag->frame->root_->isSplit()) {
// apply frame gap
cur_rect.x += settings->frame_gap();
cur_rect.y += settings->frame_gap();
cur_rect.height -= settings->frame_gap();
cur_rect.width -= settings->frame_gap();
}
bool isFocused = get_current_monitor() == this;
TilingResult res = tag->frame->root_->computeLayout(cur_rect);
if (tag->floating_focused) {
res.focus = tag->focusedClient();
}
if (tag->floating) {
for (auto& p : res.data) {
p.second.floated = true;
// deactivate smart_window_surroundings in floating mode
p.second.minimalDecoration = false;
}
}
// preprocessing
for (auto& p : res.data) {
if (p.first->fullscreen_() || p.second.floated) {
// do not hide fullscreen windows
p.second.visible = true;
}
if (settings->hide_covered_windows) {
// apply hiding of windows: move them to out of the screen:
if (!p.second.visible) {
Rectangle& geo = p.second.geometry;
geo.x = -100 - geo.width;
geo.y = -100 - geo.height;
}
}
}
// 1. Update stack (TODO: why stack first?)
for (auto& p : res.data) {
Client* c = p.first;
if (c->fullscreen_()) {
tag->stack->sliceAddLayer(c->slice, LAYER_FULLSCREEN);
} else {
tag->stack->sliceRemoveLayer(c->slice, LAYER_FULLSCREEN);
}
// special raise rules for tiled clients:
if (!p.second.floated) {
// this client is the globally focused client if this monitor
// is focused and if this client is the focus on this monitor:
bool globallyFocusedClient = isFocused && res.focus == c;
// if this client is globally focused, then it has a different border color
// and so we raise it to make the look of overlapping shadows more pleasent if
// a compositor is running.
//
// Thus, raise this client if it needs to be raised according
// to the TilingResult (if it is the selected window in a max-frame) or
// if this client is focused:
if (p.second.needsRaise || globallyFocusedClient) {
c->raise();
}
}
}
tag->stack->clearLayer(LAYER_FOCUS);
if (res.focus) {
// activate the focus layer if requested by the setting
// or if there is a fullscreen client potentially covering
// the focused client.
if ((isFocused && g_settings->raise_on_focus_temporarily())
|| tag->stack->isLayerEmpty(LAYER_FULLSCREEN) == false)
{
tag->stack->sliceAddLayer(res.focus->slice, LAYER_FOCUS);
}
}
restack();
// 2. Update window geometries
for (auto& p : res.data) {
Client* c = p.first;
bool clientFocused = isFocused && res.focus == c;
if (c->fullscreen_()) {
c->resize_fullscreen(rect, clientFocused);
} else if (p.second.floated) {
c->resize_floating(this, clientFocused);
} else {
bool minDec = p.second.minimalDecoration;
c->resize_tiling(p.second.geometry, clientFocused, minDec);
}
}
for (auto& c : tag->floating_clients_) {
if (c->fullscreen_()) {
c->resize_fullscreen(rect, res.focus == c && isFocused);
} else {
c->resize_floating(this, res.focus == c && isFocused);
}
}
if (tag->floating) {
for (auto& p : res.frames) {
p.first->hide();
}
} else {
for (auto& p : res.frames) {
p.first->render(p.second, p.first == res.focused_frame && isFocused);
p.first->updateVisibility(p.second, p.first == res.focused_frame && isFocused);
}
}
if (isFocused) {
if (res.focus) {
Root::get()->clients()->focus = res.focus;
res.focus->window_focus();
} else {
Root::get()->clients()->focus = {};
Client::window_unfocus_last();
}
}
// remove all enternotify-events from the event queue that were
// generated while arranging the clients on this monitor
monman->dropEnterNotifyEvents.emit();
}
Monitor* find_monitor_by_name(const char* name) {
for (auto m : *g_monitors) {
if (m->name == name) {
return m;
}
}
return nullptr;
}
Monitor* string_to_monitor(const char* str) {
return g_monitors->byString(str);
}
int Monitor::move_cmd(Input input, Output output) {
// usage: move_monitor INDEX RECT [PADUP [PADRIGHT [PADDOWN [PADLEFT]]]]
// moves monitor with number to RECT
if (input.empty()) {
return HERBST_NEED_MORE_ARGS;
}
auto new_rect = Rectangle::fromStr(input.front());
if (new_rect.width < WINDOW_MIN_WIDTH || new_rect.height < WINDOW_MIN_HEIGHT) {
output << input.command() << ": Rectangle is too small\n";
return HERBST_INVALID_ARGUMENT;
}
// else: just move it:
this->rect = new_rect;
input.shift();
if (!input.empty()) {
pad_up.change(input.front());
}
input.shift();
if (!input.empty()) {
pad_right.change(input.front());
}
input.shift();
if (!input.empty()) {
pad_down.change(input.front());
}
input.shift();
if (!input.empty()) {
pad_left.change(input.front());
}
monitorMoved.emit();
applyLayout();
return 0;
}
void Monitor::move_complete(Completion& complete) {
if (complete == 1) {
complete.full(Converter<Rectangle>::str(rect));
} else if (complete >= 2 && complete <= 5) {
vector<Attribute_<int>*> pads =
{ &pad_up, &pad_right, &pad_down, &pad_left };
complete.full("0");
size_t idx = complete.needleIndex();
pads[idx - 2]->complete(complete);
} else {
complete.none();
}
}
int Monitor::renameCommand(Input input, Output output) {
string new_name;
if (!(input >> new_name)) {
return HERBST_NEED_MORE_ARGS;
}
string error = name.change(new_name);
if (!error.empty()) {
output << input.command() << ": " << error << "\n";
return HERBST_INVALID_ARGUMENT;
} else {
return 0;
}
}
void Monitor::renameComplete(Completion& complete)
{
if (complete == 1) {
// no completion, because the completion of the
// converter only suggests the current name anyway.
} else if (complete >= 2) {
complete.none();
}
}
Monitor* find_monitor_with_tag(HSTag* tag) {
for (auto m : *g_monitors) {
if (m->tag == tag) {
return m;
}
}
return nullptr;
}
Monitor* get_current_monitor() {
return g_monitors->byIdx(g_monitors->cur_monitor);
}
void all_monitors_apply_layout() {
for (auto m : *g_monitors) {
m->applyLayout();
}
}
int monitor_set_tag(Monitor* monitor, HSTag* tag) {
Monitor* other = find_monitor_with_tag(tag);
if (monitor == other) {
// nothing to do
return 0;
}
if (monitor->lock_tag) {
// If the monitor tag is locked, do not change the tag
if (other) {
// but if the tag is already visible, change to the
// displaying monitor
monitor_focus_by_index(other->index());
return 0;
}
return 1;
}
if (other) {
if (g_settings->swap_monitors_to_get_tag()) {
if (other->lock_tag) {
// the monitor we want to steal the tag from is
// locked. focus that monitor instead
monitor_focus_by_index(other->index());
return 0;
}
monitor->tag_previous = monitor->tag;
other->tag_previous = other->tag;
// swap tags
other->tag = monitor->tag;
monitor->tag = tag;
/* TODO: find the best order of restacking and layouting */
other->restack();
monitor->restack();
other->applyLayout();
monitor->applyLayout();
monitor_update_focus_objects();
Ewmh::get().updateCurrentDesktop();
emit_tag_changed(other->tag, other->index());
emit_tag_changed(tag, g_monitors->cur_monitor);
} else {
// if we are not allowed to steal the tag, then just focus the
// other monitor
monitor_focus_by_index(other->index());
}
return 0;
}
HSTag* old_tag = monitor->tag;
// save old tag
monitor->tag_previous = old_tag;
// 1. show new tag
monitor->tag = tag;
// first reset focus and arrange windows
monitor->restack();
monitor->lock_frames = true;
monitor->applyLayout();
monitor->lock_frames = false;
// then show them (should reduce flicker)
tag->setVisible(true);
if (!monitor->tag->floating) {
// monitor->tag->frame->root_->updateVisibility();
}
// 2. hide old tag
old_tag->setVisible(false);
// focus window just has been shown
// discard enternotify-events
g_monitors->dropEnterNotifyEvents.emit();
monitor_update_focus_objects();
Ewmh::get().updateCurrentDesktop();
emit_tag_changed(tag, g_monitors->cur_monitor);
return 0;
}
void monitor_focus_by_index(unsigned new_selection) {
// clamp to last
new_selection = std::min(g_monitors->size() - 1, (size_t)new_selection);
Monitor* old = get_current_monitor();
Monitor* monitor = g_monitors->byIdx(new_selection);
if (old == monitor) {
// nothing to do
return;
}
// change selection globals
assert(monitor->tag);
assert(monitor->tag->frame->root_);
g_monitors->cur_monitor = new_selection;
// repaint g_monitors
old->applyLayout();
monitor->applyLayout();
int rx, ry;
{
// save old mouse position
Window win, child;
int wx, wy;
unsigned int mask;
if (True == XQueryPointer(g_display, g_root, &win, &child,
&rx, &ry, &wx, &wy, &mask)) {
old->mouse.x = rx - old->rect->x;
old->mouse.y = ry - old->rect->y;
old->mouse.x = CLAMP(old->mouse.x, 0, old->rect->width-1);
old->mouse.y = CLAMP(old->mouse.y, 0, old->rect->height-1);
}
}
// restore position of new monitor
// but only if mouse pointer is not already on new monitor
int new_x, new_y;
if ((monitor->rect->x <= rx) && (rx < monitor->rect->x + monitor->rect->width)
&& (monitor->rect->y <= ry) && (ry < monitor->rect->y + monitor->rect->height)) {
// mouse already is on new monitor
} else {
// If the mouse is located in a gap indicated by
// mouse_recenter_gap at the outer border of the monitor,
// recenter the mouse.
if (std::min(monitor->mouse.x, abs(monitor->mouse.x - monitor->rect->width))
< g_settings->mouse_recenter_gap()
|| std::min(monitor->mouse.y, abs(monitor->mouse.y - monitor->rect->height))
< g_settings->mouse_recenter_gap()) {
monitor->mouse.x = monitor->rect->width / 2;
monitor->mouse.y = monitor->rect->height / 2;
}
new_x = monitor->rect->x + monitor->mouse.x;
new_y = monitor->rect->y + monitor->mouse.y;
XWarpPointer(g_display, None, g_root, 0, 0, 0, 0, new_x, new_y);
// discard all mouse events caused by this pointer movage from the
// event queue, so the focus really stays in the last focused window on
// this monitor and doesn't jump to the window hovered by the mouse
g_monitors->dropEnterNotifyEvents.emit();
}
// update objects
monitor_update_focus_objects();
// emit hooks
Ewmh::get().updateCurrentDesktop();
emit_tag_changed(monitor->tag, new_selection);
}
void monitor_update_focus_objects() {
g_monitors->focus = g_monitors->byIdx(g_monitors->cur_monitor);
global_tags->updateFocusObject(g_monitors->focus());
}
int Monitor::relativeX(int x_root) {
return x_root - rect->x - pad_left;
}
int Monitor::relativeY(int y_root) {
return y_root - rect->y - pad_up;
}
void Monitor::restack() {
Window fullscreenFocus = 0;
/* don't add a focused fullscreen client to the stack because
* we want a focused fullscreen window to be above the panels which are
* usually unmanaged. All the windows passed to the XRestackWindows
* will end up below all unmanaged windows, so don't add a focused
* fullscreen window to it. Instead raise the fullscreen window
* manually such that it is above the panel */
Client* client = tag->focusedClient();
if (client && client->fullscreen_) {
fullscreenFocus = client->decorationWindow();
XRaiseWindow(g_display, fullscreenFocus);
}
// collect all other windows in a vector and pass it to XRestackWindows
vector<Window> buf = { stacking_window };
auto addToVector = [&buf, fullscreenFocus](Window w) {
if (w != fullscreenFocus) {
buf.push_back(w);
}
};
tag->stack->extractWindows(false, addToVector);
XRestackWindows(g_display, buf.data(), buf.size());
}
Rectangle Monitor::getFloatingArea() const {
auto m = this;
auto r = m->rect();
r.x += m->pad_left;
r.width -= m->pad_left + m->pad_right;
r.y += m->pad_up;
r.height -= m->pad_up + m->pad_down;
return r;
}
//! Returns a textual description of the monitor
string Monitor::getDescription() {
stringstream label;
label << "Monitor " << index();
if (!name().empty()) {
label << " (\"" << name() << "\")";
}
label << " with tag \"" << tag->name() << "\"";
return label.str();
}
void Monitor::evaluateClientPlacement(Client* client, ClientPlacement placement) const
{
switch (placement) {
case ClientPlacement::Center:
{
Point2D new_tl =
// the center of the monitor
getFloatingArea().dimensions() / 2
// minus half the dimensions of the client
- client->float_size_->dimensions() / 2;
client->float_size_ = Rectangle(new_tl.x, new_tl.y,
client->float_size_->width,
client->float_size_->height);
}
break;
case ClientPlacement::Smart:
{
Point2D area = getFloatingArea().dimensions();
Point2D new_tl = Floating::smartPlacement(tag, client,
area, settings->snap_gap);
client->float_size_ = Rectangle(new_tl.x, new_tl.y,
client->float_size_->width,
client->float_size_->height);
}
break;
case ClientPlacement::Unchanged:
// do not do anything
break;
}
}
string Monitor::atLeastMinWindowSize(Rectangle geom)
{
if (geom.width < WINDOW_MIN_WIDTH) {
return "Rectangle too small; it must be at least "
+ Converter<int>::str(WINDOW_MIN_WIDTH) + " wide.";
}
if (geom.height < WINDOW_MIN_HEIGHT) {
return "Rectangle too small; it must be at least "
+ Converter<int>::str(WINDOW_MIN_HEIGHT) + " high.";
}
return {};
}
| 33.215434 | 92 | 0.586641 | [
"geometry",
"render",
"vector"
] |
99f93d34a3392ec562b87f78b5f70d15f24c7a9a | 6,585 | hpp | C++ | kernel/src/simulationTools/GlobalFrictionContact.hpp | siconos/siconos-deb | 2739a23f23d797dbfecec79d409e914e13c45c67 | [
"Apache-2.0"
] | null | null | null | kernel/src/simulationTools/GlobalFrictionContact.hpp | siconos/siconos-deb | 2739a23f23d797dbfecec79d409e914e13c45c67 | [
"Apache-2.0"
] | null | null | null | kernel/src/simulationTools/GlobalFrictionContact.hpp | siconos/siconos-deb | 2739a23f23d797dbfecec79d409e914e13c45c67 | [
"Apache-2.0"
] | null | null | null | /* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2016 INRIA.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file
Primal Fricton-Contact Non-Smooth Problem
*/
#ifndef GlobalFrictionContact_H
#define GlobalFrictionContact_H
#include "LinearOSNS.hpp"
#include "SiconosVector.hpp"
#include "SimpleMatrix.hpp"
#include "GlobalFrictionContactProblem.h"
#include "Friction_cst.h"
/** Pointer to function of the type used for drivers for GlobalFrictionContact problems in Numerics */
typedef int (*GFC3D_Driver)(GlobalFrictionContactProblem*, double*, double*, double*, SolverOptions*, NumericsOptions*);
TYPEDEF_SPTR(GlobalFrictionContactProblem)
/** Formalization and Resolution of a Friction-Contact Problem
*
* \author SICONOS Development Team - copyright INRIA
* \version 3.0.0.
* \date (Creation) Dec 15, 2005
*
* This class is devoted to the formalization and the resolution of
* primal friction contact problems defined by :
* \f{eqnarray*}
* M velocity = q + H reaction \\
* globalVelocities = H^T velocity + tildeGlobalVelocities\\
* \f}
* and \f$globalVelocities, reaction\f$ belongs to the Coulomb friction law with unilateral contact.
*
* With:
* - \f$velocity \in R^{n} \f$ and \f$reaction \in R^{n} \f$ the unknowns,
* - \f$M \in R^{n \times n } \f$ and \f$q \in R^{n} \f$
* - \f$globalVelocities \in R^{m} \f$ and \f$reaction \in R^{m} \f$ the unknowns,
* - \f$tildeGlobalVelocities \in R^{m} \f$ is the modified local velocity (\f$ e U_{N,k}\f$)
* - \f$M \in R^{n \times n } \f$ and \f$q \in R^{n} \f$
* - \f$H \in R^{n \times m } \f$
*
* The dimension of the problem (2D or 3D) is given by the variable contactProblemDim and the right
* Numerics driver will be called according to this value.
*
* \b Construction:
* - Constructor from data (inputs = Simulations*, id, SP::NonSmoothSolver) - The solver is optional.
* Main functions:
*
* \b Main functions:
* - formalization of the problem: computes M,q using the set of "active" Interactions from the simulation and \n
* the interactionBlock-matrices saved in the field interactionBlocks.\n
* Functions: initialize(), computeInteractionBlock(), preCompute()
* - solving of the GlobalFrictionContact problem: function compute(), used to call solvers from Numerics through \n
* the frictionContact2D_driver() or frictionContact3D_driver() interface of Numerics.
* - post-treatment of data: set values of y/lambda variables of the active Interaction (ie Interactions) using \n
* ouput results from the solver (velocity,reaction); function postCompute().
*
*/
class GlobalFrictionContact : public LinearOSNS
{
private:
/** default constructor */
GlobalFrictionContact() {};
protected:
/** serialization hooks
*/
ACCEPT_SERIALIZATION(GlobalFrictionContact);
/** Type (dimension) of the contact problem (2D or 3D) */
int _contactProblemDim;
/** size of the local problem to solve */
size_t _sizeGlobalOutput;
/** contains the vector globalVelocities of a GlobalFrictionContact system */
SP::SiconosVector _globalVelocities;
/** contains the impact contributions */
SP::SiconosVector _b;
/** contains the matrix H of a GlobalFrictionContact system */
SP::OSNSMatrix _H;
/** friction coefficients */
SP::MuStorage _mu;
/** Pointer to the function used to call the Numerics driver to solve the problem */
GFC3D_Driver _gfc_driver;
public:
/** constructor from data
* \param dimPb dimension (2D or 3D) of the friction-contact problem
* \param numericsSolverId solver to be used (see the documentation of siconos/numerics)
*/
GlobalFrictionContact(int dimPb, int numericsSolverId = SICONOS_GLOBAL_FRICTION_3D_NSGS);
/** destructor
*/
virtual ~GlobalFrictionContact();
// GETTERS/SETTERS
/** get the type of GlobalFrictionContact problem (2D or 3D)
* \return an int (2 or 3)
*/
inline int getGlobalFrictionContactDim() const
{
return _contactProblemDim;
}
/** get dimension of the problem
* \return an unsigned ing
*/
inline unsigned int getGlobalSizeOutput() const
{
return _sizeGlobalOutput;
}
/** get globalVelocities
* \return pointer on a SiconosVector
*/
inline SP::SiconosVector globalVelocities() const
{
return _globalVelocities;
}
/** set globalVelocities to pointer newPtr
* \param newPtr the new vector
*/
inline void setGlobalVelocities(SP::SiconosVector newPtr)
{
_globalVelocities = newPtr;
}
// --- H ---
/** get H
* \return pointer on a OSNSMatrix
*/
inline SP::OSNSMatrix H() const
{
return _H;
}
/** set the value of H
* \param H the new matrix
*/
void setH(SP::OSNSMatrix H) { _H = H;}
/** get a pointer to mu, the list of the friction coefficients
* \return pointer on a std::vector<double>
*/
inline SP::MuStorage mu() const
{
return _mu;
}
/** get the value of the component number i of mu, the vector of the friction coefficients
* \return the friction coefficient for the ith contact
*/
inline double getMu(unsigned int i) const
{
return (*_mu)[i];
}
// --- Others functions ---
/** initialize the GlobalFrictionContact problem(compute topology ...)
\param the simulation, owner of this OSNSPB
*/
virtual void initialize(SP::Simulation sim);
/** Construction of the problem
* \param time current time
*/
virtual bool preCompute(double time);
/** Compute the unknown reaction and velocity and update the Interaction (y and lambda )
* \param double current time
* \return int information about the solver convergence (0: ok, >0 problem, see Numerics documentation)
*/
virtual int compute(double time);
/** post-treatment of output from Numerics solver: \n
* set values of the unknowns of Interactions using (velocity,reaction)
*/
virtual void postCompute();
/** print the data to the screen */
void display() const;
};
#endif // GlobalFrictionContact_H
| 31.208531 | 120 | 0.702354 | [
"vector",
"3d"
] |
99f98a8aca3939c4f3db3b452c3ae18e2815ebe4 | 14,992 | cpp | C++ | library/ctypes_pathintegral_emission.cpp | ucl-exoplanets/TauREx_public | 28d47f829a2873cf15e3bfb0419b8bc4e5bc03dd | [
"CC-BY-4.0"
] | 18 | 2019-07-22T01:35:24.000Z | 2022-02-10T11:25:42.000Z | library/ctypes_pathintegral_emission.cpp | ucl-exoplanets/TauREx_public | 28d47f829a2873cf15e3bfb0419b8bc4e5bc03dd | [
"CC-BY-4.0"
] | null | null | null | library/ctypes_pathintegral_emission.cpp | ucl-exoplanets/TauREx_public | 28d47f829a2873cf15e3bfb0419b8bc4e5bc03dd | [
"CC-BY-4.0"
] | 1 | 2017-10-19T15:14:06.000Z | 2017-10-19T15:14:06.000Z | /*
TauREx v2 - Development version - DO NOT DISTRIBUTE
Forward model for emission
Developers: Ingo Waldmann, Marco Rocchetto (University College London)
For both openmp and single core versions compile with g++:
g++ -fPIC -shared -o ctypes_pathintegral_emission.so ctypes_pathintegral_emission.cpp
g++ -fPIC -shared -fopenmp -o ctypes_pathintegral_emission.so ctypes_pathintegral_emission.cpp
or Intel compiler:
icc -fPIC -shared -o ctypes_pathintegral_emission.so ctypes_pathintegral_emission.cpp
icc -fPIC -shared -openmp -o ctypes_pathintegral_emission_parallel.so ctypes_pathintegral_emission.cpp
*/
#include <stdio.h>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
extern "C" {
void path_integral(const double * wngrid,
const int nwngrid,
const int nlayers,
const int nactive,
const int ninactive,
const int rayleigh,
const int cia,
const int mie,
const double mie_topP,
const double mie_bottomP,
const double * pressure,
const double * sigma_array,
const double * sigma_temp,
const int sigma_ntemp,
const double * sigma_rayleigh,
const int cia_npairs,
const double * cia_idx,
const int cia_nidx,
const double * sigma_cia,
const double * sigma_cia_temp,
const int sigma_cia_ntemp,
const double * sigma_mie,
const double * density,
const double * z,
const double * active_mixratio,
const double * inactive_mixratio,
const double * temperature,
const double planet_radius,
const double star_radius,
const double * star_sed,
void * FpFsv,
void * tauv) {
double * FpFs = (double *) FpFsv;
double * contrib = (double *) tauv;
// setting up arrays and variables
double* dz = new double[nlayers];
double* sigma_interp = new double[nwngrid*nlayers*nactive];
double* sigma_cia_interp = new double[nwngrid * nlayers * cia_npairs];
double sigma, sigma_l, sigma_r;
double tau, tau_cia, dtau, dtau1, tau_sum1, tau_sum2, dtau_cia, mu, tau_tot,eta;
double p;
double mu1, mu2, mu3, mu4, w1, w2, w3, w4;
int count, count2, t_idx;
double F_total, BB_wl, exponent;
double I1, I2, I3, I4;
double h, c, kb, pi;
double x1_idx[cia_npairs][nlayers];
double x2_idx[cia_npairs][nlayers];
h = 6.62606957e-34;
c = 299792458;
kb = 1.3806488e-23;
pi= 3.14159265359;
// set the four zenith angles sampled at four gaussian quadrature points
mu1 = 0.1834346;
mu2 = 0.5255324;
mu3 = 0.7966665;
mu4 = 0.9602899;
// gaussian quadrature weights
w1 = 0.3626838;
w2 = 0.3137066;
w3 = 0.2223810;
w4 = 0.1012885;
//dz array
for (int j=0; j<(nlayers); j++) {
if ((j+1) == nlayers) {
dz[j] = z[j] - z[j-1];
} else {
dz[j] = z[j+1] - z[j];
}
}
// interpolate sigma array to the temperature profile
for (int j=0; j<nlayers; j++) {
if (sigma_ntemp == 1) { //
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<nactive;l++) {
sigma_interp[wn + nwngrid*(j + l*nlayers)] = sigma_array[wn + nwngrid*(sigma_ntemp*(j + l*nlayers))];
}
}
} else {
if (temperature[j] > sigma_temp[sigma_ntemp-1]) {
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<nactive;l++) {
sigma_interp[wn + nwngrid*(j + l*nlayers)] = sigma_array[wn + nwngrid*(sigma_ntemp-1 + sigma_ntemp*(j + l*nlayers))];
}
}
} else if (temperature[j] < sigma_temp[0]) {
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<nactive;l++) {
sigma_interp[wn + nwngrid*(j + l*nlayers)] = sigma_array[wn + nwngrid*(sigma_ntemp*(j + l*nlayers))];
}
}
} else {
for (int t=1; t<sigma_ntemp; t++) {
if ((temperature[j] >= sigma_temp[t-1]) && (temperature[j] < sigma_temp[t])) {
#pragma omp parallel for private(sigma_l, sigma_r, sigma)
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<nactive;l++) {
sigma_l = sigma_array[wn + nwngrid*(t-1 + sigma_ntemp*(j + l*nlayers))];
sigma_r = sigma_array[wn + nwngrid*(t + sigma_ntemp*(j + l*nlayers))];
sigma = sigma_l + (sigma_r-sigma_l)*(temperature[j]-sigma_temp[t-1])/(sigma_temp[t]-sigma_temp[t-1]);
sigma_interp[wn + nwngrid*(j + l*nlayers)] = sigma;
}
}
}
}
}
}
}
// interpolate sigma CIA array to the temperature profile
for (int j=0; j<nlayers; j++) {
if (sigma_cia_ntemp == 1) { //
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<cia_npairs;l++) {
sigma_cia_interp[wn + nwngrid*(j + l*nlayers)] = sigma_cia[wn + nwngrid*(sigma_cia_ntemp*l)];
}
}
} else {
if (temperature[j] > sigma_cia_temp[sigma_cia_ntemp-1]) {
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<cia_npairs;l++) {
sigma_cia_interp[wn + nwngrid*(j + l*nlayers)] = sigma_cia[wn + nwngrid*(sigma_cia_ntemp-1 + sigma_cia_ntemp*l)];
}
}
} else if (temperature[j] < sigma_cia_temp[0]) {
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<cia_npairs;l++) {
sigma_cia_interp[wn + nwngrid*(j + l*nlayers)] = sigma_cia[wn + nwngrid*(sigma_cia_ntemp*l)];
}
}
} else {
for (int t=1; t<sigma_cia_ntemp; t++) {
if ((temperature[j] >= sigma_cia_temp[t-1]) && (temperature[j] < sigma_cia_temp[t])) {
#pragma omp parallel for private(sigma_l, sigma_r, sigma)
for (int wn=0; wn<nwngrid; wn++) {
for (int l=0;l<cia_npairs;l++) {
sigma_l = sigma_cia[wn + nwngrid*(t-1 + sigma_cia_ntemp*l)];
sigma_r = sigma_cia[wn + nwngrid*(t + sigma_cia_ntemp*l)];
sigma = sigma_l + (sigma_r-sigma_l)*(temperature[j]-sigma_cia_temp[t-1])/(sigma_cia_temp[t]-sigma_cia_temp[t-1]);
sigma_cia_interp[wn + nwngrid*(j + l*nlayers)] = sigma;
}
}
}
}
}
}
}
// get mixing ratio of individual molecules in the collision induced absorption (CIA) pairs
for (int c=0; c<cia_npairs;c++) {
if (int(cia_idx[c*2]) >= nactive) {
for (int j=0;j<nlayers;j++) {
x1_idx[c][j] = inactive_mixratio[j+nlayers*(int(cia_idx[c*2])-nactive)];
x2_idx[c][j] = inactive_mixratio[j+nlayers*(int(cia_idx[c*2+1])-nactive)];
}
} else {
for (int j=0;j<nlayers;j++) {
x1_idx[c][j] = active_mixratio[j+nlayers*int(cia_idx[c*2])];
x2_idx[c][j] = active_mixratio[j+nlayers*int(cia_idx[c*2+1])];
}
}
}
// calculate emission
#pragma omp parallel for private(F_total, I1, I2, I3, I4, dtau, tau_sum1, tau_sum2, eta, exponent, BB_wl)
for (int wn=0; wn < nwngrid; wn++) {
F_total = 0.0;
// Contribution from the surface.
I1 = 0;
I2 = 0;
I3 = 0;
I4 = 0;
tau_sum1 = 0.;
tau_sum2 = 0.;
eta = 1.0;
// calculate BB for temperature of layer 0
exponent = exp((h * c) / ((10000./wngrid[wn])*1e-6 * kb * temperature[0]));
BB_wl = ((2.0*h*pow(c,2))/pow((10000./wngrid[wn])*1e-6,5) * (1.0/(exponent - 1)))* 1e-6; // (W/m^2/micron)
for (int l=0;l<nactive;l++) { // active gases
tau_sum1 += (sigma_interp[wn + nwngrid*(l*nlayers)] * active_mixratio[nlayers*l] * density[0] * dz[0]);
}
if (cia == 1) { // cia
for (int c=0; c<cia_npairs;c++) {
tau_sum1 += sigma_cia_interp[wn + nwngrid*(c*nlayers)] * x1_idx[c][0]*x2_idx[c][0] * density[0]*density[0] * dz[0];
}
}
if ((mie == 1) && (pressure[0] >= mie_topP) && (pressure[0] <= mie_bottomP)){ //mie
tau_sum1 += sigma_mie[wn] * density[0] *dz[0];
}
for (int k=0; k<(nlayers); k++) {
// calculate tau from j+1 to TOA
for (int l=0;l<nactive;l++) { // active gases
tau_sum2 += (sigma_interp[wn + nwngrid*(k + l*nlayers)] * active_mixratio[k+nlayers*l] * density[k] * dz[k]);
}
if (cia == 1) { // cia
for (int c=0; c<cia_npairs;c++) {
tau_sum2 += sigma_cia_interp[wn + nwngrid*(k + c*nlayers)] * x1_idx[c][k]*x2_idx[c][k] * density[k]*density[k] * dz[k];
}
}
if ((mie == 1) && (pressure[k] >= mie_topP) && (pressure[k] <= mie_bottomP)){ //mie
tau_sum2 += sigma_mie[wn] * density[k] *dz[k];
}
}
// calculate individual intensities at zenith angles sampled at 4 gaussian quadrature points
I1 += BB_wl * ( exp(-tau_sum2/mu1)) * eta;
I2 += BB_wl * ( exp(-tau_sum2/mu2))* eta;
I3 += BB_wl * ( exp(-tau_sum2/mu3))* eta;
I4 += BB_wl * ( exp(-tau_sum2/mu4))* eta;
// loop through layers from bottom to TOA
for (int j=0; j<(nlayers-1); j++) {
// calculate BB for temperature of layer j
exponent = exp((h * c) / ((10000./wngrid[wn])*1e-6 * kb * temperature[j]));
BB_wl = ((2.0*h*pow(c,2))/pow((10000./wngrid[wn])*1e-6,5) * (1.0/(exponent - 1)))* 1e-6; // (W/m^2/micron)
// calculate tau from j+1 to TOA
tau_sum1 = 0.;
for (int k=j+1; k < nlayers; k++) { // loop through layers to add dtau[k]
for (int l=0;l<nactive;l++) { // active gases
tau_sum1 += (sigma_interp[wn + nwngrid*(k + l*nlayers)] * active_mixratio[k+nlayers*l] * density[k] * dz[k]);
}
// calculating optical depth due inactive gases (rayleigh scattering)
if (rayleigh == 1) {
for (int l=0; l<ninactive; l++) {
//cout << sigma_rayleigh[wn + nwngrid*(l+nactive)] << " " << inactive_mixratio[k+j+nlayers*l] << " " << density[j+k] << " " << dlarray[count] << endl;
//tautmp += sigma_rayleigh[wn + nwngrid*(l+nactive)] * inactive_mixratio[k+j+nlayers*l] * density[j+k] * dlarray[count];
tau_sum1 += sigma_rayleigh[wn + nwngrid*(l+nactive)] * inactive_mixratio[k+nlayers*l] * density[k] * dz[k];
}
}
if (cia == 1) { // cia
for (int c=0; c<cia_npairs;c++) {
tau_sum1 += sigma_cia_interp[wn + nwngrid*(k + c*nlayers)] * x1_idx[c][k]*x2_idx[c][k] * density[k]*density[k] * dz[k];
}
}
if ((mie == 1) && (pressure[k] >= mie_topP) && (pressure[k] <= mie_bottomP)){ //mie
tau_sum1 += sigma_mie[wn] * density[k] *dz[k];
}
}
// calculate tau from j to TOA (just add dtau[j] to tau_sum1 calculated above)
dtau = 0;
for (int l=0;l<nactive;l++) { // active gases
dtau += (sigma_interp[wn + nwngrid*(j + l*nlayers)] * active_mixratio[j+nlayers*l] * density[j] * dz[j]);
}
if (cia == 1) { // cia
for (int c=0; c<cia_npairs;c++) {
dtau += sigma_cia_interp[wn + nwngrid*(j + c*nlayers)] * x1_idx[c][j]*x2_idx[c][j] * density[j]*density[j] * dz[j];
}
}
if (rayleigh == 1) { // rayleigh
for (int l=0; l<ninactive; l++) {
dtau += sigma_rayleigh[wn + nwngrid*(l+nactive)] * inactive_mixratio[j+nlayers*l] * density[j] * dz[j];
}
}
if ((mie == 1) && (pressure[j] >= mie_topP) && (pressure[j] <= mie_bottomP)){ //mie
dtau += sigma_mie[wn] * density[j] *dz[j];
}
tau_sum2 = tau_sum1 + dtau;
// contribution function
contrib[wn + j*nwngrid] = (exp(-tau_sum1) - exp(-tau_sum2));
// calculate individual intensities at zenith angles sampled at 4 gaussian quadrature points
I1 += BB_wl * ( exp(-tau_sum1/mu1) - exp(-tau_sum2/mu1));
I2 += BB_wl * ( exp(-tau_sum1/mu2) - exp(-tau_sum2/mu2));
I3 += BB_wl * ( exp(-tau_sum1/mu3) - exp(-tau_sum2/mu3));
I4 += BB_wl * ( exp(-tau_sum1/mu4) - exp(-tau_sum2/mu4));
}
// Integrating over zenith angle by suming the 4 intensities multiplied by the zenith angle and the
// four quadrature weights. Get flux by multiplying by 2 pi
F_total = 2.0*pi*(I1*mu1*w1 + I2*mu2*w2 + I3*mu3*w3 + I4*mu4*w4) ;
FpFs[wn] = (F_total/star_sed[wn]) * pow((planet_radius/star_radius), 2);
}
delete[] dz;
delete[] sigma_interp;
delete[] sigma_cia_interp;
dz = NULL;
sigma_interp = NULL;
sigma_cia_interp = NULL;
}
}
| 43.32948 | 178 | 0.471385 | [
"vector",
"model"
] |
99fbfb29e2c6f5fdb611f37bcc192cf49faf8cc5 | 3,691 | cpp | C++ | sources/bbd/bbd_filter.cpp | jjYBdx4IL/string-machine | 0bb2ac9092d31402c8ecfd5f681a3a4f2d575024 | [
"BSL-1.0"
] | 34 | 2019-07-08T15:02:10.000Z | 2022-02-20T01:44:02.000Z | sources/bbd/bbd_filter.cpp | jjYBdx4IL/string-machine | 0bb2ac9092d31402c8ecfd5f681a3a4f2d575024 | [
"BSL-1.0"
] | 27 | 2019-07-08T21:46:19.000Z | 2022-03-24T16:01:02.000Z | sources/bbd/bbd_filter.cpp | jjYBdx4IL/string-machine | 0bb2ac9092d31402c8ecfd5f681a3a4f2d575024 | [
"BSL-1.0"
] | 3 | 2019-08-03T22:35:08.000Z | 2022-02-20T01:19:52.000Z | #include "bbd_filter.h"
#include <vector>
#include <mutex>
#include <algorithm>
#include <cassert>
template <class T>
static void interpolate_row(double d, unsigned rows, unsigned cols, const T *src, T *dst)
{
assert(d >= 0);
double row = d * (rows - 1);
unsigned row1 = std::min((unsigned)row, rows - 1);
unsigned row2 = std::min(row1 + 1, rows - 1);
double mu = row - (unsigned)row;
for (unsigned i = 0; i < cols; ++i)
dst[i] = (1 - mu) * src[row1 * cols + i] + mu * src[row2 * cols + i];
}
void BBD_Filter_Coef::interpolate_G(double d, cdouble *g/*[M]*/) const noexcept
{
interpolate_row(d, N, M, G.get(), g);
}
BBD_Filter_Coef BBD::compute_filter(float fs, unsigned steps, const BBD_Filter_Spec &spec)
{
BBD_Filter_Coef coef;
double ts = 1 / fs;
unsigned M = spec.M;
coef.M = M;
coef.N = steps;
coef.G.reset(new cdouble[M * steps]);
coef.P.reset(new cdouble[M]);
cdouble *pm = coef.P.get();
for (unsigned m = 0; m < M; ++m)
pm[m] = std::exp(ts * spec.P[m]);
for (unsigned step = 0; step < steps; ++step) {
double d = (double)step / (steps - 1);
cdouble *gm = &coef.G[step * M];
switch (spec.kind) {
case BBD_Filter_Kind::Input:
for (unsigned m = 0; m < M; ++m)
gm[m] = ts * spec.R[m] * std::pow(pm[m], d);
break;
case BBD_Filter_Kind::Output:
for (unsigned m = 0; m < M; ++m)
gm[m] = (spec.R[m] / spec.P[m]) * std::pow(pm[m], 1 - d);
break;
}
}
cdouble H = 0;
for (unsigned m = 0; m < M; ++m)
H -= spec.R[m] / spec.P[m];
coef.H = H.real();
return coef;
}
//------------------------------------------------------------------------------
struct Filter_Cache_Entry {
float fs;
unsigned steps;
const BBD_Filter_Spec *spec;
BBD_Filter_Coef coef;
};
static std::vector<std::unique_ptr<Filter_Cache_Entry>> filter_cache;
static std::mutex filter_cache_mutex;
const BBD_Filter_Coef &BBD::compute_filter_cached(float fs, unsigned steps, const BBD_Filter_Spec &spec)
{
std::unique_lock<std::mutex> lock(filter_cache_mutex);
for (const std::unique_ptr<Filter_Cache_Entry> &ent : filter_cache) {
if (ent->fs == fs && ent->steps == steps && ent->spec == &spec)
return ent->coef;
}
lock.unlock();
std::unique_ptr<Filter_Cache_Entry> ent(new Filter_Cache_Entry);
BBD_Filter_Coef &coef = ent->coef;
ent->fs = fs;
ent->steps = steps;
ent->spec = &spec;
coef = compute_filter(fs, steps, spec);
lock.lock();
filter_cache.emplace_back(std::move(ent));
return coef;
}
void BBD::clear_filter_cache()
{
std::lock_guard<std::mutex> lock(filter_cache_mutex);
filter_cache.clear();
}
//------------------------------------------------------------------------------
namespace j60 {
static constexpr unsigned M_in = 5;
static constexpr cdouble R_in[M_in] = {{251589, 0}, {-130428, -4165}, {-130428, 4165}, {4634, -22873}, {4634, 22873}};
static constexpr cdouble P_in[M_in] = {{-46580, 0}, {-55482, 25082}, {-55482, -25082}, {-26292, -59437}, {-26292, 59437}};
static constexpr unsigned M_out = 5;
static constexpr cdouble R_out[M_out] = {{5092, 0}, {11256, -99566}, {11256, 99566}, {-13802, -24606}, {-13802, 24606}};
static constexpr cdouble P_out[M_out] = {{-176261, 0}, {-51468, 21437}, {-51468, -21437}, {-26276, -59699}, {-26276, 59699}};
} // namespace j60
const BBD_Filter_Spec bbd_fin_j60 = {BBD_Filter_Kind::Input, j60::M_in, j60::R_in, j60::P_in};
const BBD_Filter_Spec bbd_fout_j60 = {BBD_Filter_Kind::Output, j60::M_out, j60::R_out, j60::P_out};
| 32.095652 | 125 | 0.581685 | [
"vector"
] |
99feaf08de17e30a86e67bcdcbf8a1437041d9bd | 4,489 | cpp | C++ | src/flame/tcp/server.cpp | terrywh/php-mill | b8d6c82dcac230248f9bdcd8300e5f2de417f21f | [
"MIT"
] | 45 | 2017-10-13T02:26:30.000Z | 2021-03-28T10:07:32.000Z | src/flame/tcp/server.cpp | terrywh/php-mill | b8d6c82dcac230248f9bdcd8300e5f2de417f21f | [
"MIT"
] | 1 | 2021-03-12T15:01:07.000Z | 2021-03-16T02:42:17.000Z | src/flame/tcp/server.cpp | terrywh/php-mill | b8d6c82dcac230248f9bdcd8300e5f2de417f21f | [
"MIT"
] | 17 | 2017-05-04T18:48:39.000Z | 2021-09-11T07:04:55.000Z | #include "../coroutine.h"
#include "../udp/udp.h"
#include "../time/time.h"
#include "server.h"
#include "tcp.h"
#include "socket.h"
#include "../log/logger.h"
namespace flame::tcp {
void server::declare(php::extension_entry &ext) {
php::class_entry<server> class_server("flame\\tcp\\server");
class_server
.method<&server::__construct>("__construct", {
{"bind", php::TYPE::STRING},
})
.method<&server::run>("run", {
{"cb", php::TYPE::CALLABLE},
})
.method<&server::close>("close");
ext.add(std::move(class_server));
}
server::server()
: acceptor_(gcontroller->context_x)
, socket_(gcontroller->context_x) {
}
typedef boost::asio::detail::socket_option::boolean<SOL_SOCKET, SO_REUSEPORT> reuse_port;
php::value server::__construct(php::parameters ¶ms) {
boost::system::error_code error;
closed_ = false;
std::string str_addr = params[0];
auto pair = udp::addr2pair(str_addr);
if (pair.first.empty() || pair.second.empty())
throw php::exception(zend_ce_error_exception
, "Failed to bind TCP socket: address malformed"
, -1);
boost::asio::ip::address addr = boost::asio::ip::make_address(pair.first, error);
if (error)
throw php::exception(zend_ce_error_exception
, "Failed to bind TCP socket: address malformed"
, -1);
addr_.address(addr);
addr_.port(std::atoi(pair.second.c_str()));
set("address", str_addr);
acceptor_.open(addr_.protocol());
boost::asio::socket_base::reuse_address opt1(true);
acceptor_.set_option(opt1);
reuse_port opt2(true);
acceptor_.set_option(opt2);
boost::system::error_code err;
acceptor_.bind(addr_, err);
if (err) throw php::exception(zend_ce_exception
, (boost::format("Failed to bind TCP socket: %s") % err.message()).str()
, err.value());
acceptor_.listen(boost::asio::socket_base::max_listen_connections, err);
if (err) throw php::exception(zend_ce_exception
, (boost::format("Failed to listen TCP socket: %s") % err.message()).str()
, err.value());
return nullptr;
}
php::value server::run(php::parameters ¶ms) {
cb_ = params[0];
coroutine_handler ch {coroutine::current};
boost::system::error_code err;
while(!closed_) {
acceptor_.async_accept(socket_, ch[err]);
if (err == boost::asio::error::operation_aborted) break;
else if (err) throw php::exception(zend_ce_error_exception
, (boost::format("Failed to accept TCP socket: %s") % err.message()).str()
, err.value());
else{
php::object obj(php::class_entry<socket>::entry());
socket* ptr = static_cast<socket*>(php::native(obj));
ptr->socket_ = std::move(socket_);
obj.set("local_address",
(boost::format("%s:%d") % ptr->socket_.local_endpoint().address().to_string() % ptr->socket_.local_endpoint().port()).str());
obj.set("remote_address",
(boost::format("%s:%d") % ptr->socket_.remote_endpoint().address().to_string() % ptr->socket_.remote_endpoint().port()).str());
coroutine::start(php::callable([obj, cb = cb_] (php::parameters& params) -> php::value {
try {
cb.call({obj});
} catch(const php::exception& ex) {
// 调用用户异常回调
gcontroller->event("exception", {ex});
// 记录错误信息
php::object obj = ex;
log::logger_->stream() << "[" << time::iso() << "] (ERROR) Uncaught Exception in TCP handler: "<< obj.call("__toString") << std::endl;
}
return nullptr;
}));
}
}
cb_ = nullptr;
return nullptr;
}
php::value server::close(php::parameters ¶ms) {
if (!closed_) {
closed_ = true;
acceptor_.cancel();
}
return nullptr;
}
}
| 39.377193 | 159 | 0.52172 | [
"object"
] |
8202f93c3ca231cecbbaca552f295b601c98b97a | 3,148 | cpp | C++ | testgames/run/game.cpp | jarreed0/ArchGE | c995caf86b11f89f45fcfe1027c6068662dfcde0 | [
"Apache-2.0"
] | 12 | 2017-02-09T21:03:41.000Z | 2021-04-26T14:50:20.000Z | testgames/run/game.cpp | jarreed0/ArchGE | c995caf86b11f89f45fcfe1027c6068662dfcde0 | [
"Apache-2.0"
] | null | null | null | testgames/run/game.cpp | jarreed0/ArchGE | c995caf86b11f89f45fcfe1027c6068662dfcde0 | [
"Apache-2.0"
] | null | null | null | #include "game.h"
Game::Game() {
e.debugMode(true);
e.init("RUN!", WIDTH, HEIGHT, 0);
e.setColor(194, 177, 128);
car.setImage("res/car.png", e.getRenderer());
car.setFrame(0, 0, 57, 35);
car.setSpeed(3);
car.setDestSize(57*SCALE,35*SCALE);
car.center(WIDTH, HEIGHT);
u=d=l=r=0;
vel=0;
inCar=true;
c1.setBounds(WIDTH, HEIGHT);
c1.setCar(car);
c1.setSpeed(SPEED);
c1.setVel(vel);
c1.setRotate(ROTATE);
c1.setScale(SCALE);
c2.setBounds(WIDTH, HEIGHT);
car.setDestCoord(WIDTH-200,HEIGHT-200);
car.setFrameX(57);
c2.setCar(car);
c2.setSpeed(SPEED);
c2.setVel(vel);
c2.setRotate(ROTATE);
c2.setScale(SCALE);
player.setImage("res/player.png", e.getRenderer());
player.setFrame(0,0,50,50);
player.setDest(10, 10, 25, 25);
bullet.setColor(20,30,40);
bullet.setDestSize(3,3);
loop();
}
Game::~Game() {}
void Game::loop() {
while(e.getRunning()) {
input();
update();
draw();
e.loop();
}
}
void Game::draw() {
e.draw(c1.getBurns());
e.draw(c2.getBurns());
e.draw(bullets);
e.draw(c1.getCar());
e.draw(c2.getCar());
e.draw(player);
}
void Game::input() {
i.logPress();
if(i.checkKey(i.esc) || (i.checkKey(i.quit))) e.setRunning(false);
u=d=l=r=0;
if(i.checkKey(i.w)) u=true;
if(i.checkKey(i.s)) d=true;
if(i.checkKey(i.a)) l=true;
if(i.checkKey(i.d)) r=true;
u2=d2=l2=r2=0;
if(i.checkKey(i.up)) u2=true;
if(i.checkKey(i.down)) d2=true;
if(i.checkKey(i.left)) l2=true;
if(i.checkKey(i.right)) r2=true;
u3=d3=l3=r3=0;
if(i.checkKey(i.i)) u3=true;
if(i.checkKey(i.k)) d3=true;
if(i.checkKey(i.j)) l3=true;
if(i.checkKey(i.l)) r3=true;
if(i.checkKey(i.mouseleft)) click=1;
}
void Game::update() {
walk();
c1.move(l3,r3,u3,d3);
c1.drive();
c2.move(l2,r2,u2,d2);
c2.drive();
if(click) fire();
for(int i=0; i<bullets.size(); i++) {
bullets[i].setDestCoord(bullets[i].getDestX()+bullets[i].getVelX(), bullets[i].getDestY()+bullets[i].getVelY());
}
}
double Game::get_degrees(double input) {
const double halfC = M_PI / 180;
return input * halfC;
}
void Game::walk() {
player.lookAt(i);
int dx = cos(get_degrees(player.getAngle()))*PROTATE;
int dy = sin(get_degrees(player.getAngle()))*PROTATE;
if(l) player.moveDest(dy, -dx);
if(r) player.moveDest(-dy, dx);
dx = cos(get_degrees(player.getAngle()))*pvel;
dy = sin(get_degrees(player.getAngle()))*pvel;
if(u) pvel = PSPEED;
if(d) pvel = -PSPEED;
if(!u && !d) pvel = 0;
if(u || d) player.moveDest(dx,dy);
if(player.getDestX() < 0) { player.setDestX(0); pvel=pvel/2; }
if(player.getDestX() > WIDTH-player.getDestW()) { player.setDestX(WIDTH-player.getDestW()); pvel=pvel/2; }
if(player.getDestY() < 0) { player.setDestY(0); pvel=pvel/2; }
if(player.getDestY() > HEIGHT-player.getDestH()) { player.setDestY(HEIGHT-player.getDestH()); pvel=pvel/2; }
}
void Game::fire() {
Object tmp = bullet;
tmp.setSpeed(10);
tmp.setDestCoord(player.getDestX(), player.getDestY());
tmp.setVelTo(i.getMouseX(), i.getMouseY());
cout << tmp.getVelX() << " - " << tmp.getVelY() << endl;
bullets.push_back(tmp);
}
| 22.169014 | 116 | 0.623888 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.