hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
cb4e69dd28ffffcb5e6fa2caf1d40c1e9b27c11d
4,001
cpp
C++
emulation/hel/lib/ChipObject/tInterruptManager.cpp
NWalker1208/synthesis
c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34
[ "Apache-2.0" ]
null
null
null
emulation/hel/lib/ChipObject/tInterruptManager.cpp
NWalker1208/synthesis
c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34
[ "Apache-2.0" ]
null
null
null
emulation/hel/lib/ChipObject/tInterruptManager.cpp
NWalker1208/synthesis
c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34
[ "Apache-2.0" ]
null
null
null
#include <ChipObject/tInterruptManager.h> #include <stdio.h> #ifndef __NI_CRITICAL_SECTION #define __NI_CRITICAL_SECTION #include <OSAL/Synchronized.h> class ni::dsc::osdep::CriticalSection { public: NTReentrantSemaphore sem; }; #endif #include <OSAL/Task.h> namespace nFPGA { uint32_t tInterruptManager::_globalInterruptMask = 0; ni::dsc::osdep::CriticalSection *tInterruptManager::_globalInterruptMaskSemaphore = new ni::dsc::osdep::CriticalSection(); tInterruptManager::tInterruptManager(uint32_t interruptMask, bool watcher, tRioStatusCode *status) : tSystem(status){ this->_interruptMask = interruptMask; this->_watcher = watcher; this->_enabled = false; this->_handler = NULL; *status = NiFpga_Status_Success; if (!watcher) { enable(status); } } tInterruptManager::~tInterruptManager() { } class tInterruptManager::tInterruptThread { private: friend class tInterruptManager; NTTask task; static DWORD WINAPI invokeInternal(LPVOID param){ return tInterruptManager::handlerWrapper((tInterruptManager*) param); } tInterruptThread() : task("Interruptwaiter", &tInterruptThread::invokeInternal) { } }; void tInterruptManager::registerHandler(tInterruptHandler handler, void *param, tRioStatusCode *status) { this->_handler = handler; this->_userParam = param; *status = NiFpga_Status_Success; } uint32_t tInterruptManager::watch(int32_t timeoutInMs, tRioStatusCode *status) { if (timeoutInMs == NiFpga_InfiniteTimeout) { timeoutInMs = INFINITE; } NiFpga_WaitOnIrqs(_DeviceHandle, NULL, _interruptMask, timeoutInMs, NULL, NULL); return 0;// wth guys. plz explain } void tInterruptManager::enable(tRioStatusCode *status){ *status = NiFpga_Status_Success; reserve(status); bool old = this->_enabled; this->_enabled = true; if (old) { this->_thread->task.Stop(); } this->_thread = new tInterruptThread(); this->_thread->task.Start(this); } void tInterruptManager::disable(tRioStatusCode *status){ *status = NiFpga_Status_Success; unreserve(status); bool old = this->_enabled; this->_enabled = false; if (old) { this->_thread->task.Stop(); } } bool tInterruptManager::isEnabled(tRioStatusCode *status){ *status = NiFpga_Status_Success; return this->_enabled; } void tInterruptManager::handler(){ // Don't use this. It is stupid. Doesn't provide irqsAsserted } /// Background task to wait on the IRQ signal until seen, then call the handler. int tInterruptManager::handlerWrapper(tInterruptManager *pInterrupt){ while (pInterrupt->_enabled) { NiFpga_Bool failed = false; uint32_t irqsAsserted = pInterrupt->_interruptMask; NiFpga_WaitOnIrqs(_DeviceHandle, NULL, pInterrupt->_interruptMask, INFINITE, &irqsAsserted, &failed); // Wait until interrupted if (!failed && pInterrupt->_handler!=NULL) { pInterrupt->_handler(irqsAsserted, pInterrupt->_userParam); // Notify whomever subscribed } } return 0; // No error, right? Right. } void tInterruptManager::acknowledge(tRioStatusCode *status){ // Supposed to tell the IRQ manager that this successfully processed the IRQ. But that is difficult } void tInterruptManager::reserve(tRioStatusCode *status){ tInterruptManager::_globalInterruptMaskSemaphore->sem.take(); if ((tInterruptManager::_globalInterruptMask & this->_interruptMask) > 0) { *status = NiFpga_Status_AccessDenied; // You derped printf("Interrupt already in use!\n"); tInterruptManager::_globalInterruptMaskSemaphore->sem.give(); return; } tInterruptManager::_globalInterruptMask |= this->_interruptMask; *status = NiFpga_Status_Success; tInterruptManager::_globalInterruptMaskSemaphore->sem.give(); } void tInterruptManager::unreserve(tRioStatusCode *status){ tInterruptManager::_globalInterruptMaskSemaphore->sem.take(); tInterruptManager::_globalInterruptMask &= ~this->_interruptMask; tInterruptManager::_globalInterruptMaskSemaphore->sem.give(); *status = NiFpga_Status_Success; } }
31.503937
130
0.749563
NWalker1208
cb503f82f6fdc341a6a002ed76655a823192614d
483
hpp
C++
system/sysutil.hpp
mrtryhard/mrtlib
07344c7a374ea60b494fab67c3d66d617143479e
[ "BSD-3-Clause" ]
null
null
null
system/sysutil.hpp
mrtryhard/mrtlib
07344c7a374ea60b494fab67c3d66d617143479e
[ "BSD-3-Clause" ]
null
null
null
system/sysutil.hpp
mrtryhard/mrtlib
07344c7a374ea60b494fab67c3d66d617143479e
[ "BSD-3-Clause" ]
null
null
null
#ifndef MRT_SYSTEM_SYSUTIL_HPP_ #define MRT_SYSTEM_SYSUTIL_HPP_ #include <iostream> namespace mrt { namespace system { void pause() { const auto old_flags = std::cin.flags(); char wait_char; std::cin.setf(old_flags & ~std::ios_base::skipws); std::cout << "Press any key to continue..." << std::endl; std::cin >> std::noskipws >> wait_char; std::cin.setf(old_flags); } } } #endif // MRT_SYSTEM_SYSUTIL_HPP_
23
65
0.610766
mrtryhard
cb5247f01f34da3b7c30612dbdca21cba22c0bbe
1,665
cpp
C++
rollhash.cpp
rakibulhossain/competetive-programming-library
1a1d8e18e411c6094001d56a7aca45cc106e0f09
[ "MIT" ]
1
2021-11-18T13:07:39.000Z
2021-11-18T13:07:39.000Z
rollhash.cpp
Sajjadhossaintalukder/competetive-programming-library
1a1d8e18e411c6094001d56a7aca45cc106e0f09
[ "MIT" ]
null
null
null
rollhash.cpp
Sajjadhossaintalukder/competetive-programming-library
1a1d8e18e411c6094001d56a7aca45cc106e0f09
[ "MIT" ]
2
2021-08-07T05:09:52.000Z
2021-08-23T19:41:07.000Z
#include<bits/stdc++.h> using namespace std; typedef unsigned long long ull; typedef long long ll; int gen_base(const int bef,const int aft) { auto seed = chrono::high_resolution_clock::now().time_since_epoch().count(); mt19937 mt_rand(seed); int base=uniform_int_distribution<int>(bef+1,aft)(mt_rand); return base%2==0? base-1 : base; } struct rollhash { static const int mod = (int)1e9+123; // mod vector<ll>pref1; // hash by mod vector<ull>pref2; // hash by 2^64 static vector<ll>pow1; // pow of base by mod static vector<ull>pow2; // pow of base by 2^64 static int base; // base of hash inline void init(const string& s) { pref1.push_back(0); pref2.push_back(0); int n=s.length(); while((int)pow1.size()<=n) { pow1.push_back((1ll*pow1.back()*base)%mod); pow2.push_back(pow2.back()*base); } for(int i=0; i<n; i++) { assert(base>s[i]); pref1.push_back((pref1[i]+1ll*(s[i]*pow1[i]))%mod); pref2.push_back(pref2[i]+(s[i]*pow2[i])); } } inline pair<ll,ull> operator()(const int pos,const int len,const int mxpow=0)const{ ll hash1=pref1[pos+len]-pref1[pos]; ull hash2=pref2[pos+len]-pref2[pos]; if(hash1<0) hash1+=mod; if(mxpow) { hash1=(1ll*hash1*pow1[mxpow-pos-len+1])%mod; hash2=hash2*pow2[mxpow-pos-len+1]; } return make_pair(hash1,hash2); } }; int rollhash::base((int)1e9+7); vector<ll> rollhash::pow1{1}; vector<ull> rollhash::pow2{1u}; int main() { return 0; }
21.075949
87
0.574775
rakibulhossain
cb530e61579194d839aaa97b208695672266b836
2,307
hpp
C++
test-suite/marketmodel.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
2
2021-12-12T01:27:45.000Z
2022-01-25T17:44:12.000Z
test-suite/marketmodel.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
1
2020-07-17T18:49:22.000Z
2020-07-17T18:49:22.000Z
test-suite/marketmodel.hpp
zhengyuzhang1/QuantLib
65867ab7c44419b69e40e553b41230744b83cff9
[ "BSD-3-Clause" ]
1
2021-07-11T08:32:27.000Z
2021-07-11T08:32:27.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 Ferdinando Ametrano Copyright (C) 2006 StatPro Italia srl Copyright (C) 2012 Peter Caspers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #ifndef quantlib_test_market_model_hpp #define quantlib_test_market_model_hpp #include <ql/qldefines.hpp> #include <boost/test/unit_test.hpp> #include "speedlevel.hpp" /* remember to document new and/or updated tests in the Doxygen comment block of the corresponding class */ class MarketModelTest { public: enum MarketModelType { ExponentialCorrelationFlatVolatility, ExponentialCorrelationAbcdVolatility/*, CalibratedMM*/ }; static void testInverseFloater(); static void testPeriodAdapter(); static void testAllMultiStepProducts(); static void testOneStepForwardsAndOptionlets(); static void testOneStepNormalForwardsAndOptionlets(); static void testCallableSwapNaif(); static void testCallableSwapLS(); static void testCallableSwapAnderson( MarketModelType marketModel, unsigned testedFactor); static void testGreeks(); static void testPathwiseGreeks(); static void testPathwiseVegas(); static void testPathwiseMarketVegas(); static void testStochVolForwardsAndOptionlets(); static void testAbcdVolatilityIntegration(); static void testAbcdVolatilityCompare(); static void testAbcdVolatilityFit(); static void testDriftCalculator(); static void testIsInSubset(); static void testAbcdDegenerateCases(); static void testCovariance(); static boost::unit_test_framework::test_suite* suite(SpeedLevel); }; #endif
37.209677
79
0.763762
zhengyuzhang1
cb57507b16a829830bb93d61c699889ee7ffe63f
1,609
cpp
C++
src/OpcUaStackCore/EventType/EventHandler.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackCore/EventType/EventHandler.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackCore/EventType/EventHandler.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2017 Kai Huebl ([email protected]) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl ([email protected]) */ #include <OpcUaStackCore/EventType/EventHandler.h> #include "OpcUaStackCore/Base/Log.h" namespace OpcUaStackCore { EventHandler::EventHandler(void) : EventHandlerBase() , callback_() { } EventHandler::~EventHandler(void) { } void EventHandler::callback(Callback& callback) { callback_ = callback; } Callback& EventHandler::callback(void) { return callback_; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // interface EventHandlerBase // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ bool EventHandler::fireEvent(OpcUaNodeId& nodeId, EventBase::SPtr& eventBase) { if (!callback_.exist()) { return false; } callback_(eventBase); return true; } }
24.753846
86
0.59913
gianricardo
cb5a8fe23001a40702e83f803cfa086d3fb07f05
742
cpp
C++
python/swig_/timepoint_to_datetime/foo.cpp
SnoopJeDi/playground
73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf
[ "MIT" ]
null
null
null
python/swig_/timepoint_to_datetime/foo.cpp
SnoopJeDi/playground
73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf
[ "MIT" ]
null
null
null
python/swig_/timepoint_to_datetime/foo.cpp
SnoopJeDi/playground
73fab4a38ceeff3da23683e3dd1cb1b3a74cf4cf
[ "MIT" ]
null
null
null
#include <iostream> #include <chrono> std::chrono::steady_clock::time_point get_time() { return std::chrono::steady_clock::now(); } int main(int argc, char** argv) { auto start = get_time(); std::cout << "Hello, I'm going to print out some stars I guess\n"; for(int i=0; i<1000; i++) { std::cout << "*"; } std::cout << "\n\n"; auto end = get_time(); auto dt = end - start; auto dtsec = std::chrono::duration_cast<std::chrono::seconds>(dt); double conv = std::chrono::steady_clock::duration::period::num*1.0 / std::chrono::steady_clock::duration::period::den; std::cout << "That took " << dt.count() << " ticks\n"; std::cout << "That took " << dt.count() * conv << " seconds\n"; }
27.481481
122
0.591644
SnoopJeDi
cb5bd046319c5b0670668f4b193a9d75638ca782
1,357
cpp
C++
apps/panel/widgets/ApplicationListing.cpp
AptRock327/skift
1c8192ab2d3b3f2688128bf7a85b46dbcdcb7cb3
[ "MIT" ]
null
null
null
apps/panel/widgets/ApplicationListing.cpp
AptRock327/skift
1c8192ab2d3b3f2688128bf7a85b46dbcdcb7cb3
[ "MIT" ]
null
null
null
apps/panel/widgets/ApplicationListing.cpp
AptRock327/skift
1c8192ab2d3b3f2688128bf7a85b46dbcdcb7cb3
[ "MIT" ]
null
null
null
#include <libsystem/process/Process.h> #include <libutils/FuzzyMatcher.h> #include <libwidget/Button.h> #include <libwidget/Label.h> #include <libwidget/Window.h> #include "panel/model/MenuEntry.h" #include "panel/widgets/ApplicationListing.h" namespace panel { ApplicationListing::ApplicationListing(Widget *parent) : VScroll(parent) { layout(VFLOW(4)); flags(Widget::FILL); insets(Insetsi(4)); render(); } void ApplicationListing::filter(const String &filter) { if (_filter == filter) { return; } _filter = filter; render(); } void ApplicationListing::render() { FuzzyMatcher matcher; host()->clear_children(); host()->layout(VFLOW(4)); bool find_any = false; MenuEntry::load().foreach ([&](auto &entry) { if (!matcher.match(_filter, entry.name)) { return Iteration::CONTINUE; } find_any = true; auto item = new Button(host(), Button::TEXT, entry.icon, entry.name); item->insets(Insetsi(8)); item->on(Event::ACTION, [this, entry](auto) { process_run(entry.command.cstring(), nullptr); window()->hide(); }); return Iteration::CONTINUE; }); if (!find_any) { new Label(host(), "No application found!", Anchor::CENTER); } } } // namespace panel
19.385714
77
0.607222
AptRock327
cb5d04dd07cb6c00ed36c2d2ea19f01019719629
1,146
cpp
C++
src/aimp_dotnet/SDK/MusicLibrary/Extension/Command/AimpDataStorageCommandUserMark.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
52
2015-04-14T14:39:30.000Z
2022-02-07T07:16:05.000Z
src/aimp_dotnet/SDK/MusicLibrary/Extension/Command/AimpDataStorageCommandUserMark.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
11
2015-04-02T10:45:55.000Z
2022-02-03T07:21:53.000Z
src/aimp_dotnet/SDK/MusicLibrary/Extension/Command/AimpDataStorageCommandUserMark.cpp
Smartoteka/aimp_dotnet
544502b8d080c9280ba11917ef0cc3e8dec44234
[ "Apache-2.0" ]
9
2015-04-05T18:25:57.000Z
2022-02-07T07:20:23.000Z
// ---------------------------------------------------- // AIMP DotNet SDK // Copyright (c) 2014 - 2020 Evgeniy Bogdan // https://github.com/martin211/aimp_dotnet // Mail: [email protected] // ---------------------------------------------------- #include "Stdafx.h" #include "AimpDataStorageCommandUserMark.h" AimpDataStorageCommandUserMark::AimpDataStorageCommandUserMark( gcroot<MusicLibrary::Extension::Command::IAimpDataStorageCommandUserMark^> instance) { _instance = instance; } HRESULT WINAPI AimpDataStorageCommandUserMark::SetMark(VARIANT* ID, const DOUBLE Value) { return HRESULT(_instance->SetMark(AimpConverter::FromVaiant(ID), Value)->ResultType); } HRESULT WINAPI AimpDataStorageCommandUserMark::QueryInterface(REFIID riid, LPVOID* ppvObject) { *ppvObject = nullptr; if (riid == IID_IAIMPMLDataStorageCommandUserMark) { *ppvObject = this; AddRef(); return S_OK; } return E_NOINTERFACE; } ULONG WINAPI AimpDataStorageCommandUserMark::AddRef(void) { return Base::AddRef(); } ULONG WINAPI AimpDataStorageCommandUserMark::Release(void) { return Base::Release(); }
30.157895
95
0.67452
Smartoteka
cb605c273c1aeefd1fd821e29b23580d29d367d4
6,542
cc
C++
src/misc_audio.cc
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
null
null
null
src/misc_audio.cc
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
null
null
null
src/misc_audio.cc
bartvanerp/visqol
9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Google LLC, Andrew Hines // // 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 "misc_audio.h" #include <assert.h> #include <algorithm> #include <cmath> #include <fstream> #include <memory> #include <sstream> #include <utility> #include <vector> #include "absl/base/internal/raw_logging.h" #include "wav_reader.h" namespace Visqol { const size_t MiscAudio::kNumChanMono = 1; const double MiscAudio::kZeroSample = 0.0; const double MiscAudio::kSplReferencePoint = 0.00002; const double kNoiseFloorRelativeToPeakDb = 45.; const double kNoiseFloorAbsoluteDb = -45.; AudioSignal MiscAudio::ScaleToMatchSoundPressureLevel( const AudioSignal &reference, const AudioSignal &degraded) { const double ref_spl = MiscAudio::CalcSoundPressureLevel(reference); const double deg_spl = MiscAudio::CalcSoundPressureLevel(degraded); const double scale_factor = std::pow(10, (ref_spl - deg_spl) / 20); const auto scaled_mat = degraded.data_matrix * scale_factor; AudioSignal scaled_sig{std::move(scaled_mat), degraded.sample_rate}; return scaled_sig; } double MiscAudio::CalcSoundPressureLevel(const AudioSignal &signal) { const auto &data_matrix = signal.data_matrix; double sum = 0; std::for_each(data_matrix.cbegin(), data_matrix.cend(), [&](const double &datum) { sum += std::pow(datum, 2); }); const double sound_pressure = std::sqrt(sum / data_matrix.NumElements()); return 20 * std::log10(sound_pressure / kSplReferencePoint); } // Combines the data from all channels into a single channel. AMatrix<double> MiscAudio::ToMono(const AMatrix<double> &signal) { // If already Mono, nothing to do. if (signal.NumCols() > kNumChanMono) { auto mono_mat = AMatrix<double>::Filled(signal.NumRows(), kNumChanMono, kZeroSample); for (size_t chan_i = 0; chan_i < signal.NumCols(); chan_i++) { for (size_t sample_i = 0; sample_i < signal.NumRows(); sample_i++) { mono_mat(sample_i, 0) += signal(sample_i, chan_i); } } return mono_mat / signal.NumCols(); } else { return signal; } } // Combines the data from all channels into a single channel. AudioSignal MiscAudio::ToMono(const AudioSignal &signal) { // If already Mono, nothing to do. if (signal.data_matrix.NumCols() > kNumChanMono) { const AMatrix<double> sig_mid_mat(MiscAudio::ToMono(signal.data_matrix)); AudioSignal sig_mid; sig_mid.data_matrix = std::move(sig_mid_mat); sig_mid.sample_rate = signal.sample_rate; return sig_mid; } else { return signal; } } AudioSignal MiscAudio::LoadAsMono(const FilePath &path) { AudioSignal sig; std::ifstream wav_file(path.Path().c_str(), std::ios::binary); if (wav_file) { std::stringstream wav_string_stream; wav_string_stream << wav_file.rdbuf(); wav_file.close(); WavReader wav_reader(&wav_string_stream); const size_t num_total_samples = wav_reader.GetNumTotalSamples(); if (wav_reader.IsHeaderValid() && num_total_samples != 0) { std::vector<int16_t> interleaved_samples(num_total_samples); const auto num_samp_read = wav_reader.ReadSamples(num_total_samples, &interleaved_samples[0]); // Certain wav files are 'mostly valid' and have a slight difference with // the reported file length. Warn for these. if (num_samp_read != num_total_samples) { ABSL_RAW_LOG(WARNING, "Number of samples read (%lu) was less than the expected" " number (%lu).", num_samp_read, num_total_samples); } if (num_samp_read > 0) { const auto interleaved_norm_vec = MiscMath::NormalizeInt16ToDouble( interleaved_samples); const auto multi_chan_norm_vec = ExtractMultiChannel( wav_reader.GetNumChannels(), interleaved_norm_vec); const AMatrix<double> outMat(multi_chan_norm_vec); sig.data_matrix = outMat; sig.sample_rate = wav_reader.GetSampleRateHz(); sig = MiscAudio::ToMono(sig); } else { ABSL_RAW_LOG(ERROR, "Error reading data for file %s.", path.Path().c_str()); } } else { ABSL_RAW_LOG(ERROR, "Error reading header for file %s.", path.Path().c_str()); } } else { ABSL_RAW_LOG(ERROR, "Could not find file %s.", path.Path().c_str()); } return sig; } std::vector<std::vector<double>> MiscAudio::ExtractMultiChannel( const int num_channels, const std::vector<double> &interleaved_vector) { assert(interleaved_vector.size() % num_channels == 0); const size_t sub_vector_size = interleaved_vector.size() / num_channels; std::vector<std::vector<double>> multi_channel_vec( num_channels, std::vector<double>(sub_vector_size)); auto itr = interleaved_vector.cbegin(); for (size_t sample = 0; sample < sub_vector_size; sample++) { for (int channel = 0; channel < num_channels; channel++) { multi_channel_vec[channel][sample] = *itr; itr++; } } return multi_channel_vec; } void MiscAudio::PrepareSpectrogramsForComparison( Spectrogram &reference, Spectrogram &degraded) { reference.ConvertToDb(); degraded.ConvertToDb(); // An absolute threshold is also applied. reference.RaiseFloor(kNoiseFloorAbsoluteDb); degraded.RaiseFloor(kNoiseFloorAbsoluteDb); // Apply a per-frame relative threshold. // Note that this is not an STFT spectrogram, the spectrogram bins // here are each the RMS of a band filter output on the time domain signal. reference.RaiseFloorPerFrame(kNoiseFloorRelativeToPeakDb, degraded); // Normalize to a 0dB global floor (which is probably kNoiseFloorAbsoluteDb). double ref_floor = reference.Minimum(); double deg_floor = degraded.Minimum(); double lowest_floor = std::min(ref_floor, deg_floor); reference.SubtractFloor(lowest_floor); degraded.SubtractFloor(lowest_floor); } } // namespace Visqol
35.945055
79
0.693366
bartvanerp
cb62f0e1b2ba7516ed1b49dfe0e0061f35a11105
1,218
cpp
C++
tests/syscall/epoll/host/host.cpp
oe-ci-test/openenclave
966ef04f623aba54720fa95996c1ff9e0585c22b
[ "MIT" ]
null
null
null
tests/syscall/epoll/host/host.cpp
oe-ci-test/openenclave
966ef04f623aba54720fa95996c1ff9e0585c22b
[ "MIT" ]
3
2021-04-07T20:56:28.000Z
2021-09-23T23:31:47.000Z
tests/syscall/epoll/host/host.cpp
oe-ci-test/openenclave
966ef04f623aba54720fa95996c1ff9e0585c22b
[ "MIT" ]
1
2019-11-16T08:21:33.000Z
2019-11-16T08:21:33.000Z
// Copyright (c) Open Enclave SDK contributors. // Licensed under the MIT License. #include <openenclave/host.h> #include <openenclave/internal/tests.h> #include <cstdio> #include <thread> #include "epoll_u.h" using namespace std; int main(int argc, const char* argv[]) { oe_result_t r; const uint32_t flags = oe_get_create_flags(); const oe_enclave_type_t type = OE_ENCLAVE_TYPE_SGX; if (argc != 2) { fprintf(stderr, "Usage: %s ENCLAVE_PATH\n", argv[0]); return 1; } oe_enclave_t* enclave; r = oe_create_epoll_enclave(argv[1], type, flags, NULL, 0, &enclave); OE_TEST(r == OE_OK); set_up(enclave); thread wait_thread( [enclave] { OE_TEST(wait_for_events(enclave) == OE_OK); }); this_thread::sleep_for(100ms); // give wait_thread time to initialize for (int i = 0; i < 100; ++i) { OE_TEST(trigger_and_add_event(enclave) == OE_OK); OE_TEST(trigger_and_delete_event(enclave) == OE_OK); } cancel_wait(enclave); wait_thread.join(); tear_down(enclave); r = oe_terminate_enclave(enclave); OE_TEST(r == OE_OK); printf("=== passed all tests (epoll)\n"); fflush(stdout); return 0; }
23.423077
73
0.646141
oe-ci-test
cb6515063d85df722a2f25fdfcb40563f6d94796
4,869
cpp
C++
inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
1
2020-10-13T22:49:18.000Z
2020-10-13T22:49:18.000Z
inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
1
2021-07-24T15:22:27.000Z
2021-07-24T15:22:27.000Z
inference-engine/thirdparty/clDNN/kernel_selector/core/actual_kernels/convolution/convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.cpp
cwzrad/openvino
ae4bd370eac7c695bd797a31e62317d328dbe742
[ "Apache-2.0" ]
1
2020-08-13T08:33:55.000Z
2020-08-13T08:33:55.000Z
// Copyright (c) 2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3.h" #include "kernel_selector_utils.h" #include "common_tools.h" #include <vector> #include <iostream> // // Kernel specific constants // #define SIMD_SIZE 16 namespace kernel_selector { ParamsKey Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::GetSupportedKey() const { ParamsKey k; k.EnableInputDataType(Datatype::INT8); k.EnableInputDataType(Datatype::UINT8); k.EnableOutputDataType(Datatype::INT8); k.EnableOutputDataType(Datatype::UINT8); k.EnableOutputDataType(Datatype::F32); k.EnableInputWeightsType(WeightsType::INT8); k.EnableInputLayout(DataLayout::bs_fs_yx_bsv16_fsv16); k.EnableOutputLayout(DataLayout::bs_fs_yx_bsv16_fsv16); k.EnableDifferentTypes(); k.EnableDifferentInputWeightsTypes(); k.EnableTensorOffset(); k.EnableTensorPitches(); k.EnableBiasPerFeature(); k.EnableNonBiasTerm(); k.EnableBatching(); k.EnableQuantization(QuantizationType::SYMMETRIC); k.DisableTuning(); return k; } KernelsData Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::GetKernelsData(const Params& params, const optional_params& options) const { return GetCommonKernelsData(params, options); } JitConstants Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::GetJitConstants(const convolution_params& params, const DispatchData& kd) const { auto mem_consts = Parent::GetJitConstants(params, kd); if (!params.fused_ops.empty()) { auto input_dt = GetActivationType(params); FusedOpsConfiguration conf_scalar = {"", {"out_b", "out_f + get_sub_group_local_id()", "out_y", "out_x"}, "dequantized", input_dt, 1, LoadType::FEATURE_SHUFFLE}; conf_scalar.SetLoopAxes({ Tensor::DataChannelName::BATCH }, true); conf_scalar.SetShuffleVarName("i"); mem_consts.Merge(MakeFusedOpsJitConstants(params, {conf_scalar})); } return mem_consts; } // GetJitConstants ConvolutionKernelBase::DispatchData Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::SetDefault(const convolution_params& params, int) const { DispatchData kd; const auto& output = params.output; std::vector<size_t> global = {output.X().v, output.Y().v, output.Feature().v / 16 * output.Batch().v}; std::vector<size_t> local = {1, 1, SIMD_SIZE}; kd.gws0 = global[0]; kd.gws1 = global[1]; kd.gws2 = global[2]; kd.lws0 = local[0]; kd.lws1 = local[1]; kd.lws2 = local[2]; kd.cldnnStyle = {0, 0, 0, 0, 0}; kd.gemmStyle = {0, 0, 0, 0, 0, 0}; kd.efficiency = FORCE_PRIORITY_2; return kd; } // SetDefault bool Convolution_kernel_imad_bs_fs_yx_bsv16_fsv16_3x3::Validate(const Params& params, const optional_params& options) const { if (!Parent::Validate(params, options)) { return false; } KernelData kd = KernelData::Default<convolution_params>(params); convolution_params& newParams = *static_cast<convolution_params*>(kd.params.get()); if ((newParams.filterSize.x != newParams.filterSize.y) || newParams.filterSize.x != 3) { // Fitler size needs to be 3x3 return false; } if (newParams.stride.x != newParams.stride.y) { // Strides must be equal return false; } if (newParams.output.X().v != newParams.output.Y().v) { // W and H must be equal return false; } if (newParams.output.Feature().v % 16 != 0) { // output feature size must be divided by 16 return false; } if (newParams.output.Batch().v % 16 != 0) { // batch size must be divided by 16 return false; } // check that all fused ops except eltwise have only feature or scalar inputs for (auto& fo : newParams.fused_ops) { if (fo.GetType() == FusedOpType::ELTWISE) continue; for (auto& input : fo.tensors) { if (input.X().v != 1 || input.Y().v != 1 || input.Batch().v != 1) return false; } } return true; } } // namespace kernel_selector
33.122449
144
0.653933
cwzrad
cb680c2a4f44b30f8779f92f9997901e875fa3c6
6,605
cpp
C++
tag/src/v20180813/model/ResourcesTag.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
tag/src/v20180813/model/ResourcesTag.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
tag/src/v20180813/model/ResourcesTag.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tag/v20180813/model/ResourcesTag.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tag::V20180813::Model; using namespace rapidjson; using namespace std; ResourcesTag::ResourcesTag() : m_resourceRegionHasBeenSet(false), m_serviceTypeHasBeenSet(false), m_resourcePrefixHasBeenSet(false), m_resourceIdHasBeenSet(false), m_tagsHasBeenSet(false) { } CoreInternalOutcome ResourcesTag::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("ResourceRegion") && !value["ResourceRegion"].IsNull()) { if (!value["ResourceRegion"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ResourceRegion` IsString=false incorrectly").SetRequestId(requestId)); } m_resourceRegion = string(value["ResourceRegion"].GetString()); m_resourceRegionHasBeenSet = true; } if (value.HasMember("ServiceType") && !value["ServiceType"].IsNull()) { if (!value["ServiceType"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ServiceType` IsString=false incorrectly").SetRequestId(requestId)); } m_serviceType = string(value["ServiceType"].GetString()); m_serviceTypeHasBeenSet = true; } if (value.HasMember("ResourcePrefix") && !value["ResourcePrefix"].IsNull()) { if (!value["ResourcePrefix"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ResourcePrefix` IsString=false incorrectly").SetRequestId(requestId)); } m_resourcePrefix = string(value["ResourcePrefix"].GetString()); m_resourcePrefixHasBeenSet = true; } if (value.HasMember("ResourceId") && !value["ResourceId"].IsNull()) { if (!value["ResourceId"].IsString()) { return CoreInternalOutcome(Error("response `ResourcesTag.ResourceId` IsString=false incorrectly").SetRequestId(requestId)); } m_resourceId = string(value["ResourceId"].GetString()); m_resourceIdHasBeenSet = true; } if (value.HasMember("Tags") && !value["Tags"].IsNull()) { if (!value["Tags"].IsArray()) return CoreInternalOutcome(Error("response `ResourcesTag.Tags` is not array type")); const Value &tmpValue = value["Tags"]; for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { Tag item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_tags.push_back(item); } m_tagsHasBeenSet = true; } return CoreInternalOutcome(true); } void ResourcesTag::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_resourceRegionHasBeenSet) { Value iKey(kStringType); string key = "ResourceRegion"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_resourceRegion.c_str(), allocator).Move(), allocator); } if (m_serviceTypeHasBeenSet) { Value iKey(kStringType); string key = "ServiceType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_serviceType.c_str(), allocator).Move(), allocator); } if (m_resourcePrefixHasBeenSet) { Value iKey(kStringType); string key = "ResourcePrefix"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_resourcePrefix.c_str(), allocator).Move(), allocator); } if (m_resourceIdHasBeenSet) { Value iKey(kStringType); string key = "ResourceId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_resourceId.c_str(), allocator).Move(), allocator); } if (m_tagsHasBeenSet) { Value iKey(kStringType); string key = "Tags"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kArrayType).Move(), allocator); int i=0; for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i) { value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } string ResourcesTag::GetResourceRegion() const { return m_resourceRegion; } void ResourcesTag::SetResourceRegion(const string& _resourceRegion) { m_resourceRegion = _resourceRegion; m_resourceRegionHasBeenSet = true; } bool ResourcesTag::ResourceRegionHasBeenSet() const { return m_resourceRegionHasBeenSet; } string ResourcesTag::GetServiceType() const { return m_serviceType; } void ResourcesTag::SetServiceType(const string& _serviceType) { m_serviceType = _serviceType; m_serviceTypeHasBeenSet = true; } bool ResourcesTag::ServiceTypeHasBeenSet() const { return m_serviceTypeHasBeenSet; } string ResourcesTag::GetResourcePrefix() const { return m_resourcePrefix; } void ResourcesTag::SetResourcePrefix(const string& _resourcePrefix) { m_resourcePrefix = _resourcePrefix; m_resourcePrefixHasBeenSet = true; } bool ResourcesTag::ResourcePrefixHasBeenSet() const { return m_resourcePrefixHasBeenSet; } string ResourcesTag::GetResourceId() const { return m_resourceId; } void ResourcesTag::SetResourceId(const string& _resourceId) { m_resourceId = _resourceId; m_resourceIdHasBeenSet = true; } bool ResourcesTag::ResourceIdHasBeenSet() const { return m_resourceIdHasBeenSet; } vector<Tag> ResourcesTag::GetTags() const { return m_tags; } void ResourcesTag::SetTags(const vector<Tag>& _tags) { m_tags = _tags; m_tagsHasBeenSet = true; } bool ResourcesTag::TagsHasBeenSet() const { return m_tagsHasBeenSet; }
28.106383
139
0.672521
datalliance88
cb691e6d92f3a9a20d483cbfad738dfa15f23b4a
16,699
cpp
C++
src/apps/sequencer/python/sequencer.cpp
forestcaver/performer
17750bc8e6fa23cd806d58a9c519fac25a52473f
[ "MIT" ]
1
2019-04-19T01:34:03.000Z
2019-04-19T01:34:03.000Z
src/apps/sequencer/python/sequencer.cpp
forestcaver/performer
17750bc8e6fa23cd806d58a9c519fac25a52473f
[ "MIT" ]
null
null
null
src/apps/sequencer/python/sequencer.cpp
forestcaver/performer
17750bc8e6fa23cd806d58a9c519fac25a52473f
[ "MIT" ]
null
null
null
#include "SequencerApp.h" #include "model/Model.h" #include <pybind11/pybind11.h> namespace py = pybind11; void register_sequencer(py::module &m) { // ------------------------------------------------------------------------ // Sequencer // ------------------------------------------------------------------------ py::class_<SequencerApp> sequencer(m, "Sequencer"); sequencer .def_property_readonly("model", [] (SequencerApp &app) { return &app.model; }) ; // ------------------------------------------------------------------------ // Model // ------------------------------------------------------------------------ py::class_<Model> model(m, "Model"); model .def_property_readonly("project", [] (Model &model) { return &model.project(); }) ; // ------------------------------------------------------------------------ // Project // ------------------------------------------------------------------------ py::class_<Project> project(m, "Project"); project .def_property("name", &Project::name, &Project::setName) .def_property("slot", &Project::slot, &Project::setSlot) .def_property("tempo", &Project::tempo, &Project::setTempo) .def_property("swing", &Project::swing, &Project::setSwing) .def_property("syncMeasure", &Project::syncMeasure, &Project::setSyncMeasure) .def_property("scale", &Project::scale, &Project::setScale) .def_property("rootNote", &Project::rootNote, &Project::setRootNote) .def_property("recordMode", &Project::recordMode, &Project::setRecordMode) .def_property_readonly("clockSetup", [] (Project &project) { return &project.clockSetup(); }) .def_property_readonly("tracks", [] (Project &project) { py::list result; for (int i = 0; i < CONFIG_TRACK_COUNT; ++i) { result.append(&project.track(i)); } return result; }) .def("cvOutputTrack", &Project::cvOutputTrack) .def("setCvOutputTrack", &Project::setCvOutputTrack) .def("gateOutputTrack", &Project::gateOutputTrack) .def("setGateOutputTrack", &Project::setGateOutputTrack) .def_property_readonly("song", [] (Project &project) { return &project.song(); }) .def_property_readonly("playState", [] (Project &project) { return &project.playState(); }) // TODO userScales .def_property_readonly("routing", [] (Project &project) { return &project.routing(); }) .def_property_readonly("midiOutput", [] (Project &project) { return &project.midiOutput(); }) .def_property("selectedTrackIndex", &Project::selectedTrackIndex, &Project::setSelectedTrackIndex) .def_property("selectedPatternIndex", &Project::selectedPatternIndex, &Project::setSelectedPatternIndex) .def("clear", &Project::clear) .def("clearPattern", &Project::clearPattern) .def("setTrackMode", &Project::setTrackMode) ; // ------------------------------------------------------------------------ // Types // ------------------------------------------------------------------------ py::class_<Types> types(m, "Types"); py::enum_<Types::RecordMode>(types, "RecordMode") .value("Overdub", Types::RecordMode::Overdub) .value("Overwrite", Types::RecordMode::Overwrite) .export_values() ; py::enum_<Types::PlayMode>(types, "PlayMode") .value("Aligned", Types::PlayMode::Aligned) .value("Free", Types::PlayMode::Free) .export_values() ; py::enum_<Types::FillMode>(types, "FillMode") .value("None", Types::FillMode::None) .value("Gates", Types::FillMode::Gates) .value("NextPattern", Types::FillMode::NextPattern) .export_values() ; py::enum_<Types::RunMode>(types, "RunMode") .value("Forward", Types::RunMode::Forward) .value("Backward", Types::RunMode::Backward) .value("Pendulum", Types::RunMode::Pendulum) .value("PingPong", Types::RunMode::PingPong) .value("Random", Types::RunMode::Random) .value("RandomWalk", Types::RunMode::RandomWalk) .export_values() ; py::enum_<Types::VoltageRange>(types, "VoltageRange") .value("Unipolar1V", Types::VoltageRange::Unipolar1V) .value("Unipolar2V", Types::VoltageRange::Unipolar2V) .value("Unipolar3V", Types::VoltageRange::Unipolar3V) .value("Unipolar4V", Types::VoltageRange::Unipolar4V) .value("Unipolar5V", Types::VoltageRange::Unipolar5V) .value("Bipolar1V", Types::VoltageRange::Bipolar1V) .value("Bipolar2V", Types::VoltageRange::Bipolar2V) .value("Bipolar3V", Types::VoltageRange::Bipolar3V) .value("Bipolar4V", Types::VoltageRange::Bipolar4V) .value("Bipolar5V", Types::VoltageRange::Bipolar5V) .export_values() ; // ------------------------------------------------------------------------ // ClockSetup // ------------------------------------------------------------------------ py::class_<ClockSetup> clockSetup(m, "ClockSetup"); clockSetup .def_property("mode", &ClockSetup::mode, &ClockSetup::setMode) .def_property("shiftMode", &ClockSetup::shiftMode, &ClockSetup::setShiftMode) .def_property("clockInputDivisor", &ClockSetup::clockInputDivisor, &ClockSetup::setClockInputDivisor) .def_property("clockInputMode", &ClockSetup::clockInputMode, &ClockSetup::setClockInputMode) .def_property("clockOutputDivisor", &ClockSetup::clockOutputDivisor, &ClockSetup::setClockOutputDivisor) .def_property("clockOutputPulse", &ClockSetup::clockOutputPulse, &ClockSetup::setClockOutputPulse) .def_property("clockOutputMode", &ClockSetup::clockOutputMode, &ClockSetup::setClockOutputMode) .def_property("midiRx", &ClockSetup::midiRx, &ClockSetup::setMidiRx) .def_property("midiTx", &ClockSetup::midiTx, &ClockSetup::setMidiTx) .def_property("usbRx", &ClockSetup::usbRx, &ClockSetup::setUsbRx) .def_property("usbTx", &ClockSetup::usbTx, &ClockSetup::setUsbTx) .def("clear", &ClockSetup::clear) ; py::enum_<ClockSetup::Mode>(clockSetup, "Mode") .value("Auto", ClockSetup::Mode::Auto) .value("Master", ClockSetup::Mode::Master) .value("Slave", ClockSetup::Mode::Slave) .export_values() ; py::enum_<ClockSetup::ShiftMode>(clockSetup, "ShiftMode") .value("Restart", ClockSetup::ShiftMode::Restart) .value("Pause", ClockSetup::ShiftMode::Pause) .export_values() ; py::enum_<ClockSetup::ClockInputMode>(clockSetup, "ClockInputMode") .value("Reset", ClockSetup::ClockInputMode::Reset) .value("Run", ClockSetup::ClockInputMode::Run) .value("StartStop", ClockSetup::ClockInputMode::StartStop) .export_values() ; py::enum_<ClockSetup::ClockOutputMode>(clockSetup, "ClockOutputMode") .value("Reset", ClockSetup::ClockOutputMode::Reset) .value("Run", ClockSetup::ClockOutputMode::Run) .export_values() ; // ------------------------------------------------------------------------ // Track // ------------------------------------------------------------------------ py::class_<Track> track(m, "Track"); track .def_property_readonly("trackIndex", &Track::trackIndex) .def_property_readonly("trackMode", &Track::trackMode) .def_property("linkTrack", &Track::linkTrack, &Track::setLinkTrack) .def_property_readonly("noteTrack", [] (Track &track) { return &track.noteTrack(); }) .def_property_readonly("curveTrack", [] (Track &track) { return &track.curveTrack(); }) .def_property_readonly("midiCvTrack", [] (Track &track) { return &track.midiCvTrack(); }) .def("clear", &Track::clear) .def("clearPattern", &Track::clearPattern) ; py::enum_<Track::TrackMode>(track, "TrackMode") .value("Note", Track::TrackMode::Note) .value("Curve", Track::TrackMode::Curve) .value("MidiCv", Track::TrackMode::MidiCv) .export_values() ; // ------------------------------------------------------------------------ // NoteTrack // ------------------------------------------------------------------------ py::class_<NoteTrack> noteTrack(m, "NoteTrack"); noteTrack .def_property("playMode", &NoteTrack::playMode, &NoteTrack::setPlayMode) .def_property("fillMode", &NoteTrack::fillMode, &NoteTrack::setFillMode) .def_property("slideTime", &NoteTrack::slideTime, &NoteTrack::setSlideTime) .def_property("octave", &NoteTrack::octave, &NoteTrack::setOctave) .def_property("transpose", &NoteTrack::transpose, &NoteTrack::setTranspose) .def_property("rotate", &NoteTrack::rotate, &NoteTrack::setRotate) .def_property("gateProbabilityBias", &NoteTrack::gateProbabilityBias, &NoteTrack::setGateProbabilityBias) .def_property("retriggerProbabilityBias", &NoteTrack::retriggerProbabilityBias, &NoteTrack::setRetriggerProbabilityBias) .def_property("lengthBias", &NoteTrack::lengthBias, &NoteTrack::setLengthBias) .def_property("noteProbabilityBias", &NoteTrack::noteProbabilityBias, &NoteTrack::setNoteProbabilityBias) .def_property_readonly("sequences", [] (NoteTrack &noteTrack) { py::list result; for (int i = 0; i < CONFIG_PATTERN_COUNT; ++i) { result.append(&noteTrack.sequence(i)); } return result; }) .def("clear", &NoteTrack::clear) ; // ------------------------------------------------------------------------ // CurveTrack // ------------------------------------------------------------------------ py::class_<CurveTrack> curveTrack(m, "CurveTrack"); curveTrack .def_property("playMode", &CurveTrack::playMode, &CurveTrack::setPlayMode) .def_property("fillMode", &CurveTrack::fillMode, &CurveTrack::setFillMode) .def_property("rotate", &CurveTrack::rotate, &CurveTrack::setRotate) .def_property_readonly("sequences", [] (CurveTrack &curveTrack) { py::list result; for (int i = 0; i < CONFIG_PATTERN_COUNT; ++i) { result.append(&curveTrack.sequence(i)); } return result; }) .def("clear", &CurveTrack::clear) ; // ------------------------------------------------------------------------ // MidiCvTrack // ------------------------------------------------------------------------ py::class_<MidiCvTrack> midiCvTrack(m, "MidiCvTrack"); midiCvTrack .def_property_readonly("source", [] (MidiCvTrack &midiCvTrack) { return &midiCvTrack.source(); }) .def_property("voices", &MidiCvTrack::voices, &MidiCvTrack::setVoices) .def_property("voiceConfig", &MidiCvTrack::voiceConfig, &MidiCvTrack::setVoiceConfig) .def_property("pitchBendRange", &MidiCvTrack::pitchBendRange, &MidiCvTrack::setPitchBendRange) .def_property("modulationRange", &MidiCvTrack::modulationRange, &MidiCvTrack::setModulationRange) .def_property("retrigger", &MidiCvTrack::retrigger, &MidiCvTrack::setRetrigger) .def("clear", &MidiCvTrack::clear) ; py::enum_<MidiCvTrack::VoiceConfig>(midiCvTrack, "VoiceConfig") .value("Pitch", MidiCvTrack::VoiceConfig::Pitch) .value("PitchVelocity", MidiCvTrack::VoiceConfig::PitchVelocity) .value("PitchVelocityPressure", MidiCvTrack::VoiceConfig::PitchVelocityPressure) .export_values() ; // ------------------------------------------------------------------------ // NoteSequence // ------------------------------------------------------------------------ py::class_<NoteSequence> noteSequence(m, "NoteSequence"); noteSequence .def_property("scale", &NoteSequence::scale, &NoteSequence::setScale) .def_property("rootNote", &NoteSequence::rootNote, &NoteSequence::setRootNote) .def_property("divisor", &NoteSequence::divisor, &NoteSequence::setDivisor) .def_property("resetMeasure", &NoteSequence::resetMeasure, &NoteSequence::setResetMeasure) .def_property("runMode", &NoteSequence::runMode, &NoteSequence::setRunMode) .def_property("firstStep", &NoteSequence::firstStep, &NoteSequence::setFirstStep) .def_property("lastStep", &NoteSequence::lastStep, &NoteSequence::setLastStep) .def_property_readonly("steps", [] (NoteSequence &noteSequence) { py::list result; for (int i = 0; i < CONFIG_STEP_COUNT; ++i) { result.append(&noteSequence.step(i)); } return result; }) .def("clear", &NoteSequence::clear) .def("clearSteps", &NoteSequence::clearSteps) ; py::class_<NoteSequence::Step> noteSequenceStep(noteSequence, "Step"); noteSequenceStep .def_property("gate", &NoteSequence::Step::gate, &NoteSequence::Step::setGate) .def_property("gateProbability", &NoteSequence::Step::gateProbability, &NoteSequence::Step::setGateProbability) .def_property("slide", &NoteSequence::Step::slide, &NoteSequence::Step::setSlide) .def_property("retrigger", &NoteSequence::Step::retrigger, &NoteSequence::Step::setRetrigger) .def_property("retriggerProbability", &NoteSequence::Step::retriggerProbability, &NoteSequence::Step::setRetriggerProbability) .def_property("length", &NoteSequence::Step::length, &NoteSequence::Step::setLength) .def_property("lengthVariationRange", &NoteSequence::Step::lengthVariationRange, &NoteSequence::Step::setLengthVariationRange) .def_property("lengthVariationProbability", &NoteSequence::Step::lengthVariationProbability, &NoteSequence::Step::setLengthVariationProbability) .def_property("note", &NoteSequence::Step::note, &NoteSequence::Step::setNote) .def_property("noteVariationRange", &NoteSequence::Step::noteVariationRange, &NoteSequence::Step::setNoteVariationRange) .def_property("noteVariationProbability", &NoteSequence::Step::noteVariationProbability, &NoteSequence::Step::setNoteVariationProbability) .def("clear", &NoteSequence::Step::clear) ; // ------------------------------------------------------------------------ // CurveSequence // ------------------------------------------------------------------------ py::class_<CurveSequence> curveSequence(m, "CurveSequence"); curveSequence .def_property("range", &CurveSequence::range, &CurveSequence::setRange) .def_property("divisor", &CurveSequence::divisor, &CurveSequence::setDivisor) .def_property("resetMeasure", &CurveSequence::resetMeasure, &CurveSequence::setResetMeasure) .def_property("runMode", &CurveSequence::runMode, &CurveSequence::setRunMode) .def_property("firstStep", &CurveSequence::firstStep, &CurveSequence::setFirstStep) .def_property("lastStep", &CurveSequence::lastStep, &CurveSequence::setLastStep) .def_property_readonly("steps", [] (CurveSequence &curveSequence) { py::list result; for (int i = 0; i < CONFIG_STEP_COUNT; ++i) { result.append(&curveSequence.step(i)); } return result; }) .def("clear", &CurveSequence::clear) .def("clearSteps", &CurveSequence::clearSteps) ; py::class_<CurveSequence::Step> curveSequenceStep(curveSequence, "Step"); curveSequenceStep .def_property("shape", &CurveSequence::Step::shape, &CurveSequence::Step::setShape) .def_property("min", &CurveSequence::Step::min, &CurveSequence::Step::setMin) .def_property("max", &CurveSequence::Step::max, &CurveSequence::Step::setMax) .def("clear", &CurveSequence::Step::clear) ; // ------------------------------------------------------------------------ // Song // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // PlayState // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Routing // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // MidiOutput // ------------------------------------------------------------------------ }
49.259587
152
0.565243
forestcaver
cb697c77faa2819c8e8d38ca4485f7ea793d8b14
5,064
cpp
C++
libs/variant/test/rvalue_test.cpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
libs/variant/test/rvalue_test.cpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
libs/variant/test/rvalue_test.cpp
juslee/boost-svn
6d5a03c1f5ed3e2b23bd0f3ad98d13ff33d4dcbb
[ "BSL-1.0" ]
null
null
null
//----------------------------------------------------------------------------- // boost-libs variant/test/rvalue_test.cpp source file // See http://www.boost.org for updates, documentation, and revision history. //----------------------------------------------------------------------------- // // Copyright (c) 2012 // 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) #include "boost/config.hpp" #include "boost/test/minimal.hpp" #include "boost/variant.hpp" // This test requires BOOST_HAS_RVALUE_REFS #ifndef BOOST_HAS_RVALUE_REFS void run() { BOOST_CHECK(true); } #else class move_copy_conting_class { public: static unsigned int moves_count; static unsigned int copy_count; move_copy_conting_class(){} move_copy_conting_class(move_copy_conting_class&&) { ++ moves_count; } move_copy_conting_class& operator=(move_copy_conting_class&&) { ++ moves_count; return *this; } move_copy_conting_class(const move_copy_conting_class&) { ++ copy_count; } move_copy_conting_class& operator=(const move_copy_conting_class&) { ++ copy_count; return *this; } }; unsigned int move_copy_conting_class::moves_count = 0; unsigned int move_copy_conting_class::copy_count = 0; void run() { typedef boost::variant<int, move_copy_conting_class> variant_I_type; variant_I_type v1, v2; // Assuring that `move_copy_conting_class` was not created BOOST_CHECK(move_copy_conting_class::copy_count == 0); BOOST_CHECK(move_copy_conting_class::moves_count == 0); v1 = move_copy_conting_class(); // Assuring that `move_copy_conting_class` was moved at least once BOOST_CHECK(move_copy_conting_class::moves_count != 0); unsigned int total_count = move_copy_conting_class::moves_count + move_copy_conting_class::copy_count; move_copy_conting_class var; v1 = 0; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v1 = var; // Assuring that move assignment operator moves/copyes value not more times than copy assignment operator BOOST_CHECK(total_count <= move_copy_conting_class::moves_count + move_copy_conting_class::copy_count); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v2 = static_cast<variant_I_type&&>(v1); // Assuring that `move_copy_conting_class` in v1 was moved at least once and was not copied BOOST_CHECK(move_copy_conting_class::moves_count != 0); BOOST_CHECK(move_copy_conting_class::copy_count == 0); v1 = move_copy_conting_class(); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v2 = static_cast<variant_I_type&&>(v1); // Assuring that `move_copy_conting_class` in v1 was moved at least once and was not copied BOOST_CHECK(move_copy_conting_class::moves_count != 0); BOOST_CHECK(move_copy_conting_class::copy_count == 0); total_count = move_copy_conting_class::moves_count + move_copy_conting_class::copy_count; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v1 = v2; // Assuring that move assignment operator moves/copyes value not more times than copy assignment operator BOOST_CHECK(total_count <= move_copy_conting_class::moves_count + move_copy_conting_class::copy_count); typedef boost::variant<move_copy_conting_class, int> variant_II_type; variant_II_type v3; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v1 = static_cast<variant_II_type&&>(v3); // Assuring that `move_copy_conting_class` in v3 was moved at least once (v1 and v3 have different types) BOOST_CHECK(move_copy_conting_class::moves_count != 0); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; v2 = static_cast<variant_I_type&&>(v1); // Assuring that `move_copy_conting_class` in v1 was moved at least once (v1 and v3 have different types) BOOST_CHECK(move_copy_conting_class::moves_count != 0); move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; variant_I_type v5(static_cast<variant_I_type&&>(v1)); // Assuring that `move_copy_conting_class` in v1 was moved at least once and was not copied BOOST_CHECK(move_copy_conting_class::moves_count != 0); BOOST_CHECK(move_copy_conting_class::copy_count == 0); total_count = move_copy_conting_class::moves_count + move_copy_conting_class::copy_count; move_copy_conting_class::moves_count = 0; move_copy_conting_class::copy_count = 0; variant_I_type v6(v1); // Assuring that move constructor moves/copyes value not more times than copy constructor BOOST_CHECK(total_count <= move_copy_conting_class::moves_count + move_copy_conting_class::copy_count); } #endif int test_main(int , char* []) { run(); return 0; }
36.963504
109
0.720182
juslee
cb6a19f9d53d524703bf6ff2cd44ea4655a5d8d4
696
cpp
C++
#1059 Prime Factors.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
1
2021-12-26T08:34:47.000Z
2021-12-26T08:34:47.000Z
#1059 Prime Factors.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#1059 Prime Factors.cpp
ZachVec/PAT-Advanced
52ba5989c095ddbee3c297e82a4b3d0d2e0cd449
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> int main() { size_t num; if(!scanf("%zu", &num)) return 0; std::vector<bool> isPrime(50000, true); isPrime[0] = isPrime[1] = false; for(size_t i = 2; i < 50000; ++i) { if(!isPrime[i]) continue; for(size_t j = 2 * i; j < 50000; j *= 2) isPrime[j] = false; } printf("%zu=", num); if(num == 1) putchar('1'); for(size_t i = 2, n = num, exp; i < 50000 && n != 1; ++i) { if(!isPrime[i] || n % i != 0) continue; if(n != num) putchar('*'); for(exp = 0; n % i == 0; ++exp) n /= i; printf("%zu", i); if(exp != 1) printf("^%zu", exp); } putchar('\n'); return 0; }
27.84
68
0.465517
ZachVec
cb6af83f1807b38ebb0333de2396014c2f838543
21,064
cpp
C++
library/property/test/src/test_tetengo.property.property_set.cpp
kaorut/tetengo
3360cce3e3f4c92b18154927685986c1fa7b4e8e
[ "MIT" ]
null
null
null
library/property/test/src/test_tetengo.property.property_set.cpp
kaorut/tetengo
3360cce3e3f4c92b18154927685986c1fa7b4e8e
[ "MIT" ]
153
2019-08-11T05:26:36.000Z
2021-06-23T17:24:04.000Z
library/property/test/src/test_tetengo.property.property_set.cpp
kaorut/tetengo
3360cce3e3f4c92b18154927685986c1fa7b4e8e
[ "MIT" ]
null
null
null
/*! \file \brief A property set. Copyright (C) 2019-2021 kaoru https://www.tetengo.org/ */ #include <cstdint> #include <filesystem> #include <iterator> #include <memory> #include <optional> #include <string> #include <string_view> #include <utility> #include <vector> #include <stddef.h> #include <boost/preprocessor.hpp> #include <boost/scope_exit.hpp> #include <boost/test/unit_test.hpp> #include <tetengo/property/memory_storage.hpp> #include <tetengo/property/propertySet.h> #include <tetengo/property/property_set.hpp> #include <tetengo/property/storage.h> #include <tetengo/property/storage.hpp> namespace { const std::filesystem::path& property_set_path() { static const std::filesystem::path singleton{ "test_tetengo.property.property_set" }; return singleton; } } BOOST_AUTO_TEST_SUITE(test_tetengo) BOOST_AUTO_TEST_SUITE(property) BOOST_AUTO_TEST_SUITE(property_set) BOOST_AUTO_TEST_CASE(construction) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST(p_property_set); } } BOOST_AUTO_TEST_CASE(get_bool) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_bool("alpha"); BOOST_CHECK(!o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", &value); BOOST_TEST(!result); } { auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(nullptr, "alpha", &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, nullptr, &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", nullptr); BOOST_TEST(!result); } } BOOST_AUTO_TEST_CASE(set_bool) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_bool("alpha", false); const auto o_value = property_set_.get_bool("alpha"); BOOST_REQUIRE(o_value); BOOST_TEST(!*o_value); } { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_bool("alpha", true); const auto o_value = property_set_.get_bool("alpha"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setBool(p_property_set, "alpha", 0); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(!value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setBool(p_property_set, "alpha", 1); auto value = static_cast<int>(0); const auto result = tetengo_property_propertySet_getBool(p_property_set, "alpha", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value); } { tetengo_property_propertySet_setBool(nullptr, "alpha", 0); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setBool(p_property_set, nullptr, 0); } } BOOST_AUTO_TEST_CASE(get_uint32) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_uint32("bravo"); BOOST_CHECK(!o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "alpha", &value); BOOST_TEST(!result); } { auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(nullptr, "alpha", &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, nullptr, &value); BOOST_TEST(!result); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "alpha", nullptr); BOOST_TEST(!result); } } BOOST_AUTO_TEST_CASE(set_uint32) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_uint32("bravo", 42); const auto o_value = property_set_.get_uint32("bravo"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == 42U); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setUint32(p_property_set, "bravo", 42); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "bravo", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value == 42U); } { tetengo_property_propertySet_setUint32(nullptr, "bravo", 0); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setUint32(p_property_set, nullptr, 0); } } BOOST_AUTO_TEST_CASE(get_string) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_string("charlie"); BOOST_CHECK(!o_value); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto length = tetengo_property_propertySet_getString(p_property_set, "charlie", nullptr, 0); BOOST_TEST(length == static_cast<size_t>(-1)); } { const auto length = tetengo_property_propertySet_getString(nullptr, "charlie", nullptr, 0); BOOST_TEST(length == static_cast<size_t>(-1)); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); const auto length = tetengo_property_propertySet_getString(p_property_set, nullptr, nullptr, 0); BOOST_TEST(length == static_cast<size_t>(-1)); } } BOOST_AUTO_TEST_CASE(set_string) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_string("charlie", "hoge"); const auto o_value = property_set_.get_string("charlie"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == "hoge"); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setString(p_property_set, "charlie", "hoge"); const auto length = tetengo_property_propertySet_getString(p_property_set, "charlie", nullptr, 0); BOOST_TEST_REQUIRE(length == 4U); std::vector<char> value(length + 1, '\0'); const auto length_again = tetengo_property_propertySet_getString(p_property_set, "charlie", std::data(value), std::size(value)); BOOST_TEST_REQUIRE(length_again == length); BOOST_TEST((std::string_view{ std::data(value), length } == "hoge")); } { tetengo_property_propertySet_setString(nullptr, "charlie", "hoge"); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setString(p_property_set, nullptr, "hoge"); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setString(p_property_set, "charlie", nullptr); } } BOOST_AUTO_TEST_CASE(update) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader1 = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set1{ std::move(p_storage_loader1), property_set_path() }; auto p_storage_loader2 = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set2{ std::move(p_storage_loader2), property_set_path() }; property_set1.set_uint32("hoge.cpp", 42); property_set1.commit(); { const auto o_value = property_set2.get_uint32("hoge.cpp"); BOOST_CHECK(!o_value); } property_set2.update(); { const auto o_value = property_set2.get_uint32("hoge.cpp"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == 42U); } } { auto* const p_storage_loader1 = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set1 = tetengo_property_propertySet_create(p_storage_loader1, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set1) { tetengo_property_propertySet_destroy(p_property_set1); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set1); auto* const p_storage_loader2 = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set2 = tetengo_property_propertySet_create(p_storage_loader2, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set2) { tetengo_property_propertySet_destroy(p_property_set2); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set2); tetengo_property_propertySet_setUint32(p_property_set1, "hoge", 42); tetengo_property_propertySet_commit(p_property_set1); { auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set2, "hoge", &value); BOOST_TEST(!result); } tetengo_property_propertySet_update(p_property_set2); { auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set2, "hoge", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value == 42U); } } } BOOST_AUTO_TEST_CASE(commit) { BOOST_TEST_PASSPOINT(); { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; property_set_.set_uint32("hoge.cpp", 42); property_set_.commit(); } { auto p_storage_loader = std::make_unique<tetengo::property::memory_storage_loader>(); const tetengo::property::property_set property_set_{ std::move(p_storage_loader), property_set_path() }; const auto o_value = property_set_.get_uint32("hoge.cpp"); BOOST_REQUIRE(o_value); BOOST_TEST(*o_value == 42U); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); tetengo_property_propertySet_setUint32(p_property_set, "hoge", 42); tetengo_property_propertySet_commit(p_property_set); } { auto* const p_storage_loader = tetengo_property_storageLoader_createMemoryStorageLoader(); const auto* const p_property_set = tetengo_property_propertySet_create(p_storage_loader, property_set_path().string().c_str()); BOOST_SCOPE_EXIT(p_property_set) { tetengo_property_propertySet_destroy(p_property_set); } BOOST_SCOPE_EXIT_END; BOOST_TEST_REQUIRE(p_property_set); auto value = static_cast<::uint32_t>(0); const auto result = tetengo_property_propertySet_getUint32(p_property_set, "hoge", &value); BOOST_TEST_REQUIRE(result); BOOST_TEST(value == 42U); } } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
38.437956
121
0.664214
kaorut
cb6c2f31090c6ea33cabe18bf1054a7f947f9895
1,054
inl
C++
src/ComponentWrapper.inl
vis4rd/ecs
ef32770d93ef5a24dcf056032fc75a40077dcddc
[ "MIT" ]
null
null
null
src/ComponentWrapper.inl
vis4rd/ecs
ef32770d93ef5a24dcf056032fc75a40077dcddc
[ "MIT" ]
null
null
null
src/ComponentWrapper.inl
vis4rd/ecs
ef32770d93ef5a24dcf056032fc75a40077dcddc
[ "MIT" ]
null
null
null
namespace ecs { template <typename ComponentT> ComponentWrapper<ComponentT>::ComponentWrapper(const uint64 &entity_id) : m_component(), m_entityID(entity_id) { } template <typename ComponentT> ComponentWrapper<ComponentT>::ComponentWrapper(const ComponentT &comp) : m_component(comp), m_entityID(0) { } template <typename ComponentT> const ComponentT &ComponentWrapper<ComponentT>::operator()() const { return m_component; } template <typename ComponentT> ComponentT &ComponentWrapper<ComponentT>::operator()() { return m_component; } template <typename ComponentT> const uint64 &ComponentWrapper<ComponentT>::eID() const { return m_entityID; } template <typename ComponentT> const ComponentT &ComponentWrapper<ComponentT>::eComponent() const { return m_component; } template <typename ComponentT> ComponentT &ComponentWrapper<ComponentT>::eComponent() { return m_component; } template <typename ComponentT> void ComponentWrapper<ComponentT>::printType() const { std::cout << util::type_name_to_string<ComponentT>(); } } // namespace ecs
20.666667
71
0.781784
vis4rd
cb6c3806ae14398a4db0b47f3d8235ed4db43c00
7,313
cpp
C++
Current/773_Sliding_Puzzle/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
3
2019-09-21T16:25:44.000Z
2021-08-29T20:43:57.000Z
Current/773_Sliding_Puzzle/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
Current/773_Sliding_Puzzle/main.cpp
camelboat/LeetCode_Archive
c29d263e068752a9ad355925f326b56f672bb584
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> #include <queue> #include <string> #include <unordered_map> #include <unordered_set> using namespace std; //// 83.56% , 100.00% class Solution { public: int slidingPuzzle(vector<vector<int>>& board) { string final_state = "123450"; unordered_set<string> visited; vector<vector<int>> possible_step = { {1, 3}, {0, 2, 4}, {1, 5}, {0, 4}, {1, 3, 5}, {2, 4} }; string myboard; for (auto &row : board) { for (auto & x : row) myboard+=to_string(x); } int position_0 = 0; for (int i = 0; i < myboard.length(); ++i) { if (myboard[i] == '0') { position_0 = i; break; } } queue<tuple<int, string, int>> bas; // <position_0, board, level> bas.emplace(make_tuple(position_0, myboard, 0)); visited.insert(myboard); int tmp_position_0; string tmp_board; int cur_level; while (!bas.empty()) { tie(tmp_position_0, tmp_board, cur_level) = bas.front(); bas.pop(); if (tmp_board == final_state) return cur_level; for (auto & possible_position : possible_step[tmp_position_0]) { swap(tmp_board[possible_position], tmp_board[tmp_position_0]); if (visited.find(tmp_board) == visited.end()) { bas.emplace(make_tuple(possible_position, tmp_board, cur_level+1)); visited.insert(tmp_board); } swap(tmp_board[possible_position], tmp_board[tmp_position_0]); } } return -1; } }; //// 27.45%, 16.67% //// convert to 1-d vector //class Solution { //private: // vector<int> final_state{1,2,3,4,5,0}; // map<vector<int>, int> visited; // <board, level> // map<int, vector<int>> possible_step; // //public: // int slidingPuzzle(vector<vector<int>>& board) { // possible_step[0] = vector<int>{1,3}; // possible_step[1] = vector<int>{0,2,4}; // possible_step[2] = vector<int>{1,5}; // possible_step[3] = vector<int>{0,4}; // possible_step[4] = vector<int>{1,3,5}; // possible_step[5] = vector<int>{2,4}; // // vector<int> myboard; // for (auto &row : board) // { // for (auto & x : row) // { // myboard.emplace_back(x); // } // } // int position_0 = 0; // for (int i = 0; i < 6; ++i) // { // if (myboard[i] == 0) // { // position_0 = i; break; // } // } // // queue<pair<int, vector<int>>> bas; // bas.push(make_pair(position_0, myboard)); // visited[myboard] = 0; // while (!bas.empty()) // { // pair<int, vector<int>> cur = bas.front(); // bas.pop(); // if (cur.second == final_state) return visited[cur.second]; // vector<pair<int, vector<int>>> next_states; // for (auto & possible_position : possible_step[cur.first]) // { // vector<int> tmp = cur.second; // swap(tmp[possible_position], tmp[cur.first]); // next_states.emplace_back(make_pair(possible_position, tmp)); // } // // for (auto &next_state : next_states) // { // if (visited.find(next_state.second) == visited.end()) // { // bas.emplace(next_state); // visited[next_state.second] = visited[cur.second]+1; // } // } // } // return -1; // } //}; //// 7.2%, 16.67% //// bfs, can optimize by turning vector<vector<int>> board into string (or just one-dimensional vector) //class Solution { //private: // vector<vector<int>> move_step{{0,1},{1,0},{0,-1},{-1,0}}; // vector<vector<int>> final_state{{1,2,3},{4,5,0}}; // map<vector<vector<int>>, int> visited; // <board, level> // map<vector<int>, vector<vector<int>>> possible_step; // // vector<pair<vector<int>, vector<vector<int>>>> find_next_states(pair<vector<int>, vector<vector<int>>> &val) // { // vector<pair<vector<int>, vector<vector<int>>>> res; // for (auto & next_position : possible_step[val.first]) // { // vector<vector<int>> tmp_state = val.second; // int tmp = val.second[next_position[0]][next_position[1]]; // tmp_state[next_position[0]][next_position[1]] = 0; // tmp_state[val.first[0]][val.first[1]] = tmp; // res.emplace_back(make_pair(next_position, tmp_state)); // } // return res; // } // // static void print_board(vector<vector<int>> &board) // { // cout << board[0][0] << " " << board[0][1] << " " << board[0][2] << '\n'; // cout << board[1][0] << " " << board[1][1] << " " << board[1][2] << "\n\n"; // } // //public: // int slidingPuzzle(vector<vector<int>>& board) { // vector<int> position_0 = vector<int>(2,0); // for (int i = 0; i < board.size(); ++i) // { // for (int j = 0; j < board[0].size(); ++j) // { // if (board[i][j] == 0) // { // position_0[0] = i; position_0[1] = j; // } // } // } // // cout << "initial position at " << position_0[0] << " " << position_0[1] << '\n'; // // possible_step[{0,0}] = vector<vector<int>>{{0,1}, {1,0}}; // possible_step[{0,1}] = vector<vector<int>>{{0,0}, {0,2}, {1,1}}; // possible_step[{0,2}] = vector<vector<int>>{{0,1}, {1,2}}; // possible_step[{1,0}] = vector<vector<int>>{{0,0}, {1,1}}; // possible_step[{1,1}] = vector<vector<int>>{{0,1}, {1,0}, {1,2}}; // possible_step[{1,2}] = vector<vector<int>>{{0,2}, {1,1}}; // // queue<pair<vector<int>, vector<vector<int>>>> bas; // bas.push(make_pair(position_0, board)); // visited[board] = 0; // while (!bas.empty()) // { // pair<vector<int>, vector<vector<int>>> cur = bas.front(); // bas.pop(); //// print_board(cur.second); // if (cur.second == final_state) return visited[cur.second]; // if (visited[cur.second] > 18) return -1; // vector<pair<vector<int>, vector<vector<int>>>> next_states = find_next_states(cur); // for (auto &next_state : next_states) // { // if (visited.find(next_state.second) == visited.end()) // { // bas.emplace(next_state); // visited[next_state.second] = visited[cur.second]+1; // } // } // } // return -1; // } //}; int main() { vector<vector<int>> test_board = {{1,2,3},{4,0,5}}; // vector<vector<int>> test_board = {{3,2,4},{1,5,0}}; // vector<vector<int>> test_board = {{4,1,2},{5,0,3}}; // vector<vector<int>> test_board = {{1,2,3},{5,4,0}}; Solution test; cout << test.slidingPuzzle(test_board); return 0; }
34.013953
114
0.484069
camelboat
cb6fc702e9b73092ec3977740d469c67965ed898
21,223
cpp
C++
Source/Modio/Private/ModioSubsystem.cpp
modio/modio-ue4
f7c16749def7a33a0e3ca77f1dc077d57d0b972e
[ "MIT" ]
19
2020-10-21T16:55:52.000Z
2022-03-27T10:21:23.000Z
Source/Modio/Private/ModioSubsystem.cpp
modio/modio-ue4
f7c16749def7a33a0e3ca77f1dc077d57d0b972e
[ "MIT" ]
6
2020-10-16T09:38:30.000Z
2021-11-15T23:43:59.000Z
Source/Modio/Private/ModioSubsystem.cpp
modio/modio-ue4
f7c16749def7a33a0e3ca77f1dc077d57d0b972e
[ "MIT" ]
1
2021-02-21T15:02:24.000Z
2021-02-21T15:02:24.000Z
/* * Copyright (C) 2021 mod.io Pty Ltd. <https://mod.io> * * This file is part of the mod.io UE4 Plugin. * * Distributed under the MIT License. (See accompanying file LICENSE or * view online at <https://github.com/modio/modio-ue4/blob/main/LICENSE>) * */ #include "ModioSubsystem.h" #include "Engine/Engine.h" #include "Internal/Convert/AuthParams.h" #include "Internal/Convert/ErrorCode.h" #include "Internal/Convert/FilterParams.h" #include "Internal/Convert/InitializeOptions.h" #include "Internal/Convert/List.h" #include "Internal/Convert/ModCollectionEntry.h" #include "Internal/Convert/ModDependency.h" #include "Internal/Convert/ModInfo.h" #include "Internal/Convert/ModInfoList.h" #include "Internal/Convert/ModManagementEvent.h" #include "Internal/Convert/ModProgressInfo.h" #include "Internal/Convert/ModTagInfo.h" #include "Internal/Convert/ModTagOptions.h" #include "Internal/Convert/Rating.h" #include "Internal/Convert/ReportParams.h" #include "Internal/Convert/Terms.h" #include "Internal/Convert/User.h" #include "Internal/ModioConvert.h" #include "ModioSettings.h" #include <map> template<typename DestKey, typename DestValue, typename SourceKey, typename SourceValue> TMap<DestKey, DestValue> ToUnreal(std::map<SourceKey, SourceValue>&& OriginalMap); template<typename Dest, typename Source> TOptional<Dest> ToUnrealOptional(Source Original); template<typename Dest, typename Source> Dest ToBP(Source Original); void UModioSubsystem::Initialize(FSubsystemCollectionBase& Collection) { Super::Initialize(Collection); if (const UModioSettings* Settings = GetDefault<UModioSettings>()) { SetLogLevel(Settings->LogLevel); } ImageCache = MakeUnique<FModioImageCache>(); } void UModioSubsystem::Deinitialize() { ImageCache.Release(); Super::Deinitialize(); } bool UModioSubsystem::ShouldCreateSubsystem(UObject* Outer) const { // @todo: Add hooks here where the user can decide where the subsystem is valid return true; } void UModioSubsystem::InitializeAsync(const FModioInitializeOptions& Options, FOnErrorOnlyDelegateFast OnInitComplete) { Modio::InitializeAsync(ToModio(Options), [this, OnInitComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnInitComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_InitializeAsync(const FModioInitializeOptions& InitializeOptions, FOnErrorOnlyDelegate InitCallback) { InitializeAsync(InitializeOptions, FOnErrorOnlyDelegateFast::CreateLambda( [InitCallback](FModioErrorCode ec) { InitCallback.ExecuteIfBound(ec); })); } void UModioSubsystem::ListAllModsAsync(const FModioFilterParams& Filter, FOnListAllModsDelegateFast Callback) { Modio::ListAllModsAsync(ToModio(Filter), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModInfoList> Result) { Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModInfoList>(Result)); }); } void UModioSubsystem::SubscribeToModAsync(FModioModID ModToSubscribeTo, FOnErrorOnlyDelegateFast OnSubscribeComplete) { Modio::SubscribeToModAsync(ToModio(ModToSubscribeTo), [this, OnSubscribeComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnSubscribeComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::UnsubscribeFromModAsync(FModioModID ModToUnsubscribeFrom, FOnErrorOnlyDelegateFast OnUnsubscribeComplete) { Modio::UnsubscribeFromModAsync(ToModio(ModToUnsubscribeFrom), [this, OnUnsubscribeComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnUnsubscribeComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::FetchExternalUpdatesAsync(FOnErrorOnlyDelegateFast OnFetchDone) { Modio::FetchExternalUpdatesAsync([this, OnFetchDone](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnFetchDone.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::EnableModManagement(FOnModManagementDelegateFast Callback) { Modio::EnableModManagement([this, Callback](Modio::ModManagementEvent Event) { // @todo: For some smarter caching, look at the event and see if we should invalidate the cache InvalidateUserInstallationCache(); Callback.ExecuteIfBound(ToUnreal(Event)); }); } void UModioSubsystem::K2_ListAllModsAsync(const FModioFilterParams& Filter, FOnListAllModsDelegate Callback) { ListAllModsAsync(Filter, FOnListAllModsDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModInfoList> ModList) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModInfoList>(ModList)); })); } void UModioSubsystem::K2_SubscribeToModAsync(FModioModID ModToSubscribeTo, FOnErrorOnlyDelegate OnSubscribeComplete) { SubscribeToModAsync(ModToSubscribeTo, FOnErrorOnlyDelegateFast::CreateLambda( [OnSubscribeComplete](FModioErrorCode ec) { OnSubscribeComplete.ExecuteIfBound(ec); })); } void UModioSubsystem::K2_UnsubscribeFromModAsync(FModioModID ModToUnsubscribeFrom, FOnErrorOnlyDelegate OnUnsubscribeComplete) { UnsubscribeFromModAsync(ModToUnsubscribeFrom, FOnErrorOnlyDelegateFast::CreateLambda([OnUnsubscribeComplete](FModioErrorCode ec) { OnUnsubscribeComplete.ExecuteIfBound(ec); })); } void UModioSubsystem::K2_FetchExternalUpdatesAsync(FOnErrorOnlyDelegate OnFetchDone) { FetchExternalUpdatesAsync( FOnErrorOnlyDelegateFast::CreateLambda([OnFetchDone](FModioErrorCode ec) { OnFetchDone.ExecuteIfBound(ec); })); } void UModioSubsystem::K2_EnableModManagement(FOnModManagementDelegate Callback) { EnableModManagement(FOnModManagementDelegateFast::CreateLambda( [Callback](FModioModManagementEvent Event) { Callback.ExecuteIfBound(Event); })); } void UModioSubsystem::DisableModManagement() { Modio::DisableModManagement(); } void UModioSubsystem::ShutdownAsync(FOnErrorOnlyDelegateFast OnShutdownComplete) { Modio::ShutdownAsync([this, OnShutdownComplete](Modio::ErrorCode ec) { InvalidateUserSubscriptionCache(); OnShutdownComplete.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_ShutdownAsync(FOnErrorOnlyDelegate OnShutdownComplete) { ShutdownAsync(FOnErrorOnlyDelegateFast::CreateLambda( [OnShutdownComplete](FModioErrorCode ec) { OnShutdownComplete.ExecuteIfBound(ec); })); } void UModioSubsystem::RunPendingHandlers() { InvalidateUserSubscriptionCache(); Modio::RunPendingHandlers(); } void UModioSubsystem::SetLogLevel(EModioLogLevel UnrealLogLevel) { Modio::SetLogLevel(ToModio(UnrealLogLevel)); } bool UModioSubsystem::IsModManagementBusy() { return Modio::IsModManagementBusy(); } TOptional<FModioModProgressInfo> UModioSubsystem::QueryCurrentModUpdate() { return ToUnrealOptional<FModioModProgressInfo>(Modio::QueryCurrentModUpdate()); } FModioOptionalModProgressInfo UModioSubsystem::K2_QueryCurrentModUpdate() { return ToBP<FModioOptionalModProgressInfo>(QueryCurrentModUpdate()); } const TMap<FModioModID, FModioModCollectionEntry>& UModioSubsystem::QueryUserSubscriptions() { if (!CachedUserSubscriptions) { CachedUserSubscriptions = ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QueryUserSubscriptions()); } return CachedUserSubscriptions.GetValue(); } const TMap<FModioModID, FModioModCollectionEntry>& UModioSubsystem::QueryUserInstallations(bool bIncludeOutdatedMods) { TOptional<TMap<FModioModID, FModioModCollectionEntry>>& UserInstallation = bIncludeOutdatedMods ? CachedUserInstallationWithOutdatedMods : CachedUserInstallationWithoutOutdatedMods; if (!UserInstallation) { UserInstallation = ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QueryUserInstallations(bIncludeOutdatedMods)); } return UserInstallation.GetValue(); } TOptional<FModioUser> UModioSubsystem::QueryUserProfile() { return ToUnrealOptional<FModioUser>(Modio::QueryUserProfile()); } FModioOptionalUser UModioSubsystem::K2_QueryUserProfile() { return ToBP<FModioOptionalUser>(QueryUserProfile()); } void UModioSubsystem::GetModInfoAsync(FModioModID ModId, FOnGetModInfoDelegateFast Callback) { Modio::GetModInfoAsync(ToModio(ModId), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModInfo> ModInfo) { Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModInfo>(ModInfo)); }); } void UModioSubsystem::K2_GetModInfoAsync(FModioModID ModId, FOnGetModInfoDelegate Callback) { GetModInfoAsync(ModId, FOnGetModInfoDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModInfo> ModInfo) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModInfo>(ModInfo)); })); } void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioAvatarSize AvatarSize, FOnGetMediaDelegateFast Callback) { Modio::GetModMediaAsync(ToModio(ModId), ToModio(AvatarSize), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template // function returning type T so we can be explicit about the expected type if (Path) { FModioImage Out; Out.ImagePath = ToUnreal(Path.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioGallerySize GallerySize, int32 Index, FOnGetMediaDelegateFast Callback) { Modio::GetModMediaAsync(ToModio(ModId), ToModio(GallerySize), Index, [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template // function returning type T so we can be explicit about the expected type if (Path) { FModioImage Out; Out.ImagePath = ToUnreal(Path.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::GetModMediaAsync(FModioModID ModId, EModioLogoSize LogoSize, FOnGetMediaDelegateFast Callback) { Modio::GetModMediaAsync(ToModio(ModId), ToModio(LogoSize), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Path) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a template // function returning type T so we can be explicit about the expected type if (Path) { FModioImage Out; Out.ImagePath = ToUnreal(Path.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::K2_GetModMediaAvatarAsync(FModioModID ModId, EModioAvatarSize AvatarSize, FOnGetMediaDelegate Callback) { GetModMediaAsync( ModId, AvatarSize, FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media)); })); } void UModioSubsystem::K2_GetModMediaGalleryImageAsync(FModioModID ModId, EModioGallerySize GallerySize, int32 Index, FOnGetMediaDelegate Callback) { GetModMediaAsync( ModId, GallerySize, Index, FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media)); })); } void UModioSubsystem::K2_GetModMediaLogoAsync(FModioModID ModId, EModioLogoSize LogoSize, FOnGetMediaDelegate Callback) { GetModMediaAsync( ModId, LogoSize, FOnGetMediaDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioImage> Media) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(Media)); })); } void UModioSubsystem::GetModTagOptionsAsync(FOnGetModTagOptionsDelegateFast Callback) { if (CachedModTags) { Callback.ExecuteIfBound({}, CachedModTags); return; } Modio::GetModTagOptionsAsync( [this, Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModTagOptions> ModTagOptions) { CachedModTags = ToUnrealOptional<FModioModTagOptions>(ModTagOptions); Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioModTagOptions>(ModTagOptions)); }); } void UModioSubsystem::K2_GetModTagOptionsAsync(FOnGetModTagOptionsDelegate Callback) { GetModTagOptionsAsync(FOnGetModTagOptionsDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModTagOptions> ModTagOptions) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalModTagOptions>(ModTagOptions)); })); } void UModioSubsystem::RequestEmailAuthCodeAsync(const FModioEmailAddress& EmailAddress, FOnErrorOnlyDelegateFast Callback) { Modio::RequestEmailAuthCodeAsync(ToModio(EmailAddress), [Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_RequestEmailAuthCodeAsync(const FModioEmailAddress& EmailAddress, FOnErrorOnlyDelegate Callback) { RequestEmailAuthCodeAsync(EmailAddress, FOnErrorOnlyDelegateFast::CreateLambda( [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::AuthenticateUserEmailAsync(const FModioEmailAuthCode& AuthenticationCode, FOnErrorOnlyDelegateFast Callback) { Modio::AuthenticateUserEmailAsync(ToModio(AuthenticationCode), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_AuthenticateUserEmailAsync(const FModioEmailAuthCode& AuthenticationCode, FOnErrorOnlyDelegate Callback) { AuthenticateUserEmailAsync( AuthenticationCode, FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::AuthenticateUserExternalAsync(const FModioAuthenticationParams& User, EModioAuthenticationProvider Provider, FOnErrorOnlyDelegateFast Callback) { Modio::AuthenticateUserExternalAsync(ToModio(User), ToModio(Provider), [Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_AuthenticateUserExternalAsync(const FModioAuthenticationParams& User, EModioAuthenticationProvider Provider, FOnErrorOnlyDelegate Callback) { AuthenticateUserExternalAsync( User, Provider, FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::GetTermsOfUseAsync(EModioAuthenticationProvider Provider, EModioLanguage Locale, FOnGetTermsOfUseDelegateFast Callback) { Modio::GetTermsOfUseAsync(ToModio(Provider), ToModio(Locale), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::Terms> Terms) { Callback.ExecuteIfBound(ec, ToUnrealOptional<FModioTerms>(Terms)); }); } void UModioSubsystem::K2_GetTermsOfUseAsync(EModioAuthenticationProvider Provider, EModioLanguage Locale, FOnGetTermsOfUseDelegate Callback) { GetTermsOfUseAsync( Provider, Locale, FOnGetTermsOfUseDelegateFast::CreateLambda([Callback](FModioErrorCode ec, TOptional<FModioTerms> Terms) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalTerms>(Terms)); })); } void UModioSubsystem::ClearUserDataAsync(FOnErrorOnlyDelegateFast Callback) { Modio::ClearUserDataAsync([Callback](Modio::ErrorCode ec) { Callback.ExecuteIfBound(ToUnreal(ec)); }); } void UModioSubsystem::K2_ClearUserDataAsync(FOnErrorOnlyDelegate Callback) { ClearUserDataAsync( FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::GetUserMediaAsync(EModioAvatarSize AvatarSize, FOnGetMediaDelegateFast Callback) { Modio::GetUserMediaAsync(ToModio(AvatarSize), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::filesystem::path> Media) { // Manually calling ToUnreal on the path and assigning to the member of FModioImage // because we already have a Modio::filesystem::path -> FString overload of ToUnreal // TODO: @modio-ue4 Potentially refactor ToUnreal(Modio::filesystem::path) as a // template function returning type T so we can be explicit about the expected type if (Media) { FModioImage Out; Out.ImagePath = ToUnreal(Media.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } void UModioSubsystem::K2_GetUserMediaAvatarAsync(EModioAvatarSize AvatarSize, FOnGetMediaDelegate Callback) { GetUserMediaAsync(AvatarSize, FOnGetMediaDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioImage> ModioMedia) { Callback.ExecuteIfBound(ec, ToBP<FModioOptionalImage>(ModioMedia)); })); } void UModioSubsystem::InvalidateUserSubscriptionCache() { CachedUserSubscriptions.Reset(); } void UModioSubsystem::InvalidateUserInstallationCache() { CachedUserInstallationWithOutdatedMods.Reset(); CachedUserInstallationWithoutOutdatedMods.Reset(); } FModioImageCache& UModioSubsystem::GetImageCache() const { return *ImageCache; } TArray<FModioValidationError> UModioSubsystem::GetLastValidationError() { TArray<FModioValidationError> Errors; for (const auto& Error : Modio::GetLastValidationError()) { Errors.Add(FModioValidationError {ToUnreal(Error.Field), ToUnreal(Error.Error)}); } return Errors; } TMap<FModioModID, FModioModCollectionEntry> UModioSubsystem::QuerySystemInstallations() { return ToUnreal<FModioModID, FModioModCollectionEntry>(Modio::QuerySystemInstallations()); } void UModioSubsystem::ForceUninstallModAsync(FModioModID ModToRemove, FOnErrorOnlyDelegate Callback) { Modio::ForceUninstallModAsync(ToModio(ModToRemove), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::SubmitModRatingAsync(FModioModID Mod, EModioRating Rating, FOnErrorOnlyDelegateFast Callback) { Modio::SubmitModRatingAsync(ToModio(Mod), ToModio(Rating), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_SubmitModRatingAsync(FModioModID Mod, EModioRating Rating, FOnErrorOnlyDelegate Callback) { SubmitModRatingAsync(Mod, Rating, FOnErrorOnlyDelegateFast::CreateLambda([Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::ReportContentAsync(FModioReportParams Report, FOnErrorOnlyDelegateFast Callback) { Modio::ReportContentAsync(ToModio(Report), [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); }); } void UModioSubsystem::K2_ReportContentAsync(FModioReportParams Report, FOnErrorOnlyDelegate Callback) { ReportContentAsync(Report, FOnErrorOnlyDelegateFast::CreateLambda( [Callback](FModioErrorCode ec) { Callback.ExecuteIfBound(ec); })); } void UModioSubsystem::GetModDependenciesAsync(FModioModID ModID, FOnGetModDependenciesDelegateFast Callback) { Modio::GetModDependenciesAsync( ToModio(ModID), [Callback](Modio::ErrorCode ec, Modio::Optional<Modio::ModDependencyList> Dependencies) { if (Dependencies) { FModioModDependencyList Out; Out.InternalList = ToUnreal<FModioModDependency>(Dependencies->GetRawList()); Out.PagedResult = FModioPagedResult(Dependencies.value()); Callback.ExecuteIfBound(ec, Out); } else { Callback.ExecuteIfBound(ec, {}); } }); } MODIO_API void UModioSubsystem::K2_GetModDependenciesAsync(FModioModID ModID, FOnGetModDependenciesDelegate Callback) { GetModDependenciesAsync(ModID, FOnGetModDependenciesDelegateFast::CreateLambda( [Callback](FModioErrorCode ec, TOptional<FModioModDependencyList> Dependencies) { Callback.ExecuteIfBound( ec, FModioOptionalModDependencyList(MoveTempIfPossible(Dependencies))); })); } /// File scope implementations #pragma region Implementation template<typename DestKey, typename DestValue, typename SourceKey, typename SourceValue> TMap<DestKey, DestValue> ToUnreal(std::map<SourceKey, SourceValue>&& OriginalMap) { TMap<DestKey, DestValue> Result; Result.Reserve(OriginalMap.size()); for (auto& It : OriginalMap) { Result.Add(ToUnreal(It.first), ToUnreal(It.second)); } return Result; } template<typename Dest, typename Source> TOptional<Dest> ToUnrealOptional(Source Original) { TOptional<Dest> DestinationOptional = {}; if (Original) { DestinationOptional = ToUnreal(Original.value()); } return DestinationOptional; } template<typename Dest, typename Source> Dest ToBP(Source Original) { Dest Result = {MoveTempIfPossible(Original)}; return Result; } #pragma endregion
35.195688
120
0.766433
modio
cb6fdd5a0491cc8422de48d74f399a9c03b6a21c
10,021
hpp
C++
fon9/Subr.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
21
2019-01-29T14:41:46.000Z
2022-03-11T00:22:56.000Z
fon9/Subr.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
null
null
null
fon9/Subr.hpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
9
2019-01-27T14:19:33.000Z
2022-03-11T06:18:24.000Z
/// \file fon9/Subr.hpp /// \author [email protected] #ifndef __fon9_Subr_hpp__ #define __fon9_Subr_hpp__ #include "fon9/DummyMutex.hpp" #include "fon9/MustLock.hpp" #include "fon9/SortedVector.hpp" namespace fon9 { /// Subject/Subscriber 註冊取得的 ID, 用來取消註冊時使用. /// - 此ID的編碼方式為: 在新的訂閱者註冊時, 為目前最後一個ID+1, 如果現在沒有任何訂閱者則使用1. /// - 所以如果最後一個訂閱者為 0xffffffff... 則無法再註冊新的訂閱者, 此時註冊就會失敗傳回 nullptr using SubConn = struct SubId*; fon9_WARN_DISABLE_PADDING; /// 提供給 Subject 儲存訂閱者的容器. template <class SubscriberT> class SubrMap : private SortedVector<SubConn, SubscriberT> { using base = SortedVector<SubConn, SubscriberT>; unsigned FirstReserve_; public: using typename base::size_type; using typename base::iterator; using typename base::difference_type; using typename base::value_type; /// \param firstReserve 當加入第一個元素時的預分配資料量,0表示使用預設值. /// - 第一個 subr 註冊時, 表示此 Subject 是讓人感興趣的. /// - 可以預期, 接下來可能還會有別人訂閱. /// - 預先分配 **一小塊** 可能的空間, 可大幅改進後續訂閱者的處理速度. /// - 在 x64 系統裡: 如果 SubscriberT=Object*; 加上 SubId; 每個 T 占用 sizeof(void*)*2 = 16; /// - 所以如果 firstReserve=64, 則加入第一個 subr 時大約占用 16 bytes * 64 items = 1024 bytes. SubrMap(unsigned firstReserve) : FirstReserve_{firstReserve} { } using base::begin; using base::end; using base::erase; using base::size; using base::empty; using base::sindex; using base::clear; /// 使用 SortedVector::find(SubConn id) 進行二元搜尋. iterator find(SubConn id) { return base::find(id); } /// 使用 std::find(subr) 線性搜尋, subr 必須提供 `==` 操作. template <class SubscriberT2> iterator find(const SubscriberT2& subr) { return std::find_if(this->begin(), this->end(), [&subr](const value_type& i) { return(i.second == subr); }); } /// 移除全部相同的 subr, 傳回移除的數量. template <class SubscriberT2> size_type remove(const SubscriberT2& subr, size_type ibegin, size_type iend) { return this->remove_if(ibegin, iend, [&subr](const value_type& i) -> bool { return(i.second == subr); }); } /// 在尾端建立一個 Subscriber. /// \return 傳回nullptr表示失敗, 請參閱 \ref SubConn template <class... ArgsT> SubConn emplace_back(ArgsT&&... args) { SubConn id; if (fon9_LIKELY(!this->empty())) { SubConn lastid = this->back().first; id = reinterpret_cast<SubConn>(reinterpret_cast<uintptr_t>(lastid) + 1); if (fon9_UNLIKELY(id < lastid)) return nullptr; } else { id = reinterpret_cast<SubConn>(1); if (this->FirstReserve_) this->reserve(this->FirstReserve_); } base::emplace_back(id, std::forward<ArgsT>(args)...); return id; } }; /// 事件訂閱機制: 訂閱事件的主題. /// \tparam SubscriberT 訂閱者型別, 必須配合 Publish(args...) 的參數, 提供 SubscriberT(args...) 呼叫. /// 針對 thread safe 的議題, 可考慮 std::function + shared_ptr + weak_ptr. /// \tparam MutexT 預設使用 std::recursive_mutex: 允許在收到訊息的時候, 在同一個 thread 直接取消訂閱! /// \tparam ContainerT 儲存訂閱者的容器: 預設使用 SubrMap; 請參考 SubrMap 的介面. template < class SubscriberT , class MutexT = std::recursive_mutex , template <class T/*SubscriberT*/> class ContainerT = SubrMap > class Subject { fon9_NON_COPY_NON_MOVE(Subject); using ContainerImpl = ContainerT<SubscriberT>; using Container = MustLock<ContainerImpl, MutexT>; using Locker = typename Container::Locker; using ConstLocker = typename Container::ConstLocker; using iterator = typename ContainerImpl::iterator; using size_type = typename ContainerImpl::size_type; using difference_type = typename ContainerImpl::difference_type; Container Subrs_; size_type NextEmitIdx_{}; size_type EraseIterator(Locker& subrs, iterator ifind) { if (ifind == subrs->end()) return 0; size_type idx = static_cast<size_type>(ifind - subrs->begin()); if (idx < this->NextEmitIdx_) --this->NextEmitIdx_; subrs->erase(ifind); return 1; } public: using Subscriber = SubscriberT; /// \copydoc SubrMap::SubrMap explicit Subject(unsigned firstReserve = 32) : Subrs_{firstReserve} { } /// 直接在尾端註冊一個新的訂閱者. /// - 註冊時不會檢查是否已經有相同訂閱者, 也就是: 同一個訂閱者, 可以註冊多次, 此時同一次發行流程, 會收到多次訂閱的事件. /// - 使用 SubscriberT{args...} 直接在尾端建立訂閱者. /// - 如果 SubscriberT 不支援 `operator==(const SubscriberT& subr)`, 則傳回值是唯一可以取消訂閱的依據. /// /// \return 傳回值是取消訂閱時的依據, 傳回 nullptr 表示無法註冊, 原因請參閱 \ref SubConn 的說明. template <class... ArgsT> SubConn Subscribe(ArgsT&&... args) { Locker subrs(this->Subrs_); return subrs->emplace_back(std::forward<ArgsT>(args)...); } /// 訂閱時, 在返回前就先設定好 conn, 避免底下情況: /// - conn = subj.Subscribe(...); 在返回後, 設定 conn 之前, /// 就在其他 thread 觸發了 subj.Publish(); /// 而在訂閱者處理時用到了 conn, 此時的 conn 不正確. template <class... ArgsT> void Subscribe(SubConn* conn, ArgsT&&... args) { Locker subrs(this->Subrs_); *conn = subrs->emplace_back(std::forward<ArgsT>(args)...); } /// 取消訂閱. /// - 若 MutexT = std::recursive_mutex 則: 可以在收到訊息的時候, 在同一個 thread 之中取消訂閱! /// - 若 MutexT = std::mutex 則: 在收到訊息的時候, 在同一個 thread 之中取消訂閱: 會死結! /// /// \param connection 是 Subscribe() 的傳回值. /// \return 傳回實際移除的數量: 0 or 1 size_type Unsubscribe(SubConn connection) { if (!connection) return 0; Locker subrs(this->Subrs_); return this->EraseIterator(subrs, subrs->find(connection)); } /// 取消訂閱, 並清除 *connection; size_type Unsubscribe(SubConn* connection) { if (SubConn c = *connection) { *connection = SubConn{}; return this->Unsubscribe(c); } return 0; } /// 取消訂閱, 並將 Subscriber 取出. bool MoveOutSubscriber(SubConn connection, SubscriberT& subr) { return this->MoveOutSubscriber(&connection, subr); } bool MoveOutSubscriber(SubConn* pConnection, SubscriberT& subr) { Locker subrs(this->Subrs_); auto ifind = subrs->find(*pConnection); *pConnection = SubConn{}; if (ifind == subrs->end()) return false; subr = std::move(ifind->second); this->EraseIterator(subrs, ifind); return true; } /// 取消訂閱. /// \param subr SubscriberT 必須支援: bool operator==(const SubscriberT&) const; /// \return 傳回實際移除的數量: 0 or 1 size_type Unsubscribe(const SubscriberT& subr) { Locker subrs(this->Subrs_); return this->EraseIterator(subrs, subrs->find(subr)); } size_type UnsubscribeAll(const SubscriberT& subr) { Locker subrs(this->Subrs_); size_type count = subrs->remove(subr, this->NextEmitIdx_, subrs->size()); if (this->NextEmitIdx_ > 0) { if (size_type count2 = subrs->remove(subr, 0, this->NextEmitIdx_)) { this->NextEmitIdx_ -= count2; count += count2; } } return count; } /// - 在發行訊息的過程, 會 **全程鎖住容器**. /// - 這裡會呼叫 subr(std::forward<ArgsT>(args)...); /// - 在收到發行訊息時: /// - 若 MutexT = std::mutex; 則禁止在同一個 thread: 重複發行 or 取消註冊 or 新增註冊. 如果您這樣做, 會立即進入鎖死狀態! /// - 若 MutexT = std::recursive_mutex: /// - 可允許: 重複發行 or 取消註冊 or 新增註冊. /// - 請避免: 在重複發行時, 又取消註冊. 因為原本的發行流程, 可能會有訂閱者遺漏訊息, 例: /// - Pub(msgA): Subr1(idx=0), Subr2(idx=1), Subr3(idx=2), Subr4(idx=3) /// - 在 Subr2 收到 msgA 時(msgA.NextIdx=2), Pub(msgB), 當 Subr1 收到 msgB 時, 取消註冊 Subr1. /// - 此時剩下 Subr2(idx=0), Subr3(idx=1), Subr4(idx=2) /// - 接下來 msgB 的流程: Subr2, Subr3, Subr4; msgB 發行結束. /// - 返回 msgA(msgA.NextIdx=2) 繼續流程: Subr4; **此時遺漏了 Subr3** template <class... ArgsT> void Publish(ArgsT&&... args) { struct Combiner { bool operator()(SubscriberT& subr, ArgsT&&... args) { subr(std::forward<ArgsT>(args)...); return true; } } combiner; Combine(combiner, std::forward<ArgsT>(args)...); } /// 透過 combiner 合併訊息發行結果. /// 若 combiner(SubscriberT& subr, ArgsT&&... args) 傳回 false 則中斷發行. template <class CombinerT, class... ArgsT> void Combine(CombinerT& combiner, ArgsT&&... args) { Locker subrs(this->Subrs_); struct ResetIdx { size_type prv; size_type* idx; ResetIdx(size_type* i) : prv{*i}, idx{i} { *i = 0; } ~ResetIdx() { *idx = prv; } } resetIdx{&this->NextEmitIdx_}; while (this->NextEmitIdx_ < subrs->size()) { if (!combiner(subrs->sindex(this->NextEmitIdx_++).second, std::forward<ArgsT>(args)...)) break; } } /// 是否沒有訂閱者? /// 若 MutexT = std::mutex 則: 在收到訊息的時候, 在同一個 thread 之中呼叫: 會死結! bool IsEmpty() const { ConstLocker subrs(this->Subrs_); return subrs->empty(); } /// 訂閱者數量. size_type GetSubscriberCount() const { ConstLocker subrs(this->Subrs_); return subrs->size(); } void Clear() { Locker subrs(this->Subrs_); return subrs->clear(); } /// 鎖定後就暫時不會發行訊息. ConstLocker Lock() const { return ConstLocker{this->Subrs_}; } }; /// 不支援 thread safe 的 Subject: 使用 fon9::DummyMutex. template <class SubscriberT, template <class T> class SubrContainerT = SubrMap> using UnsafeSubject = Subject<SubscriberT, DummyMutex, SubrContainerT>; /// - 輔助 Subject 提供 Obj* 當作 Subscriber 使用. /// \code /// struct CbObj { /// virtual void operator()() = 0; /// }; /// using Subr = fon9::ObjCallback<CbObj>; /// using Subj = fon9::Subject<Subr>; /// \endcode /// - 提供 Obj* 呼叫 Obj::operator() 的包裝. /// - 提供 operator==(); operator!=() 判斷是否指向同一個 Obj template <class Obj> struct ObjCallback { Obj* Obj_; ObjCallback(Obj* obj) : Obj_{obj} { } bool operator==(const ObjCallback& r) const { return this->Obj_ == r.Obj_; } bool operator!=(const ObjCallback& r) const { return this->Obj_ == r.Obj_; } template <class... ArgsT> auto operator()(ArgsT&&... args) const -> decltype((*this->Obj_)(std::forward<ArgsT>(args)...)) { return (*this->Obj_)(std::forward<ArgsT>(args)...); } }; fon9_WARN_POP; } // namespaces #endif//__fon9_Subr_hpp__
34.67474
100
0.621295
fonwin
cb709ede5c4fee21b5074dd10ff4cdcc55641c39
707
cpp
C++
src/core/EConfigure.cpp
boselor/slc
a1fd53da3f180c4062cac7083b444b438d777d26
[ "Apache-2.0" ]
null
null
null
src/core/EConfigure.cpp
boselor/slc
a1fd53da3f180c4062cac7083b444b438d777d26
[ "Apache-2.0" ]
null
null
null
src/core/EConfigure.cpp
boselor/slc
a1fd53da3f180c4062cac7083b444b438d777d26
[ "Apache-2.0" ]
null
null
null
#include <core/EConfigure.hpp> #include <fstream> namespace slc { EConfigure::EConfigure() {} EConfigure::~EConfigure() {} bool EConfigure::loadFile(EString file) { if(file.isEmpty()) return false; std::ifstream reader; reader.open(file.toStdChars(),std::ios::ate); if(!reader.is_open()) return false; std::string s; while(getline(reader,s)) { EString::format("%s",s.c_str()); } reader.close(); return true; } EString EConfigure::readString(EString path, const EString val) { if(path.isEmpty()) return val; EString res; return res; } }
20.794118
69
0.547383
boselor
cb7bbcbf7ca44ffee5ac08be4646feeebe0ba463
6,725
cpp
C++
lib/AFE-I2C-Scanner/AFE-I2C-Scanner.cpp
tschaban/AFE-Firmware
b2c7c76e0f2efb6d8e02b81a5d08e39e30016502
[ "MIT" ]
36
2017-06-05T21:27:44.000Z
2022-02-13T21:04:04.000Z
lib/AFE-I2C-Scanner/AFE-I2C-Scanner.cpp
tschaban/AFE-Firmware
b2c7c76e0f2efb6d8e02b81a5d08e39e30016502
[ "MIT" ]
661
2017-05-28T12:01:53.000Z
2022-02-13T08:51:25.000Z
lib/AFE-I2C-Scanner/AFE-I2C-Scanner.cpp
tschaban/AFE-Firmware
b2c7c76e0f2efb6d8e02b81a5d08e39e30016502
[ "MIT" ]
46
2017-12-12T21:11:32.000Z
2022-02-10T21:52:26.000Z
/* AFE Firmware for smarthome devices, More info: https://afe.smartnydom.pl/ */ #include "AFE-I2C-Scanner.h" #ifdef AFE_CONFIG_HARDWARE_I2C AFEI2CScanner::AFEI2CScanner() {}; void AFEI2CScanner::begin(TwoWire *_WirePort) { AFEDataAccess Data; WirePort = _WirePort; } #ifdef DEBUG void AFEI2CScanner::scanAll() { uint8_t numberOfDeficesFound = 0; boolean searchStatus; Serial << endl << endl << F("------------------ I2C Scanner ------------------"); for (uint8_t address = 1; address < 127; address++) { searchStatus = scan(address); if (searchStatus) numberOfDeficesFound++; } if (numberOfDeficesFound == 0) { Serial << endl << F("No I2C devices found"); } else { Serial << endl << F("Scanning completed"); } Serial << endl << F("---------------------------------------------------") << endl; } #endif boolean AFEI2CScanner::scan(byte address) { byte status; WirePort->beginTransmission(address); status = WirePort->endTransmission(); if (status == 0) { #ifdef DEBUG Serial << endl << F(" - Sensor Found [0x"); if (address < 16) { Serial << F("0"); } Serial << _HEX(address) << F("] : ") << getName(address); #endif return true; } else { return false; } } const char *AFEI2CScanner::getName(byte deviceAddress) { /* WARN: Description can't be longer than 70chars, used by addDeviceI2CAddressSelectionItem in AFE-Site-Gnerator.h */ if (deviceAddress == 0x00) return "AS3935"; else if (deviceAddress == 0x01) return "AS3935"; else if (deviceAddress == 0x02) return "AS3935"; else if (deviceAddress == 0x03) return "AS3935"; else if (deviceAddress == 0x0A) return "SGTL5000"; else if (deviceAddress == 0x0B) return "SMBusBattery?"; else if (deviceAddress == 0x0C) return "AK8963"; else if (deviceAddress == 0x10) return "CS4272"; else if (deviceAddress == 0x11) return "Si4713"; else if (deviceAddress == 0x13) return "VCNL4000,AK4558"; else if (deviceAddress == 0x18) return "LIS331DLH"; else if (deviceAddress == 0x19) return "LSM303,LIS331DLH"; else if (deviceAddress == 0x1A) return "WM8731"; else if (deviceAddress == 0x1C) return "LIS3MDL"; else if (deviceAddress == 0x1D) return "LSM303D,LSM9DS0,ADXL345,MMA7455L,LSM9DS1,LIS3DSH"; else if (deviceAddress == 0x1E) return "LSM303D,HMC5883L,FXOS8700,LIS3DSH"; else if (deviceAddress == 0x20) //return "MCP23017,MCP23008,PCF8574,FXAS21002,SoilMoisture"; return "MCP23017"; else if (deviceAddress == 0x21) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x22) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x23) return "BH1750, MCP23017"; //return "BH1750,MCP23017,MCP23008,PCF8574"; else if (deviceAddress == 0x24) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017,PN532"; else if (deviceAddress == 0x25) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x26) //return "MCP23017,MCP23008,PCF8574"; return "MCP23017"; else if (deviceAddress == 0x27) //return "MCP23017,MCP23008,PCF8574,LCD16x2,DigoleDisplay"; return "MCP23017"; else if (deviceAddress == 0x28) return "BNO055,EM7180,CAP1188"; else if (deviceAddress == 0x29) return "TSL2561,VL6180,TSL2561,TSL2591,BNO055,CAP1188"; else if (deviceAddress == 0x2A) return "SGTL5000,CAP1188"; else if (deviceAddress == 0x2B) return "CAP1188"; else if (deviceAddress == 0x2C) return "MCP44XX ePot"; else if (deviceAddress == 0x2D) return "MCP44XX ePot"; else if (deviceAddress == 0x2E) return "MCP44XX ePot"; else if (deviceAddress == 0x2F) return "MCP44XX ePot"; else if (deviceAddress == 0x38) return "RA8875,FT6206"; else if (deviceAddress == 0x39) return "TSL2561"; else if (deviceAddress == 0x3C) return "SSD1306,DigisparkOLED"; else if (deviceAddress == 0x3D) return "SSD1306"; else if (deviceAddress == 0x40) return "PCA9685,Si7021"; else if (deviceAddress == 0x41) return "STMPE610,PCA9685"; else if (deviceAddress == 0x42) return "PCA9685"; else if (deviceAddress == 0x43) return "PCA9685"; else if (deviceAddress == 0x44) return "PCA9685"; else if (deviceAddress == 0x45) return "PCA9685"; else if (deviceAddress == 0x46) return "PCA9685"; else if (deviceAddress == 0x47) return "PCA9685"; else if (deviceAddress == 0x48) return "ADS1115,PN532,TMP102,PCF8591"; else if (deviceAddress == 0x49) return "ADS1115,TSL2561,PCF8591"; else if (deviceAddress == 0x4A) return "ADS1115"; else if (deviceAddress == 0x4B) return "ADS1115,TMP102"; else if (deviceAddress == 0x50) return "EEPROM"; else if (deviceAddress == 0x51) return "EEPROM"; else if (deviceAddress == 0x52) return "Nunchuk,EEPROM"; else if (deviceAddress == 0x53) return "ADXL345,EEPROM"; else if (deviceAddress == 0x54) return "EEPROM"; else if (deviceAddress == 0x55) return "EEPROM"; else if (deviceAddress == 0x56) return "EEPROM"; else if (deviceAddress == 0x57) return "EEPROM"; else if (deviceAddress == 0x58) return "TPA2016,MAX21100"; else if (deviceAddress == 0x5A) return "MPR121"; else if (deviceAddress == 0x5C) return "BH1750"; else if (deviceAddress == 0x60) return "MPL3115,MCP4725,MCP4728,TEA5767,Si5351"; else if (deviceAddress == 0x61) return "MCP4725,AtlasEzoDO"; else if (deviceAddress == 0x62) return "LidarLite,MCP4725,AtlasEzoORP"; else if (deviceAddress == 0x63) return "MCP4725,AtlasEzoPH"; else if (deviceAddress == 0x64) return "AtlasEzoEC"; else if (deviceAddress == 0x66) return "AtlasEzoRTD"; else if (deviceAddress == 0x68) return "DS1307,DS3231,MPU6050,MPU9050,MPU9250,ITG3200,ITG3701," "LSM9DS0,L3G4200D"; else if (deviceAddress == 0x69) return "MPU6050,MPU9050,MPU9250,ITG3701,L3G4200D"; else if (deviceAddress == 0x6A) return "LSM9DS1"; else if (deviceAddress == 0x6B) return "LSM9DS0"; else if (deviceAddress == 0x70) return "AdafruitLED"; else if (deviceAddress == 0x71) return "SFE7SEG,AdafruitLED"; else if (deviceAddress == 0x72) return "AdafruitLED"; else if (deviceAddress == 0x73) return "AdafruitLED"; else if (deviceAddress == 0x76) return "BMx280"; //return "BMx280,MS5607,MS5611,MS5637"; else if (deviceAddress == 0x77) //return "BMx085,BMx180,BMx280,BMx680,MS5611"; return "BMx085,BMx180,BMx280,BMx680"; else return "UNKNOWN"; } #endif // AFE_CONFIG_HARDWARE_I2C
29.495614
119
0.654721
tschaban
cb7ddfe4bf29d5d26542d1d41a5db5f63229ffe2
6,712
cc
C++
src/mem/page_table.cc
yb-kim/gemV
02e00bb8ac0cb4aacad2fc4a8cb4eeb1cf176233
[ "BSD-3-Clause" ]
14
2015-06-25T03:00:17.000Z
2021-09-26T16:33:43.000Z
src/mem/page_table.cc
yb-kim/gemV
02e00bb8ac0cb4aacad2fc4a8cb4eeb1cf176233
[ "BSD-3-Clause" ]
1
2019-04-28T05:23:32.000Z
2019-04-28T05:23:32.000Z
src/mem/page_table.cc
yb-kim/gemV
02e00bb8ac0cb4aacad2fc4a8cb4eeb1cf176233
[ "BSD-3-Clause" ]
5
2016-10-19T07:25:58.000Z
2020-12-12T18:35:37.000Z
/* * Copyright (c) 2003 The Regents of The University of Michigan * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt * Ron Dreslinski * Ali Saidi */ /** * @file * Definitions of page table. */ #include <fstream> #include <map> #include <string> #include "base/bitfield.hh" #include "base/intmath.hh" #include "base/trace.hh" #include "config/the_isa.hh" #include "debug/MMU.hh" #include "mem/page_table.hh" #include "sim/faults.hh" #include "sim/sim_object.hh" using namespace std; using namespace TheISA; PageTable::PageTable(const std::string &__name, uint64_t _pid, Addr _pageSize) : pageSize(_pageSize), offsetMask(mask(floorLog2(_pageSize))), pid(_pid), _name(__name) { assert(isPowerOf2(pageSize)); pTableCache[0].valid = false; pTableCache[1].valid = false; pTableCache[2].valid = false; } PageTable::~PageTable() { } void PageTable::map(Addr vaddr, Addr paddr, int64_t size, bool clobber) { // starting address must be page aligned assert(pageOffset(vaddr) == 0); DPRINTF(MMU, "Allocating Page: %#x-%#x\n", vaddr, vaddr+ size); for (; size > 0; size -= pageSize, vaddr += pageSize, paddr += pageSize) { if (!clobber && (pTable.find(vaddr) != pTable.end())) { // already mapped fatal("PageTable::allocate: address 0x%x already mapped", vaddr); } pTable[vaddr] = TheISA::TlbEntry(pid, vaddr, paddr); eraseCacheEntry(vaddr); updateCache(vaddr, pTable[vaddr]); } } void PageTable::remap(Addr vaddr, int64_t size, Addr new_vaddr) { assert(pageOffset(vaddr) == 0); assert(pageOffset(new_vaddr) == 0); DPRINTF(MMU, "moving pages from vaddr %08p to %08p, size = %d\n", vaddr, new_vaddr, size); for (; size > 0; size -= pageSize, vaddr += pageSize, new_vaddr += pageSize) { assert(pTable.find(vaddr) != pTable.end()); pTable[new_vaddr] = pTable[vaddr]; pTable.erase(vaddr); eraseCacheEntry(vaddr); pTable[new_vaddr].updateVaddr(new_vaddr); updateCache(new_vaddr, pTable[new_vaddr]); } } void PageTable::unmap(Addr vaddr, int64_t size) { assert(pageOffset(vaddr) == 0); DPRINTF(MMU, "Unmapping page: %#x-%#x\n", vaddr, vaddr+ size); for (; size > 0; size -= pageSize, vaddr += pageSize) { assert(pTable.find(vaddr) != pTable.end()); pTable.erase(vaddr); eraseCacheEntry(vaddr); } } bool PageTable::isUnmapped(Addr vaddr, int64_t size) { // starting address must be page aligned assert(pageOffset(vaddr) == 0); for (; size > 0; size -= pageSize, vaddr += pageSize) { if (pTable.find(vaddr) != pTable.end()) { return false; } } return true; } bool PageTable::lookup(Addr vaddr, TheISA::TlbEntry &entry) { Addr page_addr = pageAlign(vaddr); if (pTableCache[0].valid && pTableCache[0].vaddr == page_addr) { entry = pTableCache[0].entry; return true; } if (pTableCache[1].valid && pTableCache[1].vaddr == page_addr) { entry = pTableCache[1].entry; return true; } if (pTableCache[2].valid && pTableCache[2].vaddr == page_addr) { entry = pTableCache[2].entry; return true; } PTableItr iter = pTable.find(page_addr); if (iter == pTable.end()) { return false; } updateCache(page_addr, iter->second); entry = iter->second; return true; } bool PageTable::translate(Addr vaddr, Addr &paddr) { TheISA::TlbEntry entry; if (!lookup(vaddr, entry)) { DPRINTF(MMU, "Couldn't Translate: %#x\n", vaddr); return false; } paddr = pageOffset(vaddr) + entry.pageStart(); DPRINTF(MMU, "Translating: %#x->%#x\n", vaddr, paddr); return true; } Fault PageTable::translate(RequestPtr req) { Addr paddr; assert(pageAlign(req->getVaddr() + req->getSize() - 1) == pageAlign(req->getVaddr())); if (!translate(req->getVaddr(), paddr)) { return Fault(new GenericPageTableFault(req->getVaddr())); } req->setPaddr(paddr); if ((paddr & (pageSize - 1)) + req->getSize() > pageSize) { panic("Request spans page boundaries!\n"); return NoFault; } return NoFault; } void PageTable::serialize(std::ostream &os) { paramOut(os, "ptable.size", pTable.size()); PTable::size_type count = 0; PTableItr iter = pTable.begin(); PTableItr end = pTable.end(); while (iter != end) { os << "\n[" << csprintf("%s.Entry%d", name(), count) << "]\n"; paramOut(os, "vaddr", iter->first); iter->second.serialize(os); ++iter; ++count; } assert(count == pTable.size()); } void PageTable::unserialize(Checkpoint *cp, const std::string &section) { int i = 0, count; paramIn(cp, section, "ptable.size", count); pTable.clear(); while (i < count) { TheISA::TlbEntry *entry; Addr vaddr; paramIn(cp, csprintf("%s.Entry%d", name(), i), "vaddr", vaddr); entry = new TheISA::TlbEntry(); entry->unserialize(cp, csprintf("%s.Entry%d", name(), i)); pTable[vaddr] = *entry; delete entry; ++i; } }
28.201681
82
0.643623
yb-kim
cb7e0bff626080ccb1317f2bd4e4d77bd52f6ff0
8,323
cpp
C++
tests/kernel_concatenation_test/concatenation_test.cpp
pschatzmann/pico-tflmicro
c18a5081b2d5b62b1d4d74f7c7e33d543a3b75de
[ "Apache-2.0" ]
278
2021-01-21T07:25:35.000Z
2022-03-26T18:24:10.000Z
tensorflow/lite/micro/kernels/concatenation_test.cc
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
88
2020-11-24T08:18:10.000Z
2022-03-25T20:28:30.000Z
tensorflow/lite/micro/kernels/concatenation_test.cc
sseung0703/tensorflow
be084bd7a4dd241eb781fc704f57bcacc5c9b6dd
[ "Apache-2.0" ]
38
2021-01-21T07:25:45.000Z
2022-03-31T08:48:15.000Z
/* Copyright 2019 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 <initializer_list> #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/micro/kernels/kernel_runner.h" #include "tensorflow/lite/micro/test_helpers.h" #include "tensorflow/lite/micro/testing/micro_test.h" namespace tflite { namespace testing { namespace { void TestConcatenateTwoInputs(const int* input1_dims_data, const float* input1_data, const int* input2_dims_data, const float* input2_data, int axis, const int* output_dims_data, const float* expected_output_data, float* output_data) { TfLiteIntArray* input1_dims = IntArrayFromInts(input1_dims_data); TfLiteIntArray* input2_dims = IntArrayFromInts(input2_dims_data); TfLiteIntArray* output_dims = IntArrayFromInts(output_dims_data); constexpr int input_size = 2; constexpr int output_size = 1; constexpr int tensors_size = input_size + output_size; TfLiteTensor tensors[tensors_size] = {CreateTensor(input1_data, input1_dims), CreateTensor(input2_data, input2_dims), CreateTensor(output_data, output_dims)}; int inputs_array_data[] = {2, 0, 1}; TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data); int outputs_array_data[] = {1, 2}; TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data); TfLiteConcatenationParams builtin_data = { .axis = axis, .activation = kTfLiteActNone // Only activation supported in this impl }; const TfLiteRegistration registration = tflite::ops::micro::Register_CONCATENATION(); micro::KernelRunner runner( registration, tensors, tensors_size, inputs_array, outputs_array, reinterpret_cast<void*>(&builtin_data), micro_test::reporter); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare()); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke()); const int output_dims_count = ElementCount(*output_dims); for (int i = 0; i < output_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output_data[i], output_data[i], 1e-5f); } } void TestConcatenateQuantizedTwoInputs( const int* input1_dims_data, const uint8_t* input1_data, const int* input2_dims_data, const uint8_t* input2_data, const float input_scale, const int input_zero_point, int axis, const int* output_dims_data, const uint8_t* expected_output_data, const float output_scale, const int output_zero_point, uint8_t* output_data) { TfLiteIntArray* input1_dims = IntArrayFromInts(input1_dims_data); TfLiteIntArray* input2_dims = IntArrayFromInts(input2_dims_data); TfLiteIntArray* output_dims = IntArrayFromInts(output_dims_data); constexpr int input_size = 2; constexpr int output_size = 1; constexpr int tensors_size = input_size + output_size; TfLiteTensor tensors[tensors_size] = { CreateQuantizedTensor(input1_data, input1_dims, input_scale, input_zero_point), CreateQuantizedTensor(input2_data, input2_dims, input_scale, input_zero_point), CreateQuantizedTensor(output_data, output_dims, output_scale, output_zero_point)}; int inputs_array_data[] = {2, 0, 1}; TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data); int outputs_array_data[] = {1, 2}; TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data); TfLiteConcatenationParams builtin_data = { .axis = axis, .activation = kTfLiteActNone // Only activation supported in this impl }; const TfLiteRegistration registration = tflite::ops::micro::Register_CONCATENATION(); micro::KernelRunner runner( registration, tensors, tensors_size, inputs_array, outputs_array, reinterpret_cast<void*>(&builtin_data), micro_test::reporter); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.InitAndPrepare()); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, runner.Invoke()); const int output_dims_count = ElementCount(*output_dims); for (int i = 0; i < output_dims_count; ++i) { TF_LITE_MICRO_EXPECT_EQ(expected_output_data[i], output_data[i]); } } } // namespace } // namespace testing } // namespace tflite TF_LITE_MICRO_TESTS_BEGIN TF_LITE_MICRO_TEST(TwoInputsAllAxesCombinations) { // Concatenate the same two input tensors along all possible axes. const int input_shape[] = {2, 2, 3}; const float input1_value[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f}; const float input2_value[] = {7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; // expected output when concatenating on axis 0 const int output_shape_axis0[] = {2, 4, 3}; const float output_value_axis0[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; // expected output when concatenating on axis 1 const int output_shape_axis1[] = {2, 2, 6}; const float output_value_axis1[] = {1.0f, 2.0f, 3.0f, 7.0f, 8.0f, 9.0f, 4.0f, 5.0f, 6.0f, 10.0f, 11.0f, 12.0f}; float output_data[12]; // Axis = 0 tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ 0, output_shape_axis0, output_value_axis0, output_data); // Axis = -2 (equivalent to axis = 0) tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ -2, output_shape_axis0, output_value_axis0, output_data); // Axis = 1 tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ 1, output_shape_axis1, output_value_axis1, output_data); // Axis = -1 (equivalent to axis = 1) tflite::testing::TestConcatenateTwoInputs( input_shape, input1_value, input_shape, input2_value, /* axis */ -1, output_shape_axis1, output_value_axis1, output_data); } TF_LITE_MICRO_TEST(TwoInputsQuantizedUint8) { const int axis = 2; const int input_shape[] = {3, 2, 1, 2}; const int output_shape[] = {3, 2, 1, 4}; const float input_scale = 0.1f; const int input_zero_point = 127; const float output_scale = 0.1f; const int output_zero_point = 127; const uint8_t input1_values[] = {137, 157, 167, 197}; const uint8_t input2_values[] = {138, 158, 168, 198}; const uint8_t output_value[] = { 137, 157, 138, 158, 167, 197, 168, 198, }; uint8_t output_data[8]; tflite::testing::TestConcatenateQuantizedTwoInputs( input_shape, input1_values, input_shape, input2_values, input_scale, input_zero_point, axis, output_shape, output_value, output_scale, output_zero_point, output_data); } TF_LITE_MICRO_TEST(ThreeDimensionalTwoInputsDifferentShapes) { const int axis = 1; const int input1_shape[] = {3, 2, 1, 2}; const int input2_shape[] = {3, 2, 3, 2}; const int output_shape[] = {3, 2, 4, 2}; const float input1_values[] = {1.0f, 3.0f, 4.0f, 7.0f}; const float input2_values[] = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; const float output_values[] = {1.0f, 3.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 4.0f, 7.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 12.0f}; float output_data[16]; tflite::testing::TestConcatenateTwoInputs( input1_shape, input1_values, input2_shape, input2_values, axis, output_shape, output_values, output_data); } TF_LITE_MICRO_TESTS_END
39.822967
80
0.683528
pschatzmann
cb7f46d2660af5fd64bf8c35c812b4481e56a7d3
34,615
cc
C++
source/scale_mips.cc
herocodemaster/libyuv-chromium
83f460be3324ccd546ca45e6c282e8f201853e54
[ "BSD-3-Clause" ]
36
2016-06-10T02:42:37.000Z
2021-12-09T04:57:25.000Z
source/scale_mips.cc
herocodemaster/libyuv-chromium
83f460be3324ccd546ca45e6c282e8f201853e54
[ "BSD-3-Clause" ]
2
2017-01-03T12:37:35.000Z
2017-01-11T12:49:53.000Z
source/scale_mips.cc
herocodemaster/libyuv-chromium
83f460be3324ccd546ca45e6c282e8f201853e54
[ "BSD-3-Clause" ]
15
2016-11-16T02:30:42.000Z
2021-08-10T09:01:26.000Z
/* * Copyright 2012 The LibYuv 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "libyuv/basic_types.h" #include "libyuv/row.h" #ifdef __cplusplus namespace libyuv { extern "C" { #endif // This module is for GCC MIPS DSPR2 #if !defined(LIBYUV_DISABLE_MIPS) && defined(__mips_dsp) && \ (__mips_dsp_rev >= 2) && (_MIPS_SIM == _MIPS_SIM_ABI32) void ScaleRowDown2_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 4 \n" // iterations -> by 16 "beqz $t9, 2f \n" " nop \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t4, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t5, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t6, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t7, 28(%[src_ptr]) \n" // |31|30|29|28| // TODO(fbarchard): Use odd pixels instead of even. "precr.qb.ph $t8, $t1, $t0 \n" // |6|4|2|0| "precr.qb.ph $t0, $t3, $t2 \n" // |14|12|10|8| "precr.qb.ph $t1, $t5, $t4 \n" // |22|20|18|16| "precr.qb.ph $t2, $t7, $t6 \n" // |30|28|26|24| "addiu %[src_ptr], %[src_ptr], 32 \n" "addiu $t9, $t9, -1 \n" "sw $t8, 0(%[dst]) \n" "sw $t0, 4(%[dst]) \n" "sw $t1, 8(%[dst]) \n" "sw $t2, 12(%[dst]) \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 16 \n" "2: \n" "andi $t9, %[dst_width], 0xf \n" // residue "beqz $t9, 3f \n" " nop \n" "21: \n" "lbu $t0, 0(%[src_ptr]) \n" "addiu %[src_ptr], %[src_ptr], 2 \n" "addiu $t9, $t9, -1 \n" "sb $t0, 0(%[dst]) \n" "bgtz $t9, 21b \n" " addiu %[dst], %[dst], 1 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst) : [dst_width] "r"(dst_width) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown2Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { const uint8* t = src_ptr + src_stride; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 3 \n" // iterations -> step 8 "bltz $t9, 2f \n" " nop \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t4, 0(%[t]) \n" // |19|18|17|16| "lw $t5, 4(%[t]) \n" // |23|22|21|20| "lw $t6, 8(%[t]) \n" // |27|26|25|24| "lw $t7, 12(%[t]) \n" // |31|30|29|28| "addiu $t9, $t9, -1 \n" "srl $t8, $t0, 16 \n" // |X|X|3|2| "ins $t0, $t4, 16, 16 \n" // |17|16|1|0| "ins $t4, $t8, 0, 16 \n" // |19|18|3|2| "raddu.w.qb $t0, $t0 \n" // |17+16+1+0| "raddu.w.qb $t4, $t4 \n" // |19+18+3+2| "shra_r.w $t0, $t0, 2 \n" // |t0+2|>>2 "shra_r.w $t4, $t4, 2 \n" // |t4+2|>>2 "srl $t8, $t1, 16 \n" // |X|X|7|6| "ins $t1, $t5, 16, 16 \n" // |21|20|5|4| "ins $t5, $t8, 0, 16 \n" // |22|23|7|6| "raddu.w.qb $t1, $t1 \n" // |21+20+5+4| "raddu.w.qb $t5, $t5 \n" // |23+22+7+6| "shra_r.w $t1, $t1, 2 \n" // |t1+2|>>2 "shra_r.w $t5, $t5, 2 \n" // |t5+2|>>2 "srl $t8, $t2, 16 \n" // |X|X|11|10| "ins $t2, $t6, 16, 16 \n" // |25|24|9|8| "ins $t6, $t8, 0, 16 \n" // |27|26|11|10| "raddu.w.qb $t2, $t2 \n" // |25+24+9+8| "raddu.w.qb $t6, $t6 \n" // |27+26+11+10| "shra_r.w $t2, $t2, 2 \n" // |t2+2|>>2 "shra_r.w $t6, $t6, 2 \n" // |t5+2|>>2 "srl $t8, $t3, 16 \n" // |X|X|15|14| "ins $t3, $t7, 16, 16 \n" // |29|28|13|12| "ins $t7, $t8, 0, 16 \n" // |31|30|15|14| "raddu.w.qb $t3, $t3 \n" // |29+28+13+12| "raddu.w.qb $t7, $t7 \n" // |31+30+15+14| "shra_r.w $t3, $t3, 2 \n" // |t3+2|>>2 "shra_r.w $t7, $t7, 2 \n" // |t7+2|>>2 "addiu %[src_ptr], %[src_ptr], 16 \n" "addiu %[t], %[t], 16 \n" "sb $t0, 0(%[dst]) \n" "sb $t4, 1(%[dst]) \n" "sb $t1, 2(%[dst]) \n" "sb $t5, 3(%[dst]) \n" "sb $t2, 4(%[dst]) \n" "sb $t6, 5(%[dst]) \n" "sb $t3, 6(%[dst]) \n" "sb $t7, 7(%[dst]) \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 8 \n" "2: \n" "andi $t9, %[dst_width], 0x7 \n" // x = residue "beqz $t9, 3f \n" " nop \n" "21: \n" "lwr $t1, 0(%[src_ptr]) \n" "lwl $t1, 3(%[src_ptr]) \n" "lwr $t2, 0(%[t]) \n" "lwl $t2, 3(%[t]) \n" "srl $t8, $t1, 16 \n" "ins $t1, $t2, 16, 16 \n" "ins $t2, $t8, 0, 16 \n" "raddu.w.qb $t1, $t1 \n" "raddu.w.qb $t2, $t2 \n" "shra_r.w $t1, $t1, 2 \n" "shra_r.w $t2, $t2, 2 \n" "sb $t1, 0(%[dst]) \n" "sb $t2, 1(%[dst]) \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "addiu $t9, $t9, -2 \n" "addiu %[t], %[t], 4 \n" "bgtz $t9, 21b \n" " addiu %[dst], %[dst], 2 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [t] "+r"(t) : [dst_width] "r"(dst_width) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown4_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 3 \n" "beqz $t9, 2f \n" " nop \n" "1: \n" "lw $t1, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t2, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t3, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t4, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t5, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t6, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t7, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t8, 28(%[src_ptr]) \n" // |31|30|29|28| "precr.qb.ph $t1, $t2, $t1 \n" // |6|4|2|0| "precr.qb.ph $t2, $t4, $t3 \n" // |14|12|10|8| "precr.qb.ph $t5, $t6, $t5 \n" // |22|20|18|16| "precr.qb.ph $t6, $t8, $t7 \n" // |30|28|26|24| "precr.qb.ph $t1, $t2, $t1 \n" // |12|8|4|0| "precr.qb.ph $t5, $t6, $t5 \n" // |28|24|20|16| "addiu %[src_ptr], %[src_ptr], 32 \n" "addiu $t9, $t9, -1 \n" "sw $t1, 0(%[dst]) \n" "sw $t5, 4(%[dst]) \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 8 \n" "2: \n" "andi $t9, %[dst_width], 7 \n" // residue "beqz $t9, 3f \n" " nop \n" "21: \n" "lbu $t1, 0(%[src_ptr]) \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "addiu $t9, $t9, -1 \n" "sb $t1, 0(%[dst]) \n" "bgtz $t9, 21b \n" " addiu %[dst], %[dst], 1 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst) : [dst_width] "r"(dst_width) : "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown4Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { intptr_t stride = src_stride; const uint8* s1 = src_ptr + stride; const uint8* s2 = s1 + stride; const uint8* s3 = s2 + stride; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "srl $t9, %[dst_width], 1 \n" "andi $t8, %[dst_width], 1 \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 0(%[s1]) \n" // |7|6|5|4| "lw $t2, 0(%[s2]) \n" // |11|10|9|8| "lw $t3, 0(%[s3]) \n" // |15|14|13|12| "lw $t4, 4(%[src_ptr]) \n" // |19|18|17|16| "lw $t5, 4(%[s1]) \n" // |23|22|21|20| "lw $t6, 4(%[s2]) \n" // |27|26|25|24| "lw $t7, 4(%[s3]) \n" // |31|30|29|28| "raddu.w.qb $t0, $t0 \n" // |3 + 2 + 1 + 0| "raddu.w.qb $t1, $t1 \n" // |7 + 6 + 5 + 4| "raddu.w.qb $t2, $t2 \n" // |11 + 10 + 9 + 8| "raddu.w.qb $t3, $t3 \n" // |15 + 14 + 13 + 12| "raddu.w.qb $t4, $t4 \n" // |19 + 18 + 17 + 16| "raddu.w.qb $t5, $t5 \n" // |23 + 22 + 21 + 20| "raddu.w.qb $t6, $t6 \n" // |27 + 26 + 25 + 24| "raddu.w.qb $t7, $t7 \n" // |31 + 30 + 29 + 28| "add $t0, $t0, $t1 \n" "add $t1, $t2, $t3 \n" "add $t0, $t0, $t1 \n" "add $t4, $t4, $t5 \n" "add $t6, $t6, $t7 \n" "add $t4, $t4, $t6 \n" "shra_r.w $t0, $t0, 4 \n" "shra_r.w $t4, $t4, 4 \n" "sb $t0, 0(%[dst]) \n" "sb $t4, 1(%[dst]) \n" "addiu %[src_ptr], %[src_ptr], 8 \n" "addiu %[s1], %[s1], 8 \n" "addiu %[s2], %[s2], 8 \n" "addiu %[s3], %[s3], 8 \n" "addiu $t9, $t9, -1 \n" "bgtz $t9, 1b \n" " addiu %[dst], %[dst], 2 \n" "beqz $t8, 2f \n" " nop \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 0(%[s1]) \n" // |7|6|5|4| "lw $t2, 0(%[s2]) \n" // |11|10|9|8| "lw $t3, 0(%[s3]) \n" // |15|14|13|12| "raddu.w.qb $t0, $t0 \n" // |3 + 2 + 1 + 0| "raddu.w.qb $t1, $t1 \n" // |7 + 6 + 5 + 4| "raddu.w.qb $t2, $t2 \n" // |11 + 10 + 9 + 8| "raddu.w.qb $t3, $t3 \n" // |15 + 14 + 13 + 12| "add $t0, $t0, $t1 \n" "add $t1, $t2, $t3 \n" "add $t0, $t0, $t1 \n" "shra_r.w $t0, $t0, 4 \n" "sb $t0, 0(%[dst]) \n" "2: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [s1] "+r"(s1), [s2] "+r"(s2), [s3] "+r"(s3) : [dst_width] "r"(dst_width) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown34_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t1, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t2, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t3, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t4, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t5, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t6, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t7, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t8, 28(%[src_ptr]) \n" // |31|30|29|28| "precrq.qb.ph $t0, $t2, $t4 \n" // |7|5|15|13| "precrq.qb.ph $t9, $t6, $t8 \n" // |23|21|31|30| "addiu %[dst_width], %[dst_width], -24 \n" "ins $t1, $t1, 8, 16 \n" // |3|1|0|X| "ins $t4, $t0, 8, 16 \n" // |X|15|13|12| "ins $t5, $t5, 8, 16 \n" // |19|17|16|X| "ins $t8, $t9, 8, 16 \n" // |X|31|29|28| "addiu %[src_ptr], %[src_ptr], 32 \n" "packrl.ph $t0, $t3, $t0 \n" // |9|8|7|5| "packrl.ph $t9, $t7, $t9 \n" // |25|24|23|21| "prepend $t1, $t2, 8 \n" // |4|3|1|0| "prepend $t3, $t4, 24 \n" // |15|13|12|11| "prepend $t5, $t6, 8 \n" // |20|19|17|16| "prepend $t7, $t8, 24 \n" // |31|29|28|27| "sw $t1, 0(%[dst]) \n" "sw $t0, 4(%[dst]) \n" "sw $t3, 8(%[dst]) \n" "sw $t5, 12(%[dst]) \n" "sw $t9, 16(%[dst]) \n" "sw $t7, 20(%[dst]) \n" "bnez %[dst_width], 1b \n" " addiu %[dst], %[dst], 24 \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"); } void ScaleRowDown34_0_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* d, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "repl.ph $t3, 3 \n" // 0x00030003 "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lwx $t1, %[src_stride](%[src_ptr]) \n" // |T3|T2|T1|T0| "rotr $t2, $t0, 8 \n" // |S0|S3|S2|S1| "rotr $t6, $t1, 8 \n" // |T0|T3|T2|T1| "muleu_s.ph.qbl $t4, $t2, $t3 \n" // |S0*3|S3*3| "muleu_s.ph.qbl $t5, $t6, $t3 \n" // |T0*3|T3*3| "andi $t0, $t2, 0xFFFF \n" // |0|0|S2|S1| "andi $t1, $t6, 0xFFFF \n" // |0|0|T2|T1| "raddu.w.qb $t0, $t0 \n" "raddu.w.qb $t1, $t1 \n" "shra_r.w $t0, $t0, 1 \n" "shra_r.w $t1, $t1, 1 \n" "preceu.ph.qbr $t2, $t2 \n" // |0|S2|0|S1| "preceu.ph.qbr $t6, $t6 \n" // |0|T2|0|T1| "rotr $t2, $t2, 16 \n" // |0|S1|0|S2| "rotr $t6, $t6, 16 \n" // |0|T1|0|T2| "addu.ph $t2, $t2, $t4 \n" "addu.ph $t6, $t6, $t5 \n" "sll $t5, $t0, 1 \n" "add $t0, $t5, $t0 \n" "shra_r.ph $t2, $t2, 2 \n" "shra_r.ph $t6, $t6, 2 \n" "shll.ph $t4, $t2, 1 \n" "addq.ph $t4, $t4, $t2 \n" "addu $t0, $t0, $t1 \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "shra_r.w $t0, $t0, 2 \n" "addu.ph $t6, $t6, $t4 \n" "shra_r.ph $t6, $t6, 2 \n" "srl $t1, $t6, 16 \n" "addiu %[dst_width], %[dst_width], -3 \n" "sb $t1, 0(%[d]) \n" "sb $t0, 1(%[d]) \n" "sb $t6, 2(%[d]) \n" "bgtz %[dst_width], 1b \n" " addiu %[d], %[d], 3 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [src_stride] "+r"(src_stride), [d] "+r"(d), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6"); } void ScaleRowDown34_1_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* d, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "repl.ph $t2, 3 \n" // 0x00030003 "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lwx $t1, %[src_stride](%[src_ptr]) \n" // |T3|T2|T1|T0| "rotr $t4, $t0, 8 \n" // |S0|S3|S2|S1| "rotr $t6, $t1, 8 \n" // |T0|T3|T2|T1| "muleu_s.ph.qbl $t3, $t4, $t2 \n" // |S0*3|S3*3| "muleu_s.ph.qbl $t5, $t6, $t2 \n" // |T0*3|T3*3| "andi $t0, $t4, 0xFFFF \n" // |0|0|S2|S1| "andi $t1, $t6, 0xFFFF \n" // |0|0|T2|T1| "raddu.w.qb $t0, $t0 \n" "raddu.w.qb $t1, $t1 \n" "shra_r.w $t0, $t0, 1 \n" "shra_r.w $t1, $t1, 1 \n" "preceu.ph.qbr $t4, $t4 \n" // |0|S2|0|S1| "preceu.ph.qbr $t6, $t6 \n" // |0|T2|0|T1| "rotr $t4, $t4, 16 \n" // |0|S1|0|S2| "rotr $t6, $t6, 16 \n" // |0|T1|0|T2| "addu.ph $t4, $t4, $t3 \n" "addu.ph $t6, $t6, $t5 \n" "shra_r.ph $t6, $t6, 2 \n" "shra_r.ph $t4, $t4, 2 \n" "addu.ph $t6, $t6, $t4 \n" "addiu %[src_ptr], %[src_ptr], 4 \n" "shra_r.ph $t6, $t6, 1 \n" "addu $t0, $t0, $t1 \n" "addiu %[dst_width], %[dst_width], -3 \n" "shra_r.w $t0, $t0, 1 \n" "srl $t1, $t6, 16 \n" "sb $t1, 0(%[d]) \n" "sb $t0, 1(%[d]) \n" "sb $t6, 2(%[d]) \n" "bgtz %[dst_width], 1b \n" " addiu %[d], %[d], 3 \n" "3: \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [src_stride] "+r"(src_stride), [d] "+r"(d), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6"); } void ScaleRowDown38_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst, int dst_width) { __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |3|2|1|0| "lw $t1, 4(%[src_ptr]) \n" // |7|6|5|4| "lw $t2, 8(%[src_ptr]) \n" // |11|10|9|8| "lw $t3, 12(%[src_ptr]) \n" // |15|14|13|12| "lw $t4, 16(%[src_ptr]) \n" // |19|18|17|16| "lw $t5, 20(%[src_ptr]) \n" // |23|22|21|20| "lw $t6, 24(%[src_ptr]) \n" // |27|26|25|24| "lw $t7, 28(%[src_ptr]) \n" // |31|30|29|28| "wsbh $t0, $t0 \n" // |2|3|0|1| "wsbh $t6, $t6 \n" // |26|27|24|25| "srl $t0, $t0, 8 \n" // |X|2|3|0| "srl $t3, $t3, 16 \n" // |X|X|15|14| "srl $t5, $t5, 16 \n" // |X|X|23|22| "srl $t7, $t7, 16 \n" // |X|X|31|30| "ins $t1, $t2, 24, 8 \n" // |8|6|5|4| "ins $t6, $t5, 0, 8 \n" // |26|27|24|22| "ins $t1, $t0, 0, 16 \n" // |8|6|3|0| "ins $t6, $t7, 24, 8 \n" // |30|27|24|22| "prepend $t2, $t3, 24 \n" // |X|15|14|11| "ins $t4, $t4, 16, 8 \n" // |19|16|17|X| "ins $t4, $t2, 0, 16 \n" // |19|16|14|11| "addiu %[src_ptr], %[src_ptr], 32 \n" "addiu %[dst_width], %[dst_width], -12 \n" "addiu $t8,%[dst_width], -12 \n" "sw $t1, 0(%[dst]) \n" "sw $t4, 4(%[dst]) \n" "sw $t6, 8(%[dst]) \n" "bgez $t8, 1b \n" " addiu %[dst], %[dst], 12 \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst] "+r"(dst), [dst_width] "+r"(dst_width) : : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"); } void ScaleRowDown38_2_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst_ptr, int dst_width) { intptr_t stride = src_stride; const uint8* t = src_ptr + stride; const int c = 0x2AAA; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lw $t1, 4(%[src_ptr]) \n" // |S7|S6|S5|S4| "lw $t2, 0(%[t]) \n" // |T3|T2|T1|T0| "lw $t3, 4(%[t]) \n" // |T7|T6|T5|T4| "rotr $t1, $t1, 16 \n" // |S5|S4|S7|S6| "packrl.ph $t4, $t1, $t3 \n" // |S7|S6|T7|T6| "packrl.ph $t5, $t3, $t1 \n" // |T5|T4|S5|S4| "raddu.w.qb $t4, $t4 \n" // S7+S6+T7+T6 "raddu.w.qb $t5, $t5 \n" // T5+T4+S5+S4 "precrq.qb.ph $t6, $t0, $t2 \n" // |S3|S1|T3|T1| "precrq.qb.ph $t6, $t6, $t6 \n" // |S3|T3|S3|T3| "srl $t4, $t4, 2 \n" // t4 / 4 "srl $t6, $t6, 16 \n" // |0|0|S3|T3| "raddu.w.qb $t6, $t6 \n" // 0+0+S3+T3 "addu $t6, $t5, $t6 \n" "mul $t6, $t6, %[c] \n" // t6 * 0x2AAA "sll $t0, $t0, 8 \n" // |S2|S1|S0|0| "sll $t2, $t2, 8 \n" // |T2|T1|T0|0| "raddu.w.qb $t0, $t0 \n" // S2+S1+S0+0 "raddu.w.qb $t2, $t2 \n" // T2+T1+T0+0 "addu $t0, $t0, $t2 \n" "mul $t0, $t0, %[c] \n" // t0 * 0x2AAA "addiu %[src_ptr], %[src_ptr], 8 \n" "addiu %[t], %[t], 8 \n" "addiu %[dst_width], %[dst_width], -3 \n" "addiu %[dst_ptr], %[dst_ptr], 3 \n" "srl $t6, $t6, 16 \n" "srl $t0, $t0, 16 \n" "sb $t4, -1(%[dst_ptr]) \n" "sb $t6, -2(%[dst_ptr]) \n" "bgtz %[dst_width], 1b \n" " sb $t0, -3(%[dst_ptr]) \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst_ptr] "+r"(dst_ptr), [t] "+r"(t), [dst_width] "+r"(dst_width) : [c] "r"(c) : "t0", "t1", "t2", "t3", "t4", "t5", "t6"); } void ScaleRowDown38_3_Box_DSPR2(const uint8* src_ptr, ptrdiff_t src_stride, uint8* dst_ptr, int dst_width) { intptr_t stride = src_stride; const uint8* s1 = src_ptr + stride; stride += stride; const uint8* s2 = src_ptr + stride; const int c1 = 0x1C71; const int c2 = 0x2AAA; __asm__ __volatile__( ".set push \n" ".set noreorder \n" "1: \n" "lw $t0, 0(%[src_ptr]) \n" // |S3|S2|S1|S0| "lw $t1, 4(%[src_ptr]) \n" // |S7|S6|S5|S4| "lw $t2, 0(%[s1]) \n" // |T3|T2|T1|T0| "lw $t3, 4(%[s1]) \n" // |T7|T6|T5|T4| "lw $t4, 0(%[s2]) \n" // |R3|R2|R1|R0| "lw $t5, 4(%[s2]) \n" // |R7|R6|R5|R4| "rotr $t1, $t1, 16 \n" // |S5|S4|S7|S6| "packrl.ph $t6, $t1, $t3 \n" // |S7|S6|T7|T6| "raddu.w.qb $t6, $t6 \n" // S7+S6+T7+T6 "packrl.ph $t7, $t3, $t1 \n" // |T5|T4|S5|S4| "raddu.w.qb $t7, $t7 \n" // T5+T4+S5+S4 "sll $t8, $t5, 16 \n" // |R5|R4|0|0| "raddu.w.qb $t8, $t8 \n" // R5+R4 "addu $t7, $t7, $t8 \n" "srl $t8, $t5, 16 \n" // |0|0|R7|R6| "raddu.w.qb $t8, $t8 \n" // R7 + R6 "addu $t6, $t6, $t8 \n" "mul $t6, $t6, %[c2] \n" // t6 * 0x2AAA "precrq.qb.ph $t8, $t0, $t2 \n" // |S3|S1|T3|T1| "precrq.qb.ph $t8, $t8, $t4 \n" // |S3|T3|R3|R1| "srl $t8, $t8, 8 \n" // |0|S3|T3|R3| "raddu.w.qb $t8, $t8 \n" // S3 + T3 + R3 "addu $t7, $t7, $t8 \n" "mul $t7, $t7, %[c1] \n" // t7 * 0x1C71 "sll $t0, $t0, 8 \n" // |S2|S1|S0|0| "sll $t2, $t2, 8 \n" // |T2|T1|T0|0| "sll $t4, $t4, 8 \n" // |R2|R1|R0|0| "raddu.w.qb $t0, $t0 \n" "raddu.w.qb $t2, $t2 \n" "raddu.w.qb $t4, $t4 \n" "addu $t0, $t0, $t2 \n" "addu $t0, $t0, $t4 \n" "mul $t0, $t0, %[c1] \n" // t0 * 0x1C71 "addiu %[src_ptr], %[src_ptr], 8 \n" "addiu %[s1], %[s1], 8 \n" "addiu %[s2], %[s2], 8 \n" "addiu %[dst_width], %[dst_width], -3 \n" "addiu %[dst_ptr], %[dst_ptr], 3 \n" "srl $t6, $t6, 16 \n" "srl $t7, $t7, 16 \n" "srl $t0, $t0, 16 \n" "sb $t6, -1(%[dst_ptr]) \n" "sb $t7, -2(%[dst_ptr]) \n" "bgtz %[dst_width], 1b \n" " sb $t0, -3(%[dst_ptr]) \n" ".set pop \n" : [src_ptr] "+r"(src_ptr), [dst_ptr] "+r"(dst_ptr), [s1] "+r"(s1), [s2] "+r"(s2), [dst_width] "+r"(dst_width) : [c1] "r"(c1), [c2] "r"(c2) : "t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"); } #endif // defined(__mips_dsp) && (__mips_dsp_rev >= 2) #ifdef __cplusplus } // extern "C" } // namespace libyuv #endif
55.472756
80
0.265261
herocodemaster
cb80b49bee22db688ad98ffe6917e344d3a15ec7
1,600
hpp
C++
src/core/models/mutation/indel_mutation_model.hpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
1
2018-08-21T23:34:28.000Z
2018-08-21T23:34:28.000Z
src/core/models/mutation/indel_mutation_model.hpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
null
null
null
src/core/models/mutation/indel_mutation_model.hpp
alimanfoo/octopus
f3cc3f567f02fafe33f5a06e5be693d6ea985ee3
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2018 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #ifndef indel_mutation_model_hpp #define indel_mutation_model_hpp #include <vector> #include <cstdint> #include "core/types/haplotype.hpp" #include "core/types/variant.hpp" namespace octopus { class IndelMutationModel { public: struct Parameters { double indel_mutation_rate; unsigned max_period = 10, max_periodicity = 20; double max_open_probability = 1.0, max_extend_probability = 1.0; }; struct ContextIndelModel { using Probability = double; using ProbabilityVector = std::vector<Probability>; ProbabilityVector gap_open, gap_extend; }; IndelMutationModel() = delete; IndelMutationModel(Parameters params); IndelMutationModel(const IndelMutationModel&) = default; IndelMutationModel& operator=(const IndelMutationModel&) = default; IndelMutationModel(IndelMutationModel&&) = default; IndelMutationModel& operator=(IndelMutationModel&&) = default; ~IndelMutationModel() = default; ContextIndelModel evaluate(const Haplotype& haplotype) const; private: struct ModelCell { double open, extend; }; using RepeatModel = std::vector<std::vector<ModelCell>>; Parameters params_; RepeatModel indel_repeat_model_; }; IndelMutationModel::ContextIndelModel make_indel_model(const Haplotype& context, IndelMutationModel::Parameters params); } // namespace octopus #endif
27.586207
120
0.70625
alimanfoo
cb83514bbfb5f1668dd3063a6e451fc9556841f9
261
cpp
C++
imageEditorApp/src/view/main.cpp
Ecquus/imageEditor
bcecd7434e806b29b935dec58122ece4fd36f727
[ "MIT" ]
null
null
null
imageEditorApp/src/view/main.cpp
Ecquus/imageEditor
bcecd7434e806b29b935dec58122ece4fd36f727
[ "MIT" ]
null
null
null
imageEditorApp/src/view/main.cpp
Ecquus/imageEditor
bcecd7434e806b29b935dec58122ece4fd36f727
[ "MIT" ]
null
null
null
#include <mainwindow.h> #include <QApplication> #include <cstring> int main(int argc, char *argv[]) { QApplication a(argc, argv); bool debug = argc > 1 && strcmp(argv[1], "-d") == 0; MainWindow w(debug); w.show(); return a.exec(); }
16.3125
56
0.586207
Ecquus
cb86a134595e66d8180a1dccf1409e9631a5f103
1,088
cpp
C++
Week04/Fraction.cpp
mdnam2410/hcmus-oop-lab
2eb2bc781ed652b8f44396a5460a0422fda00c5b
[ "MIT" ]
null
null
null
Week04/Fraction.cpp
mdnam2410/hcmus-oop-lab
2eb2bc781ed652b8f44396a5460a0422fda00c5b
[ "MIT" ]
null
null
null
Week04/Fraction.cpp
mdnam2410/hcmus-oop-lab
2eb2bc781ed652b8f44396a5460a0422fda00c5b
[ "MIT" ]
null
null
null
#include "Fraction.h" #include <sstream> Fraction::Fraction() { m_nom = new int(0); m_denom = new int(1); } Fraction::Fraction(int value) { m_nom = new int(value); m_denom = new int(1); } Fraction::Fraction(int nom, int denom) { m_nom = new int(nom); m_denom = new int(denom); makeDenominatorPositive(); } Fraction::Fraction(const Fraction& f) { m_nom = new int(*f.m_nom); m_denom = new int(*f.m_denom); } Fraction::~Fraction() { delete m_nom; delete m_denom; } void Fraction::makeDenominatorPositive() { if (*m_denom < 0) { *m_nom = -*m_nom; *m_denom = -*m_denom; } } int Fraction::getNom() const { return *m_nom; } int Fraction::getDenom() const { return *m_denom; } void Fraction::setNom(int nom) { *m_nom = nom; } bool Fraction::setDenom(int denom) { if (denom == 0) return false; *m_denom = denom; makeDenominatorPositive(); return true; } std::string Fraction::ToString() const { std::stringstream ss; ss << *m_nom << '/' << *m_denom; return ss.str(); }
14.90411
40
0.601103
mdnam2410
cb89a7a6a17b18d2dbda29ab619cb87648b427ee
2,166
cpp
C++
libRocketWrapper/Src/ManagedFileInterface.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
libRocketWrapper/Src/ManagedFileInterface.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
libRocketWrapper/Src/ManagedFileInterface.cpp
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
#include "StdAfx.h" class ManagedFileInterface : public Rocket::Core::FileInterface { public: typedef size_t (*OpenCb)(String path HANDLE_ARG); typedef void(*CloseCb)(Rocket::Core::FileHandle file HANDLE_ARG); typedef size_t(*ReadCb)(void* buffer, size_t size, Rocket::Core::FileHandle file HANDLE_ARG); typedef bool(*SeekCb)(Rocket::Core::FileHandle file, long offset, int origin HANDLE_ARG); typedef size_t(*TellCb)(Rocket::Core::FileHandle file HANDLE_ARG); typedef void (*ReleaseCb)(HANDLE_FIRST_ARG); ManagedFileInterface(OpenCb open, CloseCb close, ReadCb read, SeekCb seek, TellCb tell, ReleaseCb release HANDLE_ARG) :open(open), close(close), read(read), seek(seek), tell(tell), release(release) ASSIGN_HANDLE_INITIALIZER { } virtual ~ManagedFileInterface() { } virtual Rocket::Core::FileHandle Open(const Rocket::Core::String& path) { return open(path.CString() PASS_HANDLE_ARG); } virtual void Close(Rocket::Core::FileHandle file) { close(file PASS_HANDLE_ARG); } virtual size_t Read(void* buffer, size_t size, Rocket::Core::FileHandle file) { return read(buffer, size, file PASS_HANDLE_ARG); } virtual bool Seek(Rocket::Core::FileHandle file, long offset, int origin) { return seek(file, offset, origin PASS_HANDLE_ARG); } virtual size_t Tell(Rocket::Core::FileHandle file) { return tell(file PASS_HANDLE_ARG); } virtual void Release() { release(PASS_HANDLE); } private: OpenCb open; CloseCb close; ReadCb read; SeekCb seek; TellCb tell; ReleaseCb release; HANDLE_INSTANCE }; extern "C" _AnomalousExport ManagedFileInterface* ManagedFileInterface_Create(ManagedFileInterface::OpenCb open, ManagedFileInterface::CloseCb close, ManagedFileInterface::ReadCb read, ManagedFileInterface::SeekCb seek, ManagedFileInterface::TellCb tell, ManagedFileInterface::ReleaseCb release HANDLE_ARG) { return new ManagedFileInterface(open, close, read, seek, tell, release PASS_HANDLE_ARG); } extern "C" _AnomalousExport void ManagedFileInterface_Delete(ManagedFileInterface* fileInterface) { delete fileInterface; }
27.769231
307
0.738689
AnomalousMedical
cb8b164073545b49850380576d5c5daf872f92c9
1,493
cpp
C++
src/main.cpp
NDelt/Mini-Search-Engine
c7c64a7d365e5112e0a6eb320d3ff3e399bd9e18
[ "Apache-2.0" ]
null
null
null
src/main.cpp
NDelt/Mini-Search-Engine
c7c64a7d365e5112e0a6eb320d3ff3e399bd9e18
[ "Apache-2.0" ]
null
null
null
src/main.cpp
NDelt/Mini-Search-Engine
c7c64a7d365e5112e0a6eb320d3ff3e399bd9e18
[ "Apache-2.0" ]
1
2019-04-11T03:02:05.000Z
2019-04-11T03:02:05.000Z
/*************************************************************************** * Copyright 2019 HYUNWOO O * * 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 <iostream> #include "TableIndexer.hpp" #include "TableSearcher.hpp" #define MAX_QUERY_SIZE 1000 int main() { HashMap hashMap; TableIndexer tableIndexer; tableIndexer.createIndex("../resources/amazon_jobs.csv", hashMap); TableSearcher tableSearcher; while (true) { std::cout << "Input queries: (type 'exitsearch' to exit) "; char temp[MAX_QUERY_SIZE]; std::cin.getline(temp, MAX_QUERY_SIZE, '\n'); std::string searchQuery(temp); if (searchQuery == "exitsearch") { std::cout << "===== Shut down search engine... =====\n"; break; } tableSearcher.search(searchQuery, hashMap); } return 0; }
30.469388
76
0.583389
NDelt
cb8c968fa166b95b8a5674447afc69c8b9cd0f6f
324
hpp
C++
native/sample/headers/mcpe/LevelChunk.hpp
Molybdocene-dichloride/GregTech_BE
b19171ff4e41826c0bd4cf2dbdd9916f46254d67
[ "MIT" ]
4
2021-01-15T08:33:44.000Z
2022-03-13T19:11:08.000Z
native/sample/headers/mcpe/LevelChunk.hpp
Molybdocene-dichloride/GregTech_BE
b19171ff4e41826c0bd4cf2dbdd9916f46254d67
[ "MIT" ]
null
null
null
native/sample/headers/mcpe/LevelChunk.hpp
Molybdocene-dichloride/GregTech_BE
b19171ff4e41826c0bd4cf2dbdd9916f46254d67
[ "MIT" ]
null
null
null
#pragma once #include <mcpe\BlockPos.hpp> #include <mcpe\Block.hpp> #include <mcpe\Dimension.hpp> class LevelChunk { public: Level getLevel() const; Dimension getDimension() const; Block getBlock(ChunkBlockPos const&) const; ChunkLocalHeight getHeightRange() const; ChunkPos* getPosition() const; };
24.923077
47
0.722222
Molybdocene-dichloride
cb8eb92813d5ae8dc1699cdd1ab54e63d08b8617
2,007
cc
C++
tests/api/mpi/comm/probe-intercomm.cc
jpkenny/sst-macro
bcc1f43034281885104962586d8b104df84b58bd
[ "BSD-Source-Code" ]
20
2017-01-26T09:28:23.000Z
2022-01-17T11:31:55.000Z
tests/api/mpi/comm/probe-intercomm.cc
jpkenny/sst-macro
bcc1f43034281885104962586d8b104df84b58bd
[ "BSD-Source-Code" ]
542
2016-03-29T22:50:58.000Z
2022-03-22T20:14:08.000Z
tests/api/mpi/comm/probe-intercomm.cc
jpkenny/sst-macro
bcc1f43034281885104962586d8b104df84b58bd
[ "BSD-Source-Code" ]
36
2016-03-10T21:33:54.000Z
2021-12-01T07:44:12.000Z
/* * * (C) 2003 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include <sstmac/replacements/mpi/mpi.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "mpitest.h" namespace probe_intercomm{ /** static char MTEST_Descrip[] = "Test MPI_Probe() for an intercomm"; */ #define MAX_DATA_LEN 100 int probe_intercomm( int argc, char *argv[] ) { int errs = 0, recvlen, isLeft; MPI_Status status; int rank, size; MPI_Comm intercomm; char buf[MAX_DATA_LEN]; const char *test_str = "test"; MTest_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &rank ); MPI_Comm_size( MPI_COMM_WORLD, &size ); if (size < 2) { fprintf( stderr, "This test requires at least two processes." ); MPI_Abort( MPI_COMM_WORLD, 1 ); } while (MTestGetIntercomm( &intercomm, &isLeft, 2 )) { if (intercomm == MPI_COMM_NULL) continue; MPI_Comm_rank(intercomm, &rank); /** 0 ranks on each side communicate, everyone else does nothing */ if(rank == 0) { if (isLeft) { recvlen = -1; MPI_Probe(0, 0, intercomm, &status); MPI_Get_count(&status, MPI_CHAR, &recvlen); if (recvlen != (strlen(test_str) + 1)) { printf(" Error: recvlen (%d) != strlen(\"%s\")+1 (%d)\n", recvlen, test_str, (int)strlen(test_str) + 1); ++errs; } buf[0] = '\0'; MPI_Recv(buf, recvlen, MPI_CHAR, 0, 0, intercomm, &status); if (strcmp(test_str,buf)) { printf(" Error: strcmp(test_str,buf)!=0\n"); ++errs; } } else { strncpy(buf, test_str, 5); MPI_Send(buf, strlen(buf)+1, MPI_CHAR, 0, 0, intercomm); } } MTestFreeComm(&intercomm); } MTest_Finalize( errs ); MPI_Finalize(); return 0; } }
26.76
124
0.540608
jpkenny
cb8eb99ac87328b3295e2a216dc5fdb43219b1a5
3,660
cpp
C++
cxxtest/cxxtest/LinkedList.cpp
coreyp1/graphlab
637be90021c5f83ab7833ca15c48e76039057969
[ "ECL-2.0", "Apache-2.0" ]
333
2016-07-29T19:22:07.000Z
2022-03-30T02:40:34.000Z
cxxtest/cxxtest/LinkedList.cpp
HybridGraph/GraphLab-PowerGraph
ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94
[ "ECL-2.0", "Apache-2.0" ]
17
2016-09-15T00:31:59.000Z
2022-02-08T07:51:07.000Z
cxxtest/cxxtest/LinkedList.cpp
HybridGraph/GraphLab-PowerGraph
ba333c1cd82325ab2bfc6dd7ebb871b3fff64a94
[ "ECL-2.0", "Apache-2.0" ]
163
2016-07-29T19:22:11.000Z
2022-03-07T07:15:24.000Z
/* ------------------------------------------------------------------------- CxxTest: A lightweight C++ unit testing library. Copyright (c) 2008 Sandia Corporation. This software is distributed under the LGPL License v2.1 For more information, see the COPYING file in the top CxxTest directory. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. ------------------------------------------------------------------------- */ #ifndef __cxxtest__LinkedList_cpp__ #define __cxxtest__LinkedList_cpp__ #include <cxxtest/LinkedList.h> namespace CxxTest { List GlobalFixture::_list = { 0, 0 }; List RealSuiteDescription::_suites = { 0, 0 }; void List::initialize() { _head = _tail = 0; } Link *List::head() { Link *l = _head; while ( l && !l->active() ) l = l->next(); return l; } const Link *List::head() const { Link *l = _head; while ( l && !l->active() ) l = l->next(); return l; } Link *List::tail() { Link *l = _tail; while ( l && !l->active() ) l = l->prev(); return l; } const Link *List::tail() const { Link *l = _tail; while ( l && !l->active() ) l = l->prev(); return l; } bool List::empty() const { return (_head == 0); } unsigned List::size() const { unsigned count = 0; for ( const Link *l = head(); l != 0; l = l->next() ) ++ count; return count; } Link *List::nth( unsigned n ) { Link *l = head(); while ( n -- ) l = l->next(); return l; } void List::activateAll() { for ( Link *l = _head; l != 0; l = l->justNext() ) l->setActive( true ); } void List::leaveOnly( const Link &link ) { for ( Link *l = head(); l != 0; l = l->next() ) if ( l != &link ) l->setActive( false ); } Link::Link() : _next( 0 ), _prev( 0 ), _active( true ) { } Link::~Link() { } bool Link::active() const { return _active; } void Link::setActive( bool value ) { _active = value; } Link * Link::justNext() { return _next; } Link * Link::justPrev() { return _prev; } Link * Link::next() { Link *l = _next; while ( l && !l->_active ) l = l->_next; return l; } Link * Link::prev() { Link *l = _prev; while ( l && !l->_active ) l = l->_prev; return l; } const Link * Link::next() const { Link *l = _next; while ( l && !l->_active ) l = l->_next; return l; } const Link * Link::prev() const { Link *l = _prev; while ( l && !l->_active ) l = l->_prev; return l; } void Link::attach( List &l ) { if ( l._tail ) l._tail->_next = this; _prev = l._tail; _next = 0; if ( l._head == 0 ) l._head = this; l._tail = this; } void Link::detach( List &l ) { if ( _prev ) _prev->_next = _next; else l._head = _next; if ( _next ) _next->_prev = _prev; else l._tail = _prev; } } #endif // __cxxtest__LinkedList_cpp__
19.891304
73
0.428415
coreyp1
cb8f1953a88140b9afa9a18898b6c177720b6f8a
9,131
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/cpp/VS_Snippets_CLR/formatting.numeric.custom/cpp/custom.cpp
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
using namespace System; using namespace System::Globalization; void ShowZeroPlaceholder() { // <Snippet1> double value; value = 123; Console::WriteLine(value.ToString("00000")); Console::WriteLine(String::Format("{0:00000}", value)); // Displays 00123 value = 1.2; Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.00}", value)); // Displays 1.20 Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:00.00}", value)); // Displays 01.20 CultureInfo^ daDK = CultureInfo::CreateSpecificCulture("da-DK"); Console::WriteLine(value.ToString("00.00", daDK)); Console::WriteLine(String::Format(daDK, "{0:00.00}", value)); // Displays 01,20 value = .56; Console::WriteLine(value.ToString("0.0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.0}", value)); // Displays 0.6 value = 1234567890; Console::WriteLine(value.ToString("0,0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0,0}", value)); // Displays 1,234,567,890 CultureInfo^ elGR = CultureInfo::CreateSpecificCulture("el-GR"); Console::WriteLine(value.ToString("0,0", elGR)); Console::WriteLine(String::Format(elGR, "{0:0,0}", value)); // Displays 1.234.567.890 value = 1234567890.123456; Console::WriteLine(value.ToString("0,0.0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0,0.0}", value)); // Displays 1,234,567,890.1 value = 1234.567890; Console::WriteLine(value.ToString("0,0.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0,0.00}", value)); // Displays 1,234.57 // </Snippet1> } void ShowDigitPlaceholder() { // <Snippet2> double value; value = 1.2; Console::WriteLine(value.ToString("#.##", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#.##}", value)); // Displays 1.2 value = 123; Console::WriteLine(value.ToString("#####")); Console::WriteLine(String::Format("{0:#####}", value)); // Displays 123 value = 123456; Console::WriteLine(value.ToString("[##-##-##]")); Console::WriteLine(String::Format("{0:[##-##-##]}", value)); // Displays [12-34-56] value = 1234567890; Console::WriteLine(value.ToString("#")); Console::WriteLine(String::Format("{0:#}", value)); // Displays 1234567890 Console::WriteLine(value.ToString("(###) ###-####")); Console::WriteLine(String::Format("{0:(###) ###-####}", value)); // Displays (123) 456-7890 // </Snippet2> } void ShowDecimalPoint() { // <Snippet3> double value; value = 1.2; Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.00}", value)); // Displays 1.20 Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:00.00}", value)); // Displays 01.20 Console::WriteLine(value.ToString("00.00", CultureInfo::CreateSpecificCulture("da-DK"))); Console::WriteLine(String::Format(CultureInfo::CreateSpecificCulture("da-DK"), "{0:00.00}", value)); // Displays 01,20 value = .086; Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#0.##%}", value)); // Displays 8.6% value = 86000; Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E+0}", value)); // Displays 8.6E+4 // </Snippet3> } void ShowThousandSpecifier() { // <Snippet4> double value = 1234567890; Console::WriteLine(value.ToString("#,#", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,#}", value)); // Displays 1,234,567,890 Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,##0,,}", value)); // Displays 1,235 // </Snippet4> } void ShowScalingSpecifier() { // <Snippet5> double value = 1234567890; Console::WriteLine(value.ToString("#,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,,}", value)); // Displays 1235 Console::WriteLine(value.ToString("#,,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,,,}", value)); // Displays 1 Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#,##0,,}", value)); // Displays 1,235 // </Snippet5> } void ShowPercentagePlaceholder() { // <Snippet6> double value = .086; Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:#0.##%}", value)); // Displays 8.6% // </Snippet6> } void ShowScientificNotation() { // <Snippet7> double value = 86000; Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E+0}", value)); // Displays 8.6E+4 Console::WriteLine(value.ToString("0.###E+000", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E+000}", value)); // Displays 8.6E+004 Console::WriteLine(value.ToString("0.###E-000", CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:0.###E-000}", value)); // Displays 8.6E004 // </Snippet7> } void ShowSectionSpecifier() { // <Snippet8> double posValue = 1234; double negValue = -1234; double zeroValue = 0; String^ fmt2 = "##;(##)"; String^ fmt3 = "##;(##);**Zero**"; Console::WriteLine(posValue.ToString(fmt2)); Console::WriteLine(String::Format("{0:" + fmt2 + "}", posValue)); // Displays 1234 Console::WriteLine(negValue.ToString(fmt2)); Console::WriteLine(String::Format("{0:" + fmt2 + "}", negValue)); // Displays (1234) Console::WriteLine(zeroValue.ToString(fmt3)); Console::WriteLine(String::Format("{0:" + fmt3 + "}", zeroValue)); // Displays **Zero** // </Snippet8> } void ShowPerMillePlaceholder() { // <Snippet9> double value = .00354; String^ perMilleFmt = "#0.## " + '\u2030'; Console::WriteLine(value.ToString(perMilleFmt, CultureInfo::InvariantCulture)); Console::WriteLine(String::Format(CultureInfo::InvariantCulture, "{0:" + perMilleFmt + "}", value)); // Displays 3.54‰ // </Snippet9> } void main() { Console::WriteLine("Zero Placeholder:"); ShowZeroPlaceholder(); Console::WriteLine(); Console::WriteLine("Digit Placeholder:"); ShowDigitPlaceholder(); Console::WriteLine(); Console::WriteLine("Decimal Point:"); ShowDecimalPoint(); Console::WriteLine(); Console::WriteLine("Thousand Specifier:"); ShowThousandSpecifier(); Console::WriteLine(); Console::WriteLine("Scaling Specifier:"); ShowScalingSpecifier(); Console::WriteLine(); Console::WriteLine("Percentage Placeholder:"); ShowPercentagePlaceholder(); Console::WriteLine(); Console::WriteLine("Scientific Notation:"); ShowScientificNotation(); Console::WriteLine(); Console::WriteLine("Section Specifier:"); ShowSectionSpecifier(); Console::WriteLine(); Console::WriteLine("Per Mille Placeholder:"); ShowPerMillePlaceholder(); }
34.587121
88
0.584273
BaruaSourav
cb8f5f99ee52b47d12b2b22e88ec05420a77959c
1,226
cpp
C++
imap/src/protocol/StoreResponseParser.cpp
webOS-ports/mojomail
49358ac2878e010f5c6e3bd962f047c476c11fc3
[ "Apache-2.0" ]
6
2015-01-09T02:20:27.000Z
2021-01-02T08:14:23.000Z
mojomail/imap/src/protocol/StoreResponseParser.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
3
2019-05-11T19:17:56.000Z
2021-11-24T16:04:36.000Z
mojomail/imap/src/protocol/StoreResponseParser.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
6
2015-01-09T02:21:13.000Z
2021-01-02T02:37:10.000Z
// @@@LICENSE // // Copyright (c) 2010-2013 LG Electronics, 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. // // LICENSE@@@ #include "protocol/StoreResponseParser.h" StoreResponseParser::StoreResponseParser(ImapSession& session, DoneSignal::SlotRef doneSlot) : ImapResponseParser(session, doneSlot), m_responsesLeft(0) { } StoreResponseParser::~StoreResponseParser() { } void StoreResponseParser::HandleResponse(ImapStatusCode status, const std::string& response) { // FIXME handle errors m_responsesLeft--; } void StoreResponseParser::AddExpectedResponse() { m_responsesLeft++; } void StoreResponseParser::Done() { if(m_responsesLeft < 1 || m_status == STATUS_EXCEPTION) m_doneSignal.fire(); }
26.085106
92
0.750408
webOS-ports
cb921de5fe541c257bb94857dfbcc47a3e146bf7
984
cpp
C++
src/scripting/Sandbox.cpp
AlxAce/CyberEngineTweaks
3b1d2dba1717a69eae1972497dbde1952fef6d47
[ "MIT" ]
null
null
null
src/scripting/Sandbox.cpp
AlxAce/CyberEngineTweaks
3b1d2dba1717a69eae1972497dbde1952fef6d47
[ "MIT" ]
null
null
null
src/scripting/Sandbox.cpp
AlxAce/CyberEngineTweaks
3b1d2dba1717a69eae1972497dbde1952fef6d47
[ "MIT" ]
null
null
null
#include <stdafx.h> #include "Sandbox.h" #include "Scripting.h" Sandbox::Sandbox(Scripting* apScripting, sol::environment aBaseEnvironment, const std::filesystem::path& acRootPath) : m_pScripting(apScripting) , m_env(apScripting->GetState().Get(), sol::create) , m_path(acRootPath) { // copy base environment, do not set it as fallback, as it may cause globals to bleed into other things! for (const auto& cKV : aBaseEnvironment) m_env[cKV.first].set(cKV.second.as<sol::object>()); } sol::protected_function_result Sandbox::ExecuteFile(const std::string& acPath) const { return m_pScripting->GetState().Get().script_file(acPath, m_env); } sol::protected_function_result Sandbox::ExecuteString(const std::string& acString) const { return m_pScripting->GetState().Get().script(acString, m_env); } sol::environment& Sandbox::GetEnvironment() { return m_env; } const std::filesystem::path& Sandbox::GetRootPath() const { return m_path; }
28.114286
116
0.723577
AlxAce
cb923eaa13a4528dda916d9bd8bfb0930d92e117
3,031
cpp
C++
NEERC/Subregionals/2010-2011/C/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
2
2018-11-08T05:57:22.000Z
2018-11-08T05:57:27.000Z
NEERC/Subregionals/2010-2011/C/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
NEERC/Subregionals/2010-2011/C/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
#define __USE_MINGW_ANSI_STDIO 0 #include<bits/stdc++.h> using namespace std; #define PI acos(-1) #define pb push_back #define fi first #define se second #define TASK "commuting" #define sz(a) (int)(a).size() #define all(c) (c).begin(), (c).end() #define TIMESTAMP fprintf(stderr, "Execution time: %.3lf s.\n", (double)clock()/CLOCKS_PER_SEC) typedef long long ll; typedef long double ld; typedef vector <int> vi; typedef vector <ll> vll; typedef pair <int, int> pii; typedef vector <vi> vvi; typedef vector <pii> vpii; typedef vector <string> vs; const int MAXN = 2e5 + 9; const int MOD = (int)(1e9 + 7); const int INF = 1e9; int gg[MAXN], rr[MAXN]; int n; int ans[MAXN]; int T[MAXN]; int cnt = 0; int tmp[MAXN], posTmp; mt19937_64 rnd(chrono::high_resolution_clock::now().time_since_epoch().count()); void input() { cin >> n; for(int i = 1; i <= n; i++) { int x; cin >> x; gg[i] = x; rr[x] = i; } } void go(int pos) { if(pos == n + 1) { cnt++; bool ok = 1; for(int i = 1; i <= n; i++) if(T[i] < ans[i]) ok = 0; else if(ok && ans[i] < T[i]) { return; } for(int i = 1; i <= n; i++) { if(gg[T[i]] != T[gg[i]]) return; } if(!ok) { cout << " found " << endl; cout << " input " << endl; for(int i = 1; i <= n; i++) cout << gg[i] << ' '; cout << endl; cout << " ans " << endl; for(int i = 1; i <= n; i++) cout << ans[i] << ' '; cout << endl; cout << " bettter ans " << endl; for(int i = 1; i <= n; i++) cout << T[i] << ' '; cout << endl; cout << " checking " << endl; for(int i = 1; i <= n; i++) cout << gg[T[i]] - T[gg[i]] << ' '; cout << endl; exit(0); } return; } for(int i = 1; i <= n; i++) { T[pos] = i; go(pos + 1); } } void solve() { memset(ans, -1, sizeof(ans)); vi cycles(n + 1, INF); vi used(n + 1, 0); for(int i = 1; i <= n; i++) { if(used[i]) continue; posTmp = 0; tmp[posTmp++] = gg[i]; int v = gg[gg[i]]; while(v != gg[i]) { used[v] = 1; tmp[posTmp++] = v; v = gg[v]; } int curMin = *min_element(tmp, tmp + posTmp); cycles[posTmp] = min(cycles[posTmp], curMin); } for(int i = 1; i <= n; i++) { if(ans[i] != -1) continue; posTmp = 0; tmp[posTmp++] = gg[i]; int v = gg[gg[i]]; while(v != gg[i]) { tmp[posTmp++] = v; v = gg[v]; } int cur = INF; cerr << i << ' ' << posTmp << endl; TIMESTAMP; for(int j = 1; j <= posTmp; j++) if(posTmp % j == 0) cur = min(cur, cycles[j]); for(int j = 0; j < posTmp; j++) { ans[rr[tmp[j]]] = cur; cur = gg[cur]; } } for(int i = 1; i <= n; i++) assert(ans[gg[i]] == gg[ans[i]]); //go(1); for(int i = 1; i <= n; i++) cout << ans[i] << ' '; cout << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); #ifdef LOCAL freopen("xxx.in", "r", stdin); freopen("xxx.out", "w", stdout); #else freopen(TASK".in", "r", stdin); freopen(TASK".out", "w", stdout); #endif input(); solve(); #ifdef LOCAL TIMESTAMP; #endif return 0; }
20.206667
95
0.509733
Zovube
cb9360ba1b46f7dbb3d672f5808f37bfdb08724b
266
cpp
C++
source/tm/constant_generation.cpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
7
2021-03-05T16:50:19.000Z
2022-02-02T04:30:07.000Z
source/tm/constant_generation.cpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
47
2021-02-01T18:54:23.000Z
2022-03-06T19:06:16.000Z
source/tm/constant_generation.cpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
1
2021-01-28T13:10:41.000Z
2021-01-28T13:10:41.000Z
// Handles challenges / current battles // Copyright David Stone 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <tm/constant_generation.hpp>
33.25
61
0.763158
davidstone
cb98c32601e70e620f0b17364d4492831bda8af3
871
cpp
C++
Chapter10/10_3.cpp
GeertArien/c-accelerated
c0ae9f66b1733de04f3133db2e9d8af6d555fe6e
[ "MIT" ]
27
2019-03-12T02:24:43.000Z
2022-02-18T22:49:00.000Z
Chapter10/10_3.cpp
GeertArien/C-Accelerated
c0ae9f66b1733de04f3133db2e9d8af6d555fe6e
[ "MIT" ]
1
2020-06-24T18:34:45.000Z
2020-06-28T12:55:05.000Z
Chapter10/10_3.cpp
GeertArien/c-accelerated
c0ae9f66b1733de04f3133db2e9d8af6d555fe6e
[ "MIT" ]
12
2019-04-22T03:49:19.000Z
2021-08-31T17:39:35.000Z
/** Accelerated C++, Exercise 10-3, 10_3.cpp Write a test program to verify that the median function operates correctly. Ensure that calling median does not change the order of the elements in the container. */ #include "stdafx.h" #include "10_3.h" #include "10_2.h" #include <vector> using std::vector; #include <iostream> using std::cout; using std::endl; using std::ostream; template<class T> ostream& print_vector(const vector<T> v, ostream& os) { if (v.size() > 0) { os << v[0]; for (vector<T>::size_type i = 1; i < v.size(); i++) os << ", " << v[i]; os << endl; } return os; } int ex10_3() { vector<double> v_double = { 12.5, 5.25, 25.7, 16.3, 1.26 }; print_vector(v_double, cout); cout << median<double, vector<double>::iterator>(v_double.begin(), v_double.end()) << endl; print_vector(v_double, cout); return 0; }
18.145833
93
0.641791
GeertArien
cb9910fa098641be0c52b70076718f3aad44d7ac
389
cpp
C++
uva/10298.cpp
larc/competitive_programming
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
1
2019-05-23T19:05:39.000Z
2019-05-23T19:05:39.000Z
uva/10298.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
uva/10298.cpp
larc/oremor
deccd7152a14adf217c58546d1cf8ac6b45f1c52
[ "MIT" ]
null
null
null
// 10298 - Power Strings #include <cstdio> #define N 1000001 int main() { int i, j; int b[N]; char str[N]; while(scanf("%s", str), str[0] != '.') { // KMP algorithm i = 0; j = -1; b[0] = -1; while(str[i]) { while(j >= 0 && str[i] != str[j]) j = b[j]; i++; j++; b[i] = j; } if(i % (i - j)) printf("1\n"); else printf("%d\n", i / (i - j)); } return 0; }
12.548387
46
0.44473
larc
ed80a4dddec6ede720ff4cb69f5cb4a2a23bec1e
5,630
hpp
C++
include/System/__Filters.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/__Filters.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/System/__Filters.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Reflection namespace System::Reflection { // Forward declaring type: MemberInfo class MemberInfo; } // Completed forward declares // Type namespace: System namespace System { // Forward declaring type: __Filters class __Filters; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::__Filters); DEFINE_IL2CPP_ARG_TYPE(::System::__Filters*, "System", "__Filters"); // Type namespace: System namespace System { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.__Filters // [TokenAttribute] Offset: FFFFFFFF class __Filters : public ::Il2CppObject { public: // Get static field: static readonly System.__Filters Instance static ::System::__Filters* _get_Instance(); // Set static field: static readonly System.__Filters Instance static void _set_Instance(::System::__Filters* value); // static private System.Void .cctor() // Offset: 0x298CE34 static void _cctor(); // System.Boolean FilterAttribute(System.Reflection.MemberInfo m, System.Object filterCriteria) // Offset: 0x298C794 bool FilterAttribute(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria); // System.Boolean FilterName(System.Reflection.MemberInfo m, System.Object filterCriteria) // Offset: 0x298CAEC bool FilterName(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria); // System.Boolean FilterIgnoreCase(System.Reflection.MemberInfo m, System.Object filterCriteria) // Offset: 0x298CC84 bool FilterIgnoreCase(::System::Reflection::MemberInfo* m, ::Il2CppObject* filterCriteria); // public System.Void .ctor() // Offset: 0x298CE2C // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static __Filters* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::__Filters::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<__Filters*, creationType>())); } }; // System.__Filters #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::__Filters::_cctor // Il2CppName: .cctor template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::__Filters::_cctor)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::__Filters*), ".cctor", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::__Filters::FilterAttribute // Il2CppName: FilterAttribute template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterAttribute)> { static const MethodInfo* get() { static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg; static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterAttribute", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria}); } }; // Writing MetadataGetter for method: System::__Filters::FilterName // Il2CppName: FilterName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterName)> { static const MethodInfo* get() { static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg; static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria}); } }; // Writing MetadataGetter for method: System::__Filters::FilterIgnoreCase // Il2CppName: FilterIgnoreCase template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::__Filters::*)(::System::Reflection::MemberInfo*, ::Il2CppObject*)>(&System::__Filters::FilterIgnoreCase)> { static const MethodInfo* get() { static auto* m = &::il2cpp_utils::GetClassFromName("System.Reflection", "MemberInfo")->byval_arg; static auto* filterCriteria = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::__Filters*), "FilterIgnoreCase", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{m, filterCriteria}); } }; // Writing MetadataGetter for method: System::__Filters::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
52.616822
191
0.717584
RedBrumbler
ed81d0c8516309b107e0070d82087c6017d6cee0
371
cpp
C++
MDE/Object.cpp
dmitriyha/Magic-Dungeon-Epidemic
37d19f416d36f1abb2393af1e43f76b24f57001a
[ "Unlicense" ]
null
null
null
MDE/Object.cpp
dmitriyha/Magic-Dungeon-Epidemic
37d19f416d36f1abb2393af1e43f76b24f57001a
[ "Unlicense" ]
null
null
null
MDE/Object.cpp
dmitriyha/Magic-Dungeon-Epidemic
37d19f416d36f1abb2393af1e43f76b24f57001a
[ "Unlicense" ]
null
null
null
#include "Object.h" Object::Object() { } void Object::render(){ SDL_RenderCopy(texture->getRenderer(), texture->getTexture(), &sprite, &location); } /** \brief Sets the texture to the character * * \param Texture* _texture: The texture which you want to set to character * */ void Object::setTexture(Texture* _texture){ texture = _texture; } Object::~Object() { }
15.458333
83
0.695418
dmitriyha
ed82443b297dd63ffca152b82387e03252605e84
1,597
cpp
C++
src/Core/Service/ServerHandler.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
6
2017-08-07T07:01:48.000Z
2022-02-27T20:58:44.000Z
src/Core/Service/ServerHandler.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
18
2017-08-10T20:34:50.000Z
2017-09-05T19:48:52.000Z
src/Core/Service/ServerHandler.cpp
Loki-Astari/ThorsNisse
75fd6891959d6e9deb7c07cb26660e65ba7f51bd
[ "MIT" ]
1
2019-02-20T19:06:13.000Z
2019-02-20T19:06:13.000Z
#include "Handler.h" #include "ServerHandler.h" using namespace ThorsAnvil::Nisse::Core::Service; TimerHandler::TimerHandler(Server& parent, double timeOut, std::function<void()>&& action) : HandlerNonSuspendable(parent, -1, EV_PERSIST, timeOut) , action(std::move(action)) {} short TimerHandler::eventActivate(LibSocketId /*sockId*/, short /*eventType*/) { action(); return 0; } #ifdef COVERAGE_TEST /* * This code is only compiled into the unit tests for code coverage purposes * It is not part of the live code. */ #include "ServerHandler.tpp" #include "test/Action.h" #include "ThorsNisseCoreSocket/Socket.h" template ThorsAnvil::Nisse::Core::Service::ServerHandler<Action, void>::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&); template ThorsAnvil::Nisse::Core::Service::ServerHandler<ActionUnReg, void>::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&); template ThorsAnvil::Nisse::Core::Service::ServerHandler<TestHandler, std::tuple<bool, bool, bool> >::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&, std::tuple<bool, bool, bool>&); template ThorsAnvil::Nisse::Core::Service::ServerHandler<InHandlerTest, std::tuple<bool, std::function<void (ThorsAnvil::Nisse::Core::Service::Server&)> > >::ServerHandler(ThorsAnvil::Nisse::Core::Service::Server&, ThorsAnvil::Nisse::Core::Socket::ServerSocket&&, std::tuple<bool, std::function<void (ThorsAnvil::Nisse::Core::Service::Server&)> >&); #endif
51.516129
349
0.745147
Loki-Astari
ed832226bf229488cd6137fb15495fac5b35ec54
5,182
cpp
C++
src/master/RejudgeJob/RejudgeJobBase.cpp
WentsingNee/tsoj_core_cpp
8a83d6cc81c247a1299da207ac54b62419b75bab
[ "MIT" ]
1
2019-03-08T06:15:52.000Z
2019-03-08T06:15:52.000Z
src/master/RejudgeJob/RejudgeJobBase.cpp
WentsingNee/tsoj_core_cpp
8a83d6cc81c247a1299da207ac54b62419b75bab
[ "MIT" ]
null
null
null
src/master/RejudgeJob/RejudgeJobBase.cpp
WentsingNee/tsoj_core_cpp
8a83d6cc81c247a1299da207ac54b62419b75bab
[ "MIT" ]
null
null
null
/* * RejudgeJobBase.cpp * * Created on: 2018年11月20日 * Author: peter */ #include "RejudgeJobBase.hpp" #include "logger.hpp" #ifndef MYSQLPP_MYSQL_HEADERS_BURIED # define MYSQLPP_MYSQL_HEADERS_BURIED #endif #include <mysql++/transaction.h> #include <mysql_conn_factory.hpp> extern std::ofstream log_fp; RejudgeJobBase::RejudgeJobBase(int jobType, ojv4::s_id_type s_id, kerbal::redis_v2::connection & redis_conn) : UpdateJobBase(jobType, s_id, redis_conn), rejudge_time(mysqlpp::DateTime::now()) { LOG_DEBUG(jobType, s_id, log_fp, BOOST_CURRENT_FUNCTION); } void RejudgeJobBase::handle() { LOG_DEBUG(jobType, s_id, log_fp, BOOST_CURRENT_FUNCTION); std::exception_ptr move_solution_exception = nullptr; std::exception_ptr update_solution_exception = nullptr; std::exception_ptr update_compile_error_info_exception = nullptr; std::exception_ptr update_user_exception = nullptr; std::exception_ptr update_problem_exception = nullptr; std::exception_ptr update_user_problem_exception = nullptr; std::exception_ptr update_user_problem_status_exception = nullptr; std::exception_ptr commit_exception = nullptr; // 本次更新任务的 mysql 连接 auto mysql_conn_handle = sync_fetch_mysql_conn(); mysqlpp::Connection & mysql_conn = *mysql_conn_handle; mysqlpp::Transaction trans(mysql_conn); try { this->move_orig_solution_to_rejudge_solution(mysql_conn); } catch (const std::exception & e) { move_solution_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Move original solution failed!", e); //DO NOT THROW } if (move_solution_exception == nullptr) { try { this->update_solution(mysql_conn); } catch (const std::exception & e) { move_solution_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update solution failed!", e); //DO NOT THROW } if (update_solution_exception == nullptr) { try { this->update_compile_info(mysql_conn); } catch (const std::exception & e) { update_compile_error_info_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update compile error info failed!", e); //DO NOT THROW } try { this->update_user(mysql_conn); } catch (const std::exception & e) { update_user_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update user failed!", e); //DO NOT THROW } try { this->update_problem(mysql_conn); } catch (const std::exception & e) { update_problem_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update problem failed!", e); //DO NOT THROW } try { this->update_user_problem(mysql_conn); } catch (const std::exception & e) { update_user_problem_exception = std::current_exception(); EXCEPT_FATAL(jobType, s_id, log_fp, "Update user problem failed!", e); //DO NOT THROW } // try { // this->update_user_problem_status(mysql_conn); // } catch (const std::exception & e) { // update_user_problem_status_exception = std::current_exception(); // EXCEPT_FATAL(jobType, s_id, log_fp, "Update user problem status failed!", e); // //DO NOT THROW // } try { this->send_rejudge_notification(mysql_conn); } catch (const std::exception & e){ EXCEPT_WARNING(jobType, s_id, log_fp, "Send rejudge notification failed!", e); //DO NOT THROW } } try { trans.commit(); } catch (const std::exception & e) { EXCEPT_FATAL(jobType, s_id, log_fp, "MySQL commit failed!", e); commit_exception = std::current_exception(); //DO NOT THROW } catch (...) { UNKNOWN_EXCEPT_FATAL(jobType, s_id, log_fp, "MySQL commit failed!"); commit_exception = std::current_exception(); //DO NOT THROW } } this->clear_redis_info(); } void RejudgeJobBase::clear_redis_info() noexcept try { this->UpdateJobBase::clear_this_jobs_info_in_redis(); auto redis_conn_handler = sync_fetch_redis_conn(); kerbal::redis_v2::operation opt(*redis_conn_handler); try { boost::format judge_status_templ("judge_status:%d:%d"); if (opt.del((judge_status_templ % jobType % s_id).str()) == false) { LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete judge_status actually!"); } } catch (const std::exception & e) { LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting judge_status!"); //DO NOT THROW } try { boost::format similarity_details("similarity_details:%d:%d"); if (opt.del((similarity_details % jobType % s_id).str()) == false) { // LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete similarity_details actually!"); } } catch (const std::exception & e) { LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting similarity_details!"); //DO NOT THROW } try { boost::format job_info("job_info:%d:%d"); if (opt.del((job_info % jobType % s_id).str()) == false) { // LOG_WARNING(jobType, s_id, log_fp, "Doesn't delete job_info actually!"); } } catch (const std::exception & e) { LOG_WARNING(jobType, s_id, log_fp, "Exception occurred while deleting job_info!"); //DO NOT THROW } } catch (...) { UNKNOWN_EXCEPT_FATAL(jobType, s_id, log_fp, "Clear this jobs info in redis failed!"); }
30.662722
110
0.710922
WentsingNee
ed8570b4c3ce9ed25904a28725f3e759ad4832b4
4,734
cpp
C++
hphp/runtime/vm/jit/stack-overflow.cpp
jmurret/hhvm
f005fa3ca2793291cf59e217db3e9ce074d22f71
[ "PHP-3.01", "Zend-2.0" ]
1
2020-01-17T02:24:38.000Z
2020-01-17T02:24:38.000Z
hphp/runtime/vm/jit/stack-overflow.cpp
jmurret/hhvm
f005fa3ca2793291cf59e217db3e9ce074d22f71
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/jit/stack-overflow.cpp
jmurret/hhvm
f005fa3ca2793291cf59e217db3e9ce074d22f71
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | [email protected] so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/stack-overflow.h" #include "hphp/runtime/base/exceptions.h" #include "hphp/runtime/base/typed-value.h" #include "hphp/runtime/vm/bytecode.h" #include "hphp/runtime/vm/func.h" #include "hphp/runtime/vm/hhbc.h" #include "hphp/runtime/vm/hhbc-codec.h" #include "hphp/runtime/vm/unit.h" #include "hphp/runtime/vm/unwind.h" #include "hphp/runtime/vm/vm-regs.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/util/assertions.h" namespace HPHP { namespace jit { /////////////////////////////////////////////////////////////////////////////// bool checkCalleeStackOverflow(const TypedValue* calleeFP, const Func* callee) { auto const limit = callee->maxStackCells() + kStackCheckPadding; const void* const needed_top = calleeFP - limit; const void* const lower_limit = static_cast<char*>(vmRegsUnsafe().stack.getStackLowAddress()) + Stack::sSurprisePageSize; return needed_top < lower_limit; } void handleStackOverflow(ActRec* calleeAR) { // We didn't finish setting up the prologue, so let the unwinder know that // locals are already freed so it doesn't try to decref the garbage. Do not // bother decrefing numArgs, as we are going to fail the request anyway. calleeAR->setLocalsDecRefd(); // sync_regstate in unwind-itanium.cpp doesn't have enough context to properly // sync registers, so do it here. Sync them to correspond to the state on // function entry. This is not really true, but it's good enough for unwinder. auto& unsafeRegs = vmRegsUnsafe(); unsafeRegs.fp = calleeAR; unsafeRegs.pc = calleeAR->func()->getEntry(); unsafeRegs.stack.top() = reinterpret_cast<TypedValue*>(calleeAR) - calleeAR->func()->numSlotsInFrame(); unsafeRegs.jitReturnAddr = nullptr; tl_regState = VMRegState::CLEAN; throw_stack_overflow(); } void handlePossibleStackOverflow(ActRec* calleeAR) { assert_native_stack_aligned(); // If it's not an overflow, it was probably a surprise flag trip. But we // can't assert that it is because background threads are allowed to clear // surprise bits concurrently, so it could be cleared again by now. auto const calleeFP = reinterpret_cast<const TypedValue*>(calleeAR); if (!checkCalleeStackOverflow(calleeFP, calleeAR->func())) return; /* * Stack overflows in this situation are a slightly different case than * handleStackOverflow: * * A function prologue already did all the work to prepare to enter the * function, but then it found out it didn't have enough room on the stack. * It may even have written uninits deeper than the stack base (but we limit * it to sSurprisePageSize, so it's harmless). * * Most importantly, it might have pulled args /off/ the eval stack and * shoved them into an array for a variadic capture param. We need to get * things into an appropriate state for handleStackOverflow to be able to * synchronize things to throw from the PC of the caller's FCall. * * We don't actually need to make sure the stack is the right depth for the * FCall: the unwinder will expect to see a pre-live ActRec (and we'll set it * up so it will), but it doesn't care how many args (or what types of args) * are below it on the stack. * * So, all that boils down to this: we set calleeAR->m_numArgs to indicate * how many things are actually on the stack (so handleStackOverflow knows * what to set the vmsp to)---we just set it to the function's numLocals, * which might mean decreffing some uninits unnecessarily, but that's ok. */ calleeAR->setNumArgs(calleeAR->m_func->numLocals()); handleStackOverflow(calleeAR); } /////////////////////////////////////////////////////////////////////////////// }}
43.833333
82
0.635192
jmurret
ed8953dbe4132319a7738c97bc09a74f76558e7c
4,437
cpp
C++
Rocket/Engine/FileSystem/OsFileSync.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
Rocket/Engine/FileSystem/OsFileSync.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
Rocket/Engine/FileSystem/OsFileSync.cpp
rocketman123456/RocketEngine
ede1670d70c4689a5dc8543ca5351e8f23fcb840
[ "Apache-2.0" ]
null
null
null
#include "FileSystem/OsFileSync.h" #include "Log/Log.h" #include <exception> namespace Rocket { int32_t OsFileSync::Initialize(const std::string& path, const std::string& file_name, FileOperateMode mode) { mode_ = mode; file_.file_path = path; file_.file_name = file_name; file_.full_name = path + file_name; return Initialize(file_.full_name.data(), mode_); } int32_t OsFileSync::Initialize(const std::string& path, FileOperateMode mode) { mode_ = mode; file_.full_name = path; switch(mode_) { case FileOperateMode::READ_BINARY: file_.file_pointer = (void*)fopen(file_.full_name.data(), "rb"); break; case FileOperateMode::WRITE_BINARY: file_.file_pointer = (void*)fopen(file_.full_name.data(), "wb"); break; case FileOperateMode::READ_TEXT: file_.file_pointer = (void*)fopen(file_.full_name.data(), "r"); break; case FileOperateMode::WRITE_TEXT: file_.file_pointer = (void*)fopen(file_.full_name.data(), "w"); break; default: break; }; SeekToEnd(); file_.total_size = Tell(); Seek(0); initialized_ = true; RK_TRACE(File, "Open File {} Success", file_.full_name); if(file_.file_pointer == nullptr) return 1; else return 0; } void OsFileSync::Finalize() { if(file_.file_pointer != nullptr) fclose((FILE*)file_.file_pointer); if(file_.extra_file_info != nullptr) delete file_.extra_file_info; initialized_ = false; } std::size_t OsFileSync::Read(FileBuffer& buffer, std::size_t length) { if(mode_ == FileOperateMode::READ_BINARY) { buffer.size = length; buffer.buffer = new uint8_t[length]; auto result = fread(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer); if(result == 1) return length; else return 0; } else if(mode_ == FileOperateMode::READ_TEXT) { buffer.size = length + 1; buffer.buffer = new uint8_t[length + 1]; auto result = fread(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer); static_cast<char*>(buffer.buffer)[length] = '\0'; if(result == 0) return buffer.size; else return 0; } else { return 0; } } std::size_t OsFileSync::ReadAll(FileBuffer& buffer) { if(mode_ == FileOperateMode::READ_BINARY || mode_ == FileOperateMode::READ_TEXT) return Read(buffer, file_.total_size); else return 0; } std::size_t OsFileSync::Write(FileBuffer& buffer, std::size_t length) { std::size_t real_length = 0; if(length == 0 || length > buffer.size) real_length = buffer.size; else real_length = length; auto result = fwrite(buffer.buffer, real_length, 1, (FILE*)file_.file_pointer); if(result == 1) return length; else return 0; } std::size_t OsFileSync::WriteAll(FileBuffer& buffer) { auto result = fwrite(buffer.buffer, buffer.size, 1, (FILE*)file_.file_pointer); if(result == 1) return buffer.size; else return 0; } void OsFileSync::Seek(std::size_t position) { auto result = fseek((FILE*)file_.file_pointer, position, SEEK_SET); if(result != 0) { RK_ERROR(File, "{} File Seek {} Error", file_.full_name, position); throw std::runtime_error("File Seek Error"); } } void OsFileSync::SeekToEnd(void) { auto result = fseek((FILE*)file_.file_pointer, 0, SEEK_END); if(result != 0) { RK_ERROR(File, "{} File Seek End Error", file_.full_name); throw std::runtime_error("File Seek End Error"); } } void OsFileSync::Skip(std::size_t bytes) { auto result = fseek((FILE*)file_.file_pointer, bytes, SEEK_CUR); if(result != 0) { RK_ERROR(File, "{} File Skip {} Error", file_.full_name); throw std::runtime_error("File Skip Error"); } } std::size_t OsFileSync::Tell(void) const { std::size_t result = ftell((FILE*)file_.file_pointer); return result; } }
33.360902
119
0.572459
rocketman123456
ed8e6b442228e6aa14ede0f0daa3f79932d78ded
2,756
cpp
C++
src/io/lnk4archive.cpp
HououinKyouma29/impacto
8d4bf2605f54630b1b1cf7dbf3d05e5fd0249c2d
[ "ISC" ]
2
2021-02-08T12:01:16.000Z
2021-07-01T22:54:41.000Z
src/io/lnk4archive.cpp
HououinKyouma29/impacto
8d4bf2605f54630b1b1cf7dbf3d05e5fd0249c2d
[ "ISC" ]
null
null
null
src/io/lnk4archive.cpp
HououinKyouma29/impacto
8d4bf2605f54630b1b1cf7dbf3d05e5fd0249c2d
[ "ISC" ]
null
null
null
#include "lnk4archive.h" #include "../log.h" #include "uncompressedstream.h" #include "vfs.h" #include "../util.h" #include <SDL_endian.h> namespace Impacto { namespace Io { struct Lnk4MetaEntry : FileMeta { int64_t Offset; }; Lnk4Archive::~Lnk4Archive() { if (TOC) delete[] TOC; } IoError Lnk4Archive::Open(FileMeta* file, InputStream** outStream) { Lnk4MetaEntry* entry = (Lnk4MetaEntry*)file; IoError err = UncompressedStream::Create(BaseStream, entry->Offset, entry->Size, outStream); if (err != IoError_OK) { ImpLog(LL_Error, LC_IO, "LNK4 file open failed for file \"%s\" in archive \"%s\"\n", entry->FileName.c_str(), BaseStream->Meta.FileName.c_str()); } return err; } IoError Lnk4Archive::Create(InputStream* stream, VfsArchive** outArchive) { ImpLog(LL_Trace, LC_IO, "Trying to mount \"%s\" as LNK4\n", stream->Meta.FileName.c_str()); Lnk4Archive* result = 0; uint32_t* rawToc = 0; uint32_t offsetBlockSize = 2048; uint32_t blockSize = 1024; uint32_t const magic = 0x4C4E4B34; uint32_t const tocOffset = 8; uint32_t maxFileCount; uint32_t fileCount; uint32_t dataOffset; char fileName[6]; if (ReadBE<uint32_t>(stream) != magic) { ImpLog(LL_Trace, LC_IO, "Not LNK4\n"); goto fail; } dataOffset = ReadLE<uint32_t>(stream); if (dataOffset < tocOffset) { ImpLog(LL_Error, LC_IO, "LNK4 header too short\n"); goto fail; } maxFileCount = (dataOffset - tocOffset) / 8; rawToc = (uint32_t*)ImpStackAlloc(dataOffset - tocOffset); if (stream->Read(rawToc, dataOffset - tocOffset) != dataOffset - tocOffset) goto fail; fileCount = 0; for (uint32_t* it = rawToc; it < rawToc + (maxFileCount * 2); it += 2) { // first file starts at 0 if (SDL_SwapLE32(*it) == 0 && it != rawToc) break; fileCount++; } result = new Lnk4Archive; result->BaseStream = stream; result->NamesToIds.reserve(fileCount); result->IdsToFiles.reserve(fileCount); result->TOC = new Lnk4MetaEntry[fileCount]; for (uint32_t i = 0; i < fileCount; i++) { snprintf(fileName, 6, "%05i", i); result->TOC[i].FileName = fileName; result->TOC[i].Id = i; result->TOC[i].Offset = SDL_SwapLE32(rawToc[i * 2]) * offsetBlockSize + dataOffset; result->TOC[i].Size = SDL_SwapLE32(rawToc[i * 2 + 1]) * blockSize; result->IdsToFiles[i] = &result->TOC[i]; result->NamesToIds[result->TOC[i].FileName] = i; } ImpStackFree(rawToc); result->IsInit = true; *outArchive = result; return IoError_OK; fail: stream->Seek(0, RW_SEEK_SET); if (result) delete result; if (rawToc) ImpStackFree(rawToc); return IoError_Fail; } } // namespace Io } // namespace Impacto
26
77
0.651669
HououinKyouma29
ed938ba7c93d8f0b90d9bd881f8eba96f41b3c08
16,130
cpp
C++
rEFIt_UEFI/entry_scan/legacy.cpp
harperse/CloverBootloader
8d1baad2a62c66aae776cfd45d832399632c299e
[ "BSD-2-Clause" ]
null
null
null
rEFIt_UEFI/entry_scan/legacy.cpp
harperse/CloverBootloader
8d1baad2a62c66aae776cfd45d832399632c299e
[ "BSD-2-Clause" ]
null
null
null
rEFIt_UEFI/entry_scan/legacy.cpp
harperse/CloverBootloader
8d1baad2a62c66aae776cfd45d832399632c299e
[ "BSD-2-Clause" ]
null
null
null
/* * refit/scan/legacy.c * * Copyright (c) 2006-2010 Christoph Pfisterer * 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 Christoph Pfisterer nor the names of the * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <Platform.h> // Only use angled for Platform, else, xcode project won't compile #include "entry_scan.h" #include "../refit/screen.h" #include "../refit/menu.h" #include "../gui/REFIT_MENU_SCREEN.h" #include "../gui/REFIT_MAINMENU_SCREEN.h" #include "../Platform/Volumes.h" #include "../libeg/XTheme.h" #include "../include/OSFlags.h" #ifndef DEBUG_ALL #define DEBUG_SCAN_LEGACY 1 #else #define DEBUG_SCAN_LEGACY DEBUG_ALL #endif #if DEBUG_SCAN_LEGACY == 0 #define DBG(...) #else #define DBG(...) DebugLog(DEBUG_SCAN_LEGACY, __VA_ARGS__) #endif //the function is not in the class and deals always with MainMenu //I made args as pointers to have an ability to call with NULL XBool AddLegacyEntry(IN const XStringW& FullTitle, IN const XStringW& _LoaderTitle, IN REFIT_VOLUME *Volume, IN const XIcon* Image, IN const XIcon* DriveImage, IN char32_t Hotkey, IN XBool CustomEntry) { LEGACY_ENTRY *Entry, *SubEntry; REFIT_MENU_SCREEN *SubScreen; XStringW VolDesc; CHAR16 ShortcutLetter = 0; // INTN i; DBG(" AddLegacyEntry:\n"); DBG(" FullTitle=%ls\n", FullTitle.wc_str()); DBG(" LoaderTitle=%ls\n", _LoaderTitle.wc_str()); DBG(" Volume->LegacyOS->Name=%ls\n", Volume->LegacyOS->Name.wc_str()); if (Volume == NULL) { return false; } // Ignore this loader if it's device path is already present in another loader for (UINTN i = 0; i < MainMenu.Entries.size(); ++i) { REFIT_ABSTRACT_MENU_ENTRY& MainEntry = MainMenu.Entries[i]; // DBG("entry %lld\n", i); // Only want legacy if (MainEntry.getLEGACY_ENTRY()) { if ( MainEntry.getLEGACY_ENTRY()->DevicePathString.isEqualIC(Volume->DevicePathString) ) { return true; } } } XStringW LoaderTitle; if ( _LoaderTitle.isEmpty() ) { LoaderTitle = Volume->LegacyOS->Name; }else{ LoaderTitle = _LoaderTitle; } XStringW LTitle; if (LoaderTitle.isEmpty()) { if (Volume->LegacyOS->Name.notEmpty()) { LTitle.takeValueFrom(Volume->LegacyOS->Name); if (Volume->LegacyOS->Name[0] == 'W' || Volume->LegacyOS->Name[0] == 'L') ShortcutLetter = (wchar_t)Volume->LegacyOS->Name[0]; // cast safe because value is 'W' or 'L' } else LTitle = L"Legacy OS"_XSW; } else LTitle = LoaderTitle; if (Volume->VolName.notEmpty()) VolDesc = Volume->VolName; else VolDesc.takeValueFrom((Volume->DiskKind == DISK_KIND_OPTICAL) ? L"CD" : L"HD"); //DBG("VolDesc=%ls\n", VolDesc); // prepare the menu entry Entry = new LEGACY_ENTRY; if ( FullTitle.notEmpty() ) { Entry->Title = FullTitle; } else { if (ThemeX.BootCampStyle) { Entry->Title = LTitle; } else { Entry->Title.SWPrintf("Boot %ls from %ls", LoaderTitle.wc_str(), VolDesc.wc_str()); } } DBG(" Entry->Title=%ls\n", Entry->Title.wc_str()); Entry->Row = 0; Entry->ShortcutLetter = (Hotkey == 0) ? ShortcutLetter : Hotkey; if ( Image && !Image->isEmpty() ) { Entry->Image = *Image; } else { Entry->Image = ThemeX.LoadOSIcon(Volume->LegacyOS->IconName); if (Entry->Image.Image.isEmpty()) { Entry->Image = ThemeX.GetIcon("os_win"_XS8); //we have no legacy.png } } // DBG("IconName=%ls\n", Volume->LegacyOS->IconName); Entry->DriveImage = (DriveImage != NULL) ? *DriveImage : ScanVolumeDefaultIcon(Volume, Volume->LegacyOS->Type, Volume->DevicePath); // DBG("HideBadges=%d Volume=%ls\n", GlobalConfig.HideBadges, Volume->VolName); // DBG("Title=%ls OSName=%ls OSIconName=%ls\n", LoaderTitle, Volume->OSName, Volume->OSIconName); //actions Entry->AtClick = ActionSelect; Entry->AtDoubleClick = ActionEnter; Entry->AtRightClick = ActionDetails; if (ThemeX.HideBadges & HDBADGES_SHOW) { if (ThemeX.HideBadges & HDBADGES_SWAP) { //will be scaled later Entry->BadgeImage.Image = XImage(Entry->DriveImage.Image, 0); //ThemeX.BadgeScale/16.f); //0 accepted } else { Entry->BadgeImage.Image = XImage(Entry->Image.Image, 0); //ThemeX.BadgeScale/16.f); } } Entry->Volume = Volume; Entry->DevicePathString = Volume->DevicePathString; // Entry->LoadOptions = (Volume->DiskKind == DISK_KIND_OPTICAL) ? "CD"_XS8 : ((Volume->DiskKind == DISK_KIND_EXTERNAL) ? "USB"_XS8 : "HD"_XS8); Entry->LoadOptions.setEmpty(); Entry->LoadOptions.Add((Volume->DiskKind == DISK_KIND_OPTICAL) ? "CD" : ((Volume->DiskKind == DISK_KIND_EXTERNAL) ? "USB" : "HD")); // If this isn't a custom entry make sure it's not hidden by a custom entry if (!CustomEntry) { for (size_t CustomIndex = 0 ; CustomIndex < GlobalConfig.CustomLegacyEntries.size() ; ++CustomIndex ) { CUSTOM_LEGACY_ENTRY& Custom = GlobalConfig.CustomLegacyEntries[CustomIndex]; if ( Custom.settings.Disabled || OSFLAG_ISSET(Custom.getFlags(), OSFLAG_DISABLED) || Custom.settings.Hidden ) { if (Custom.settings.Volume.notEmpty()) { if ( !Volume->DevicePathString.contains(Custom.settings.Volume) && !Volume->VolName.contains(Custom.settings.Volume) ) { if (Custom.settings.Type != 0) { if (Custom.settings.Type == Volume->LegacyOS->Type) { Entry->Hidden = true; } } else { Entry->Hidden = true; } } } else if (Custom.settings.Type != 0) { if (Custom.settings.Type == Volume->LegacyOS->Type) { Entry->Hidden = true; } } } } } // create the submenu SubScreen = new REFIT_MENU_SCREEN; // SubScreen->Title = L"Boot Options for "_XSW + LoaderTitle + L" on "_XSW + VolDesc; SubScreen->Title.SWPrintf("Boot Options for %ls on %ls", LoaderTitle.wc_str(), VolDesc.wc_str()); SubScreen->TitleImage = Entry->Image; //it is XIcon SubScreen->ID = SCREEN_BOOT; SubScreen->GetAnime(); // default entry SubEntry = new LEGACY_ENTRY; SubEntry->Title = L"Boot "_XSW + LoaderTitle; // SubEntry->Tag = TAG_LEGACY; SubEntry->Volume = Entry->Volume; SubEntry->DevicePathString = Entry->DevicePathString; SubEntry->LoadOptions = Entry->LoadOptions; SubEntry->AtClick = ActionEnter; SubScreen->AddMenuEntry(SubEntry, true); SubScreen->AddMenuEntry(&MenuEntryReturn, false); Entry->SubScreen = SubScreen; MainMenu.AddMenuEntry(Entry, true); // DBG(" added '%ls' OSType=%d Icon=%ls\n", Entry->Title, Volume->LegacyOS->Type, Volume->LegacyOS->IconName); return true; } void ScanLegacy(void) { UINTN VolumeIndex, VolumeIndex2; XBool ShowVolume, HideIfOthersFound; REFIT_VOLUME *Volume; DBG("Scanning legacy ...\n"); for (VolumeIndex = 0; VolumeIndex < Volumes.size(); VolumeIndex++) { Volume = &Volumes[VolumeIndex]; // DBG("test VI=%d\n", VolumeIndex); if ((Volume->BootType != BOOTING_BY_PBR) && (Volume->BootType != BOOTING_BY_MBR) && (Volume->BootType != BOOTING_BY_CD)) { // DBG(" not legacy\n"); continue; } // DBG("%2d: '%ls' (%ls)", VolumeIndex, Volume->VolName, Volume->LegacyOS->IconName); #if 0 // REFIT_DEBUG > 0 DBG(" %d %ls\n %d %d %ls %d %ls\n", VolumeIndex, FileDevicePathToStr(Volume->DevicePath), Volume->DiskKind, Volume->MbrPartitionIndex, Volume->IsAppleLegacy ? L"AL" : L"--", Volume->HasBootCode, Volume->VolName ? Volume->VolName : L"(no name)"); #endif // skip volume if its kind is configured as disabled /* if ((Volume->DiskKind == DISK_KIND_OPTICAL && (GlobalConfig.DisableFlags & VOLTYPE_OPTICAL)) || (Volume->DiskKind == DISK_KIND_EXTERNAL && (GlobalConfig.DisableFlags & VOLTYPE_EXTERNAL)) || (Volume->DiskKind == DISK_KIND_INTERNAL && (GlobalConfig.DisableFlags & VOLTYPE_INTERNAL)) || (Volume->DiskKind == DISK_KIND_FIREWIRE && (GlobalConfig.DisableFlags & VOLTYPE_FIREWIRE))) */ if (((1ull<<Volume->DiskKind) & GlobalConfig.DisableFlags) != 0) { // DBG(" hidden\n"); continue; } // DBG("not hidden\n"); ShowVolume = false; HideIfOthersFound = false; if (Volume->IsAppleLegacy) { ShowVolume = true; HideIfOthersFound = true; } else if (Volume->HasBootCode) { ShowVolume = true; // DBG("Volume %d will be shown BlockIo=%X WholeIo=%X\n", // VolumeIndex, Volume->BlockIO, Volume->WholeDiskBlockIO); if ((Volume->WholeDiskBlockIO == 0) && Volume->BlockIOOffset == 0 /* && Volume->OSName == NULL */) // this is a whole disk (MBR) entry; hide if we have entries for partitions HideIfOthersFound = true; // DBG("Hide it!\n"); } if (HideIfOthersFound) { // check for other bootable entries on the same disk //if PBR exists then Hide MBR for (VolumeIndex2 = 0; VolumeIndex2 < Volumes.size(); VolumeIndex2++) { // DBG("what to hide %d\n", VolumeIndex2); if (VolumeIndex2 != VolumeIndex && Volumes[VolumeIndex2].HasBootCode && Volumes[VolumeIndex2].WholeDiskBlockIO == Volume->BlockIO){ ShowVolume = false; // DBG("PBR volume at index %d\n", VolumeIndex2); break; } } } if (ShowVolume && (!Volume->Hidden)){ // DBG(" add legacy\n"); if (!AddLegacyEntry(L""_XSW, L""_XSW, Volume, NULL, NULL, 0, false)) { DBG("...entry not added\n"); }; } else { DBG(" hidden\n"); } } } // Add custom legacy void AddCustomLegacy(void) { UINTN VolumeIndex, VolumeIndex2; XBool ShowVolume, HideIfOthersFound; REFIT_VOLUME *Volume; XIcon MainIcon; XIcon DriveIcon; // DBG("Custom legacy start\n"); if (GlobalConfig.CustomLegacyEntries.notEmpty()) { DbgHeader("AddCustomLegacy"); } // Traverse the custom entries for (size_t i = 0 ; i < GlobalConfig.CustomLegacyEntries.size() ; ++i ) { CUSTOM_LEGACY_ENTRY& Custom = GlobalConfig.CustomLegacyEntries[i]; if (Custom.settings.Disabled || OSFLAG_ISSET(Custom.getFlags(), OSFLAG_DISABLED)) { DBG("Custom legacy %zu skipped because it is disabled.\n", i); continue; } // if (!gSettings.ShowHiddenEntries && OSFLAG_ISSET(Custom.Flags, OSFLAG_HIDDEN)) { // DBG("Custom legacy %llu skipped because it is hidden.\n", i); // continue; // } if (Custom.settings.Volume.notEmpty()) { DBG("Custom legacy %zu matching \"%ls\" ...\n", i, Custom.settings.Volume.wc_str()); } for (VolumeIndex = 0; VolumeIndex < Volumes.size(); ++VolumeIndex) { Volume = &Volumes[VolumeIndex]; DBG(" Checking volume \"%ls\" (%ls) ... ", Volume->VolName.wc_str(), Volume->DevicePathString.wc_str()); // skip volume if its kind is configured as disabled if (((1ull<<Volume->DiskKind) & GlobalConfig.DisableFlags) != 0) { DBG("skipped because media is disabled\n"); continue; } if (Custom.settings.VolumeType != 0) { if (((1ull<<Volume->DiskKind) & Custom.settings.VolumeType) == 0) { DBG("skipped because media is ignored\n"); continue; } } if ((Volume->BootType != BOOTING_BY_PBR) && (Volume->BootType != BOOTING_BY_MBR) && (Volume->BootType != BOOTING_BY_CD)) { DBG("skipped because volume is not legacy bootable\n"); continue; } ShowVolume = false; HideIfOthersFound = false; if (Volume->IsAppleLegacy) { ShowVolume = true; HideIfOthersFound = true; } else if (Volume->HasBootCode) { ShowVolume = true; if ((Volume->WholeDiskBlockIO == 0) && Volume->BlockIOOffset == 0) { // this is a whole disk (MBR) entry; hide if we have entries for partitions HideIfOthersFound = true; } } if (HideIfOthersFound) { // check for other bootable entries on the same disk //if PBR exists then Hide MBR for (VolumeIndex2 = 0; VolumeIndex2 < Volumes.size(); VolumeIndex2++) { if (VolumeIndex2 != VolumeIndex && Volumes[VolumeIndex2].HasBootCode && Volumes[VolumeIndex2].WholeDiskBlockIO == Volume->BlockIO) { ShowVolume = false; break; } } } if ( !ShowVolume ) { DBG("skipped because volume ShowVolume==false\n"); continue; } if ( Volume->Hidden ) { DBG("skipped because volume is hidden\n"); continue; } // Check for exact volume matches if (Custom.settings.Volume.notEmpty()) { if ((StrStr(Volume->DevicePathString.wc_str(), Custom.settings.Volume.wc_str()) == NULL) && ((Volume->VolName.isEmpty()) || (StrStr(Volume->VolName.wc_str(), Custom.settings.Volume.wc_str()) == NULL))) { DBG("skipped\n"); continue; } // Check if the volume should be of certain os type if ((Custom.settings.Type != 0) && (Custom.settings.Type != Volume->LegacyOS->Type)) { DBG("skipped because wrong type\n"); continue; } } else if ((Custom.settings.Type != 0) && (Custom.settings.Type != Volume->LegacyOS->Type)) { DBG("skipped because wrong type\n"); continue; } // Change to custom image if needed MainIcon = Custom.Image; if (MainIcon.Image.isEmpty()) { MainIcon.Image.LoadXImage(&ThemeX.getThemeDir(), Custom.settings.ImagePath); } // Change to custom drive image if needed DriveIcon = Custom.DriveImage; if (DriveIcon.Image.isEmpty()) { DriveIcon.Image.LoadXImage(&ThemeX.getThemeDir(), Custom.settings.DriveImagePath); } // Create a legacy entry for this volume DBG("\n"); if (AddLegacyEntry(Custom.settings.FullTitle, Custom.settings.Title, Volume, &MainIcon, &DriveIcon, Custom.settings.Hotkey, true)) { // DBG("match!\n"); } } } //DBG("Custom legacy end\n"); }
39.05569
202
0.614445
harperse
ed93d24e740d446f00bec865166bd46f1da6ac20
2,308
cpp
C++
src/protocols/kde/decoration.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
src/protocols/kde/decoration.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
src/protocols/kde/decoration.cpp
Link1J/Awning
4e35e092725d1688ac94f8473fb6bffd99a5cfa0
[ "MIT" ]
null
null
null
#include "decoration.hpp" #include <spdlog/spdlog.h> #include "protocols/wl/surface.hpp" namespace Awning::Protocols::KDE::Decoration { const struct org_kde_kwin_server_decoration_interface interface = { .release = Interface::Release, .request_mode = Interface::Request_Mode, }; std::unordered_map<wl_resource*,Instance> instances; namespace Interface { void Release(struct wl_client *client, struct wl_resource *resource) { } void Request_Mode(struct wl_client *client, struct wl_resource *resource, uint32_t mode) { auto surface = instances[resource].surface; WL::Surface::instances[surface].window->Frame(mode == ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER); org_kde_kwin_server_decoration_send_mode(resource, mode); } } wl_resource* Create(struct wl_client* wl_client, uint32_t version, uint32_t id, wl_resource* surface) { struct wl_resource* resource = wl_resource_create(wl_client, &org_kde_kwin_server_decoration_interface, version, id); if (resource == nullptr) { wl_client_post_no_memory(wl_client); return resource; } wl_resource_set_implementation(resource, &interface, nullptr, Destroy); instances[resource].surface = surface; return resource; } void Destroy(struct wl_resource* resource) { } } namespace Awning::Protocols::KDE::Decoration_Manager { const struct org_kde_kwin_server_decoration_manager_interface interface = { .create = Interface::Create, }; namespace Interface { void Create(struct wl_client *client, struct wl_resource *resource, uint32_t id, struct wl_resource *surface) { Decoration::Create(client, 1, id, surface); } } void Bind(struct wl_client* wl_client, void* data, uint32_t version, uint32_t id) { struct wl_resource* resource = wl_resource_create(wl_client, &org_kde_kwin_server_decoration_manager_interface, version, id); if (resource == nullptr) { wl_client_post_no_memory(wl_client); return; } wl_resource_set_implementation(resource, &interface, data, nullptr); org_kde_kwin_server_decoration_manager_send_default_mode(resource, ORG_KDE_KWIN_SERVER_DECORATION_MANAGER_MODE_SERVER); } wl_global* Add(struct wl_display* display, void* data) { return wl_global_create(display, &org_kde_kwin_server_decoration_manager_interface, 1, data, Bind); } }
30.368421
127
0.774263
Link1J
ed95a6a1373036eb62be5e560e77bcba19dc9d94
1,415
cpp
C++
network.cpp
rohith-nagamalla/Ooad_project
ffdc9e34153afe46dbb94061737e92642b186599
[ "Apache-2.0" ]
1
2019-11-28T13:48:45.000Z
2019-11-28T13:48:45.000Z
network.cpp
rohith-nagamalla/Ooad_project
ffdc9e34153afe46dbb94061737e92642b186599
[ "Apache-2.0" ]
null
null
null
network.cpp
rohith-nagamalla/Ooad_project
ffdc9e34153afe46dbb94061737e92642b186599
[ "Apache-2.0" ]
null
null
null
#ifndef network_cpp #define network_cpp #include<bits/stdc++.h> #include "customer.cpp" #include "utilities.cpp" using namespace std; namespace Network { string sms_otp(string name,string number) { string processed_name; for(int i=0;i<name.size() && name[i]!=' ';i++) processed_name.push_back(name[i]); string otp=Utilities::generate_otp(); string command="python3 sms_otp.py "+number+" "+otp+" "+processed_name; cout<<"> Sending OTP.............\n"; system(command.c_str()); fstream file(".junk"); int status; file>>status; if(status==-1) { cout<<"> OTP Sending Faliure. Please Check Your Network And Try Later.\n"; string empty; return empty; } cout<<"> OTP Sent Success\n"; return otp; } string mail_otp(string name,string email) { string processed_name; for(int i=0;i<name.size() && name[i]!=' ';i++) processed_name.push_back(name[i]); string otp=Utilities::generate_otp(); string command="python3 mail_otp.py "+email+" "+otp+" "+processed_name; cout<<"> Sending OTP.............\n"; system(command.c_str()); fstream file(".junk"); int status; file>>status; if(status==-1) { cout<<"> OTP Sending Faliure. Please Check Your Network And Try Later.\n"; string empty; return empty; } cout<<"> OTP Sent Success\n"; return otp; } }; #endif
26.203704
82
0.609894
rohith-nagamalla
ed95f18d3c589af673cf33428c51878f74a78973
8,236
cpp
C++
XivAlexanderLoader/App.cpp
ClarenceShalave/XivAlexander
c0f27cad381a48e097e5476e7cb7e2620b738ca7
[ "Apache-2.0" ]
1
2021-04-07T22:04:37.000Z
2021-04-07T22:04:37.000Z
XivAlexanderLoader/App.cpp
ClarenceShalave/XivAlexander
c0f27cad381a48e097e5476e7cb7e2620b738ca7
[ "Apache-2.0" ]
null
null
null
XivAlexanderLoader/App.cpp
ClarenceShalave/XivAlexander
c0f27cad381a48e097e5476e7cb7e2620b738ca7
[ "Apache-2.0" ]
null
null
null
#include "pch.h" static void* GetModulePointer(HANDLE hProcess, const wchar_t* sDllPath) { Utils::Win32Handle<> th32(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetProcessId(hProcess))); MODULEENTRY32W mod{ sizeof MODULEENTRY32W }; if (!Module32FirstW(th32, &mod)) return nullptr; do { if (_wcsicmp(mod.szExePath, sDllPath) == 0) return mod.modBaseAddr; } while (Module32NextW(th32, &mod)); return nullptr; } static std::wstring GetProcessExecutablePath(HANDLE hProcess) { std::wstring sPath(PATHCCH_MAX_CCH, L'\0'); while (true) { auto length = static_cast<DWORD>(sPath.size()); QueryFullProcessImageNameW(hProcess, 0, &sPath[0], &length); if (length < sPath.size() - 1) { sPath.resize(length); break; } } return sPath; } static int CallRemoteFunction(HANDLE hProcess, void* rpfn, void* rpParam) { Utils::Win32Handle<> hLoadLibraryThread(CreateRemoteThread(hProcess, nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(rpfn), rpParam, 0, nullptr)); WaitForSingleObject(hLoadLibraryThread, INFINITE); DWORD exitCode; GetExitCodeThread(hLoadLibraryThread, &exitCode); return exitCode; } static int InjectDll(HANDLE hProcess, const wchar_t* pszDllPath) { const size_t nDllPathLength = wcslen(pszDllPath) + 1; if (GetModulePointer(hProcess, pszDllPath)) return 0; const auto nNumberOfBytes = nDllPathLength * sizeof pszDllPath[0]; void* rpszDllPath = VirtualAllocEx(hProcess, nullptr, nNumberOfBytes, MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!rpszDllPath) return -1; if (!WriteProcessMemory(hProcess, rpszDllPath, pszDllPath, nNumberOfBytes, nullptr)) { VirtualFreeEx(hProcess, rpszDllPath, 0, MEM_RELEASE); return -1; } const auto exitCode = CallRemoteFunction(hProcess, LoadLibraryW, rpszDllPath); VirtualFreeEx(hProcess, rpszDllPath, 0, MEM_RELEASE); return exitCode; } BOOL SetPrivilege(HANDLE hToken, LPCTSTR Privilege, BOOL bEnablePrivilege) { TOKEN_PRIVILEGES tp; LUID luid; TOKEN_PRIVILEGES tpPrevious; DWORD cbPrevious = sizeof(TOKEN_PRIVILEGES); if (!LookupPrivilegeValue(NULL, Privilege, &luid)) return FALSE; // // first pass. get current privilege setting // tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = 0; AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &tpPrevious, &cbPrevious ); if (GetLastError() != ERROR_SUCCESS) return FALSE; // // second pass. set privilege based on previous setting // tpPrevious.PrivilegeCount = 1; tpPrevious.Privileges[0].Luid = luid; if (bEnablePrivilege) tpPrevious.Privileges[0].Attributes |= (SE_PRIVILEGE_ENABLED); else tpPrevious.Privileges[0].Attributes ^= (SE_PRIVILEGE_ENABLED & tpPrevious.Privileges[0].Attributes); AdjustTokenPrivileges( hToken, FALSE, &tpPrevious, cbPrevious, NULL, NULL); if (GetLastError() != ERROR_SUCCESS) return FALSE; return TRUE; } const char* AddDebugPrivilege() { Utils::Win32Handle<> token; { HANDLE hToken; if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) { if (GetLastError() == ERROR_NO_TOKEN) { if (!ImpersonateSelf(SecurityImpersonation)) return "ImpersonateSelf"; if (!OpenThreadToken(GetCurrentThread(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, FALSE, &hToken)) { return "OpenThreadToken2"; } } else return "OpenThreadToken1"; } token = hToken; } if (!SetPrivilege(token, SE_DEBUG_NAME, TRUE)) return "SetPrivilege"; return nullptr; } void* FindModuleAddress(HANDLE hProcess, const wchar_t* szDllPath) { HMODULE hMods[1024]; DWORD cbNeeded; unsigned int i; bool skip = false; if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) { for (i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { WCHAR szModName[MAX_PATH]; if (GetModuleFileNameExW(hProcess, hMods[i], szModName, MAX_PATH)) { if (wcsncmp(szModName, szDllPath, MAX_PATH) == 0) return hMods[i]; } } } return nullptr; } extern "C" __declspec(dllimport) int __stdcall LoadXivAlexander(void* lpReserved); extern "C" __declspec(dllimport) int __stdcall UnloadXivAlexander(void* lpReserved); int WINAPI wWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nShowCmd ) { struct { bool noask = false; bool noerror = false; } params; int nArgs; LPWSTR *szArgList = CommandLineToArgvW(lpCmdLine, &nArgs); if (nArgs > 1) { for (int i = 1; i < nArgs; i++) { if (wcsncmp(L"/noask", szArgList[i], 6) == 0) params.noask = true; if (wcsncmp(L"/noerror", szArgList[i], 8) == 0) params.noerror = true; } } LocalFree(szArgList); DWORD pid; HWND hwnd = nullptr; wchar_t szDllPath[PATHCCH_MAX_CCH] = { 0 }; GetModuleFileNameW(nullptr, szDllPath, _countof(szDllPath)); PathCchRemoveFileSpec(szDllPath, _countof(szDllPath)); PathCchAppend(szDllPath, _countof(szDllPath), L"XivAlexander.dll"); const auto szDebugPrivError = AddDebugPrivilege(); const std::wstring ProcessName(L"ffxiv_dx11.exe"); bool found = false; while (hwnd = FindWindowExW(nullptr, hwnd, L"FFXIVGAME", nullptr)) { GetWindowThreadProcessId(hwnd, &pid); std::wstring sExePath; try { { Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid)); sExePath = GetProcessExecutablePath(hProcess); } if (sExePath.length() < ProcessName.length() || (0 != sExePath.compare(sExePath.length() - ProcessName.length(), ProcessName.length(), ProcessName))) continue; found = true; void* rpModule; { Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)); rpModule = FindModuleAddress(hProcess, szDllPath); } std::wstring msg; UINT nMsgType; if (rpModule) { msg = Utils::FormatString( L"XivAlexander detected in FFXIV Process (%d:%s)\n" L"Press Yes to try loading again if it hasn't loaded properly,\n" L"Press No to skip,\n" L"Press Cancel to unload.\n" L"\n" L"Note: your anti-virus software will probably classify DLL injection as a malicious action, " L"and you will have to add both XivAlexanderLoader.exe and XivAlexander.dll to exceptions.", static_cast<int>(pid), sExePath.c_str()); nMsgType = (MB_YESNOCANCEL | MB_ICONQUESTION | MB_DEFBUTTON1); } else { msg = Utils::FormatString( L"FFXIV Process found (%d:%s)\n" L"Continue loading XivAlexander into this process?\n" L"\n" L"Note: your anti-virus software will probably classify DLL injection as a malicious action, " L"and you will have to add both XivAlexanderLoader.exe and XivAlexander.dll to exceptions.", static_cast<int>(pid), sExePath.c_str()); nMsgType = (MB_YESNO | MB_DEFBUTTON1); } int response = params.noask ? IDYES : MessageBoxW(nullptr, msg.c_str(), L"XivAlexander Loader", nMsgType); if (response == IDNO) continue; { Utils::Win32Handle<> hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, pid)); rpModule = FindModuleAddress(hProcess, szDllPath); if (response == IDCANCEL && !rpModule) continue; if (!rpModule) { InjectDll(hProcess, szDllPath); rpModule = FindModuleAddress(hProcess, szDllPath); } DWORD loadResult = 0; if (response == IDYES) { loadResult = CallRemoteFunction(hProcess, LoadXivAlexander, nullptr); if (loadResult != 0) { response = IDCANCEL; } } if (response == IDCANCEL) { if (CallRemoteFunction(hProcess, UnloadXivAlexander, nullptr)) { CallRemoteFunction(hProcess, FreeLibrary, rpModule); } } if (loadResult) throw std::exception(Utils::FormatString("Failed to start the addon: %d", loadResult).c_str()); } } catch (std::exception& e) { if (!params.noerror) MessageBoxW(nullptr, Utils::FromUtf8(Utils::FormatString("PID %d: %s\nDebug Privilege: %s", pid, e.what(), szDebugPrivError ? szDebugPrivError : "OK")).c_str(), L"Error", MB_OK | MB_ICONERROR); } } if (!found) { if (!params.noerror) MessageBoxW(nullptr, L"ffxiv_dx11.exe not found", L"Error", MB_OK | MB_ICONERROR); } return 0; }
30.6171
197
0.711875
ClarenceShalave
ed97526dd2144357bba8959470a4c497127b9181
3,029
cpp
C++
src/PE/CodeIntegrity.cpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
2
2021-12-31T07:25:05.000Z
2022-03-05T15:03:00.000Z
src/PE/CodeIntegrity.cpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
null
null
null
src/PE/CodeIntegrity.cpp
ienho/LIEF
29eb867e5fdcd5e11ce22d0c6f16ab27505b1be8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2021 R. Thomas * Copyright 2017 - 2021 Quarkslab * * 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 <numeric> #include <iomanip> #include <sstream> #include "LIEF/PE/hash.hpp" #include "LIEF/PE/Structures.hpp" #include "LIEF/PE/EnumToString.hpp" #include "LIEF/PE/CodeIntegrity.hpp" namespace LIEF { namespace PE { CodeIntegrity::~CodeIntegrity() = default; CodeIntegrity& CodeIntegrity::operator=(const CodeIntegrity&) = default; CodeIntegrity::CodeIntegrity(const CodeIntegrity&) = default; CodeIntegrity::CodeIntegrity() : flags_{0}, catalog_{0}, catalog_offset_{0}, reserved_{0} {} CodeIntegrity::CodeIntegrity(const pe_code_integrity *header) : flags_{header->Flags}, catalog_{header->Catalog}, catalog_offset_{header->CatalogOffset}, reserved_{header->Reserved} {} uint16_t CodeIntegrity::flags() const { return this->flags_; } uint16_t CodeIntegrity::catalog() const { return this->catalog_; } uint32_t CodeIntegrity::catalog_offset() const { return this->catalog_offset_; } uint32_t CodeIntegrity::reserved() const { return this->reserved_; } void CodeIntegrity::flags(uint16_t flags) { this->flags_ = flags; } void CodeIntegrity::catalog(uint16_t catalog) { this->catalog_ = catalog; } void CodeIntegrity::catalog_offset(uint32_t catalog_offset) { this->catalog_offset_ = catalog_offset; } void CodeIntegrity::reserved(uint32_t reserved) { this->reserved_ = reserved; } void CodeIntegrity::accept(LIEF::Visitor& visitor) const { visitor.visit(*this); } bool CodeIntegrity::operator==(const CodeIntegrity& rhs) const { size_t hash_lhs = Hash::hash(*this); size_t hash_rhs = Hash::hash(rhs); return hash_lhs == hash_rhs; } bool CodeIntegrity::operator!=(const CodeIntegrity& rhs) const { return not (*this == rhs); } std::ostream& operator<<(std::ostream& os, const CodeIntegrity& entry) { os << std::hex << std::left << std::showbase; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Flags:" << std::hex << entry.flags() << std::endl; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Catalog:" << std::hex << entry.catalog() << std::endl; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Catalog offset:" << std::hex << entry.catalog_offset() << std::endl; os << std::setw(CodeIntegrity::PRINT_WIDTH) << std::setfill(' ') << "Reserved:" << std::hex << entry.reserved() << std::endl; return os; } } }
28.308411
139
0.699241
ienho
ed97f70765144ce53e7f800ea9feee523b65f31d
12,218
cc
C++
src/video/FBPostProcessor.cc
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/FBPostProcessor.cc
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/FBPostProcessor.cc
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#include "FBPostProcessor.hh" #include "RawFrame.hh" #include "StretchScalerOutput.hh" #include "ScalerOutput.hh" #include "RenderSettings.hh" #include "Scaler.hh" #include "ScalerFactory.hh" #include "SDLOutputSurface.hh" #include "aligned.hh" #include "checked_cast.hh" #include "random.hh" #include "xrange.hh" #include <algorithm> #include <cassert> #include <cmath> #include <cstdint> #include <cstddef> #include <numeric> #ifdef __SSE2__ #include <emmintrin.h> #endif namespace openmsx { constexpr unsigned NOISE_SHIFT = 8192; constexpr unsigned NOISE_BUF_SIZE = 2 * NOISE_SHIFT; ALIGNAS_SSE static signed char noiseBuf[NOISE_BUF_SIZE]; template<typename Pixel> void FBPostProcessor<Pixel>::preCalcNoise(float factor) { // We skip noise drawing if the factor is 0, so there is no point in // initializing the random data in that case. if (factor == 0.0f) return; // for 32bpp groups of 4 consecutive noiseBuf elements (starting at // 4 element boundaries) must have the same value. Later optimizations // depend on it. float scale[4]; if (sizeof(Pixel) == 4) { // 32bpp // TODO ATM we compensate for big endian here. A better // alternative is to turn noiseBuf into an array of ints (it's // now bytes) and in the 16bpp code extract R,G,B components // from those ints const auto p = Pixel(OPENMSX_BIGENDIAN ? 0x00010203 : 0x03020100); // TODO we can also fill the array with 'factor' and only set // 'alpha' to 0.0. But PixelOperations doesn't offer a simple // way to get the position of the alpha byte (yet). scale[0] = scale[1] = scale[2] = scale[3] = 0.0f; scale[pixelOps.red (p)] = factor; scale[pixelOps.green(p)] = factor; scale[pixelOps.blue (p)] = factor; } else { // 16bpp scale[0] = (pixelOps.getMaxRed() / 255.0f) * factor; scale[1] = (pixelOps.getMaxGreen() / 255.0f) * factor; scale[2] = (pixelOps.getMaxBlue() / 255.0f) * factor; scale[3] = 0.0f; } auto& generator = global_urng(); // fast (non-cryptographic) random numbers std::normal_distribution<float> distribution(0.0f, 1.0f); for (unsigned i = 0; i < NOISE_BUF_SIZE; i += 4) { float r = distribution(generator); noiseBuf[i + 0] = std::clamp(int(roundf(r * scale[0])), -128, 127); noiseBuf[i + 1] = std::clamp(int(roundf(r * scale[1])), -128, 127); noiseBuf[i + 2] = std::clamp(int(roundf(r * scale[2])), -128, 127); noiseBuf[i + 3] = std::clamp(int(roundf(r * scale[3])), -128, 127); } } #ifdef __SSE2__ static inline void drawNoiseLineSse2(uint32_t* buf_, signed char* noise, size_t width) { // To each of the RGBA color components (a value in range [0..255]) we // want to add a signed noise value (in range [-128..127]) and also clip // the result to the range [0..255]. There is no SSE instruction that // directly performs this operation. But we can: // - subtract 128 from the RGBA component to get a signed byte // - perform the addition with signed saturation // - add 128 to the result to get back to the unsigned byte range // For 8-bit values the following 3 expressions are equivalent: // x + 128 == x - 128 == x ^ 128 // So the expression becomes: // signed_add_sat(value ^ 128, noise) ^ 128 // The following loop does just that, though it processes 64 bytes per // iteration. ptrdiff_t x = width * sizeof(uint32_t); assert((x & 63) == 0); assert((uintptr_t(buf_) & 15) == 0); char* buf = reinterpret_cast<char*>(buf_) + x; char* nse = reinterpret_cast<char*>(noise) + x; x = -x; __m128i b7 = _mm_set1_epi8(-128); // 0x80 do { __m128i i0 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 0)); __m128i i1 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 16)); __m128i i2 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 32)); __m128i i3 = _mm_load_si128(reinterpret_cast<__m128i*>(buf + x + 48)); __m128i n0 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 0)); __m128i n1 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 16)); __m128i n2 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 32)); __m128i n3 = _mm_load_si128(reinterpret_cast<__m128i*>(nse + x + 48)); __m128i o0 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i0, b7), n0), b7); __m128i o1 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i1, b7), n1), b7); __m128i o2 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i2, b7), n2), b7); __m128i o3 = _mm_xor_si128(_mm_adds_epi8(_mm_xor_si128(i3, b7), n3), b7); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 0), o0); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 16), o1); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 32), o2); _mm_store_si128(reinterpret_cast<__m128i*>(buf + x + 48), o3); x += 4 * sizeof(__m128i); } while (x < 0); } #endif /** Add noise to the given pixel. * @param p contains 4 8-bit unsigned components, so components have range [0, 255] * @param n contains 4 8-bit signed components, so components have range [-128, 127] * @result per component result of clip<0, 255>(p + n) */ static constexpr uint32_t addNoise4(uint32_t p, uint32_t n) { // unclipped result (lower 8 bits of each component) // alternative: // uint32_t s20 = ((p & 0x00FF00FF) + (n & 0x00FF00FF)) & 0x00FF00FF; // uint32_t s31 = ((p & 0xFF00FF00) + (n & 0xFF00FF00)) & 0xFF00FF00; // uint32_t s = s20 | s31; uint32_t s0 = p + n; // carry spills to neighbors uint32_t ci = (p ^ n ^ s0) & 0x01010100; // carry-in bits of prev sum uint32_t s = s0 - ci; // subtract carry bits again // Underflow of a component happens ONLY // WHEN input component is in range [0, 127] // AND noise component is negative // AND result component is in range [128, 255] // Overflow of a component happens ONLY // WHEN input component in in range [128, 255] // AND noise component is positive // AND result component is in range [0, 127] // Create a mask per component containing 00 for no under/overflow, // FF for under/overflow // ((~p & n & s) | (p & ~n & ~s)) == ((p ^ n) & (p ^ s)) uint32_t t = (p ^ n) & (p ^ s) & 0x80808080; uint32_t u1 = t & s; // underflow (alternative: u1 = t & n) // alternative1: uint32_t u2 = u1 | (u1 >> 1); // uint32_t u4 = u2 | (u2 >> 2); // uint32_t u8 = u4 | (u4 >> 4); // alternative2: uint32_t u8 = (u1 >> 7) * 0xFF; uint32_t u8 = (u1 << 1) - (u1 >> 7); uint32_t o1 = t & p; // overflow uint32_t o8 = (o1 << 1) - (o1 >> 7); // clip result return (s & (~u8)) | o8; } template<typename Pixel> void FBPostProcessor<Pixel>::drawNoiseLine( Pixel* buf, signed char* noise, size_t width) { #ifdef __SSE2__ if (sizeof(Pixel) == 4) { // cast to avoid compilation error in case of 16bpp (even // though this code is dead in that case). auto* buf32 = reinterpret_cast<uint32_t*>(buf); drawNoiseLineSse2(buf32, noise, width); return; } #endif // c++ version if (sizeof(Pixel) == 4) { // optimized version for 32bpp auto* noise4 = reinterpret_cast<uint32_t*>(noise); for (auto i : xrange(width)) { buf[i] = addNoise4(buf[i], noise4[i]); } } else { int mr = pixelOps.getMaxRed(); int mg = pixelOps.getMaxGreen(); int mb = pixelOps.getMaxBlue(); for (auto i : xrange(width)) { Pixel p = buf[i]; int r = pixelOps.red(p); int g = pixelOps.green(p); int b = pixelOps.blue(p); r += noise[4 * i + 0]; g += noise[4 * i + 1]; b += noise[4 * i + 2]; r = std::min(std::max(r, 0), mr); g = std::min(std::max(g, 0), mg); b = std::min(std::max(b, 0), mb); buf[i] = pixelOps.combine(r, g, b); } } } template<typename Pixel> void FBPostProcessor<Pixel>::drawNoise(OutputSurface& output_) { if (renderSettings.getNoise() == 0.0f) return; auto& output = checked_cast<SDLOutputSurface&>(output_); auto [w, h] = output.getLogicalSize(); auto pixelAccess = output.getDirectPixelAccess(); for (auto y : xrange(h)) { auto* buf = pixelAccess.getLinePtr<Pixel>(y); drawNoiseLine(buf, &noiseBuf[noiseShift[y]], w); } } template<typename Pixel> void FBPostProcessor<Pixel>::update(const Setting& setting) noexcept { VideoLayer::update(setting); auto& noiseSetting = renderSettings.getNoiseSetting(); if (&setting == &noiseSetting) { preCalcNoise(noiseSetting.getDouble()); } } template<typename Pixel> FBPostProcessor<Pixel>::FBPostProcessor(MSXMotherBoard& motherBoard_, Display& display_, OutputSurface& screen_, const std::string& videoSource, unsigned maxWidth_, unsigned height_, bool canDoInterlace_) : PostProcessor( motherBoard_, display_, screen_, videoSource, maxWidth_, height_, canDoInterlace_) , noiseShift(screen.getLogicalHeight()) , pixelOps(screen.getPixelFormat()) { scaleAlgorithm = RenderSettings::NO_SCALER; scaleFactor = unsigned(-1); stretchWidth = unsigned(-1); auto& noiseSetting = renderSettings.getNoiseSetting(); noiseSetting.attach(*this); preCalcNoise(noiseSetting.getDouble()); assert((screen.getLogicalWidth() * sizeof(Pixel)) < NOISE_SHIFT); } template<typename Pixel> FBPostProcessor<Pixel>::~FBPostProcessor() { renderSettings.getNoiseSetting().detach(*this); } template<typename Pixel> void FBPostProcessor<Pixel>::paint(OutputSurface& output_) { auto& output = checked_cast<SDLOutputSurface&>(output_); if (renderSettings.getInterleaveBlackFrame()) { interleaveCount ^= 1; if (interleaveCount) { output.clearScreen(); return; } } if (!paintFrame) return; // New scaler algorithm selected? Or different horizontal stretch? auto algo = renderSettings.getScaleAlgorithm(); unsigned factor = renderSettings.getScaleFactor(); unsigned inWidth = lrintf(renderSettings.getHorizontalStretch()); if ((scaleAlgorithm != algo) || (scaleFactor != factor) || (inWidth != stretchWidth) || (lastOutput != &output)) { scaleAlgorithm = algo; scaleFactor = factor; stretchWidth = inWidth; lastOutput = &output; currScaler = ScalerFactory<Pixel>::createScaler( PixelOperations<Pixel>(output.getPixelFormat()), renderSettings); stretchScaler = StretchScalerOutputFactory<Pixel>::create( output, pixelOps, inWidth); } // Scale image. const unsigned srcHeight = paintFrame->getHeight(); const unsigned dstHeight = output.getLogicalHeight(); unsigned g = std::gcd(srcHeight, dstHeight); unsigned srcStep = srcHeight / g; unsigned dstStep = dstHeight / g; // TODO: Store all MSX lines in RawFrame and only scale the ones that fit // on the PC screen, as a preparation for resizable output window. unsigned srcStartY = 0; unsigned dstStartY = 0; while (dstStartY < dstHeight) { // Currently this is true because the source frame height // is always >= dstHeight/(dstStep/srcStep). assert(srcStartY < srcHeight); // get region with equal lineWidth unsigned lineWidth = getLineWidth(paintFrame, srcStartY, srcStep); unsigned srcEndY = srcStartY + srcStep; unsigned dstEndY = dstStartY + dstStep; while ((srcEndY < srcHeight) && (dstEndY < dstHeight) && (getLineWidth(paintFrame, srcEndY, srcStep) == lineWidth)) { srcEndY += srcStep; dstEndY += dstStep; } // fill region //fprintf(stderr, "post processing lines %d-%d: %d\n", // srcStartY, srcEndY, lineWidth); currScaler->scaleImage( *paintFrame, superImposeVideoFrame, srcStartY, srcEndY, lineWidth, // source *stretchScaler, dstStartY, dstEndY); // dest // next region srcStartY = srcEndY; dstStartY = dstEndY; } drawNoise(output); output.flushFrameBuffer(); } template<typename Pixel> std::unique_ptr<RawFrame> FBPostProcessor<Pixel>::rotateFrames( std::unique_ptr<RawFrame> finishedFrame, EmuTime::param time) { auto& generator = global_urng(); // fast (non-cryptographic) random numbers std::uniform_int_distribution<int> distribution(0, NOISE_SHIFT / 16 - 1); for (auto y : xrange(screen.getLogicalHeight())) { noiseShift[y] = distribution(generator) * 16; } return PostProcessor::rotateFrames(std::move(finishedFrame), time); } // Force template instantiation. #if HAVE_16BPP template class FBPostProcessor<uint16_t>; #endif #if HAVE_32BPP template class FBPostProcessor<uint32_t>; #endif } // namespace openmsx
34.22409
86
0.681863
D15C0DE
ed9b56a08d18cd0d8b4728595e32efa030bbd3ac
103
cpp
C++
prototypes_cinder/PinballWarping/xcode/Location.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
1
2016-07-29T21:19:12.000Z
2016-07-29T21:19:12.000Z
prototypes_cinder/PinballWarping/xcode/Location.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
null
null
null
prototypes_cinder/PinballWarping/xcode/Location.cpp
redpaperheart/pinball_dreams
f1b873dc451157d9f2987501080a907635c80350
[ "Unlicense" ]
null
null
null
// // Location.cpp // PinballWarping // // Created by Eric on 6/10/15. // // #include "Location.h"
10.3
31
0.592233
redpaperheart
ed9ba3c47988be5ffd20aee496fdc10cbac0ae5a
3,102
cpp
C++
Greedy/948. Bag of Tokens.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
138
2020-02-08T05:25:26.000Z
2021-11-04T11:59:28.000Z
Greedy/948. Bag of Tokens.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
null
null
null
Greedy/948. Bag of Tokens.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
24
2021-01-02T07:18:43.000Z
2022-03-20T08:17:54.000Z
/* Bad Question Description: https://leetcode.com/problems/bag-of-tokens/discuss/197856/Bad-descriptions! Description Rewrite: You have a bag of tokens, from which you can take whichever token you want, and after you take one, you can't put it back to the bag, meaning you can use every token at most once. You start the game with P power and 0 point. For every tokens[i], you can use it in either way: - plus tokens[i] powers, and minus 1 point; - or, minus tokens[i] powers, and plus 1 point. (meaning you exchange your powers to get 1 point, or exchange your point to get more powers) But you have to make sure that during the process, both your powers>=0 and points>=0, otherwise you would have to stop playing the game. And you can use just some of the tokens (don't have to use all of them). Your target is to get the maximum points possible. */ //2020 class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(), tokens.end()); int point = 0; for(int i = 0, j = tokens.size()-1; i<=j;){ if(tokens[i] <= P){ point++; P -= tokens[i++]; } else if(i!=j && point > 0){ //i != j, 若只剩下一个点,不用了 point--; P+= tokens[j--]; } else{ break; } } return point; } }; class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(), tokens.end()); int res = 0, points = 0, i = 0, j = tokens.size() - 1; while (i <= j) { if (P >= tokens[i]) { P -= tokens[i++]; res = max(res, ++points); } else if (points > 0) { points--; P += tokens[j--]; } else { break; } } return res; } }; class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { sort(tokens.begin(), tokens.end()); return helper(tokens, 0, tokens.size()-1, P, 0); } int helper(vector<int>& tokens, int i, int j, int p, int points){ if(i > j) return points; int res = points; if(tokens[i] <= p) res = max(res, helper(tokens, i+1, j, p-tokens[i], points+1)); else if(points >= 1) res = max(res, helper(tokens, i, j-1, p+tokens[j], points-1)); return res; } }; class Solution { public: int bagOfTokensScore(vector<int>& tokens, int P) { int N = tokens.size(); if (!N) return 0; sort(tokens.begin(), tokens.end()); if (P < tokens[0]) return 0; int l = 0, h = N-1; int points = 0; while (l <= h) { if (P < tokens[l] && points) { P += tokens[h--]; points--; } if (P < tokens[l]) return points; P -= tokens[l++]; points++; } return points; } };
24.425197
136
0.503224
beckswu
eda0f587865b486a279f453d1c5a33422465cb54
3,478
cxx
C++
odb-tests-2.4.0/evolution/add-index/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/evolution/add-index/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/evolution/add-index/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
// file : evolution/add-index/driver.cxx // copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC // license : GNU GPL v2; see accompanying LICENSE file // Test adding a new index. // #include <memory> // std::auto_ptr #include <cassert> #include <iostream> #include <odb/database.hxx> #include <odb/transaction.hxx> #include <odb/schema-catalog.hxx> #include <common/common.hxx> #include "test2.hxx" #include "test3.hxx" #include "test2-odb.hxx" #include "test3-odb.hxx" using namespace std; using namespace odb::core; int main (int argc, char* argv[]) { try { auto_ptr<database> db (create_database (argc, argv, false)); bool embedded (schema_catalog::exists (*db)); // 1 - base version // 2 - migration // 3 - current version // unsigned short pass (*argv[argc - 1] - '0'); switch (pass) { case 1: { using namespace v2; if (embedded) { transaction t (db->begin ()); schema_catalog::drop_schema (*db); schema_catalog::create_schema (*db, "", false); schema_catalog::migrate_schema (*db, 2); t.commit (); } object o0 (0); o0.num = 123; object o1 (1); o1.num = 234; object o2 (2); o2.num = 234; // Duplicates are ok. // { transaction t (db->begin ()); db->persist (o0); db->persist (o1); db->persist (o2); t.commit (); } break; } case 2: { using namespace v3; if (embedded) { transaction t (db->begin ()); schema_catalog::migrate_schema_pre (*db, 3); t.commit (); } object o3 (3); o3.num = 234; // Duplicates are still ok but we need to remove them before the // post migration step. // { transaction t (db->begin ()); db->persist (o3); t.commit (); } { typedef odb::query<object> query; typedef odb::result<object> result; transaction t (db->begin ()); result r (db->query<object> ( "ORDER BY" + query::num + "," + query::id)); unsigned long prev (0); for (result::iterator i (r.begin ()); i != r.end (); ++i) { if (i->num == prev) db->erase (*i); prev = i->num; } t.commit (); } if (embedded) { transaction t (db->begin ()); schema_catalog::migrate_schema_post (*db, 3); t.commit (); } break; } case 3: { using namespace v3; { transaction t (db->begin ()); auto_ptr<object> p0 (db->load<object> (0)); auto_ptr<object> p1 (db->load<object> (1)); assert (p0->num == 123); assert (p1->num == 234); t.commit (); } try { object o2 (2); o2.num = 234; transaction t (db->begin ()); db->persist (o2); assert (false); } catch (const odb::exception& ) {} break; } default: { cerr << "unknown pass number '" << argv[argc - 1] << "'" << endl; return 1; } } } catch (const odb::exception& e) { cerr << e.what () << endl; return 1; } }
20.826347
73
0.47211
edidada
eda638f445c131091d5de5a945bf29c8532f6e0e
552
cpp
C++
stack_two_queues/stack_two_queues.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
46
2017-06-26T15:09:10.000Z
2022-03-19T04:21:32.000Z
stack_two_queues/stack_two_queues.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
null
null
null
stack_two_queues/stack_two_queues.cpp
ryanmcdermott/katas
d23b8c131f03e4df0a3a5268de4b63c5b35058a1
[ "MIT" ]
13
2017-10-18T05:30:18.000Z
2021-10-04T22:46:35.000Z
#include "./stack_two_queues.hpp" #include <queue> using std::queue; void stack_two_queues::pop() { if (q1.empty()) { return; } while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } q1.pop(); queue<int> temp = q1; q1 = q2; q2 = temp; } void stack_two_queues::push(int num) { q1.push(num); } int stack_two_queues::top() { while (q1.size() != 1) { q2.push(q1.front()); q1.pop(); } int top_item = q1.front(); q2.push(top_item); queue<int> temp = q1; q1 = q2; q2 = temp; return top_item; }
13.8
54
0.559783
ryanmcdermott
eda87f79f5dcd8a91e728dc73a19ca219e1aa82e
3,181
cpp
C++
sample/main.cpp
vmcraft/remoteprinter
bf0294bb01ec61782daf166a869abd2ee97fba28
[ "Apache-2.0" ]
11
2019-11-18T10:17:25.000Z
2022-01-26T04:48:16.000Z
sample/main.cpp
vmcraft/remoteprinter
bf0294bb01ec61782daf166a869abd2ee97fba28
[ "Apache-2.0" ]
null
null
null
sample/main.cpp
vmcraft/remoteprinter
bf0294bb01ec61782daf166a869abd2ee97fba28
[ "Apache-2.0" ]
5
2016-10-13T14:05:17.000Z
2021-02-09T15:50:29.000Z
#include "thriftlink_server.h" #include "userdef_server.h" #include <Windows.h> #include "stdio.h" #pragma comment(lib, "user32.lib") bool inject_dll(HMODULE &hmodule, HHOOK &hhook, int target_threadid); void eject_dll(HMODULE &hmodule, HHOOK &hhook); BOOL CtrlHandler( DWORD fdwCtrlType ) ; bool _break_loop = false; int main(int argc, char **argv) { if (argc==3 && _stricmp(argv[1], "hook")==0){ int threadid = atoi(argv[2]); HMODULE hmodule = NULL; HHOOK hhook = NULL; // Inject dlls if (!inject_dll(hmodule, hhook, threadid)){ printf("Injection failed.\n"); return 1; } // Set Ctrl handler. if( !SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE ) ) { printf("Could not set control handler.\n"); return 1; } printf("Press CTRL+C to stop.\n"); // Message handler is required for 32bit/64bit platform cross supporting. MSG msg; bool runThread = true; while(runThread) { // Keep pumping... PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE); TranslateMessage(&msg); DispatchMessage(&msg); if (_break_loop) break; Sleep(10); } eject_dll(hmodule, hhook); return 0; } else if ((argc==2||argc==3) && _stricmp(argv[1], "server")==0) { int port = 3900; if (argc==3) atoi(argv[2]); thrift_server_start(port); return 0; } printf("Usage:\n"); printf(" %s hook thread_id\n", argv[0]); printf(" %s server [port_number]\n", argv[0]); return 1; } // // This sample demonstrate how to inject dll by SetWindowsHookEx. // You can inject apifwrd.dll to destination process simply by AppInit_DLLs registry key or // implement your own method like CreateRemoteThread, ... // bool inject_dll(HMODULE &hmodule, HHOOK &hhook, int target_threadid) { // Already hooked. if (hhook!=NULL) return true; // Load library if (hmodule==NULL) { hmodule = LoadLibraryW(L"apifwrd.dll"); if (hmodule==NULL) return false; } // apifwrd.dll is ready to support SetWindowsHookEx() way. HOOKPROC addr = (HOOKPROC) GetProcAddress(hmodule, "HelperHookProcForSetWindowsHookEx"); if (addr==NULL) { FreeLibrary(hmodule); return false; } // Install hook hhook = SetWindowsHookEx(WH_CBT, addr, hmodule, target_threadid); if (hhook==NULL) { FreeLibrary(hmodule); return false; } return true; } void eject_dll(HMODULE &hmodule, HHOOK &hhook) { if (hhook) { UnhookWindowsHookEx(hhook); hhook = NULL; } if (hmodule) { FreeLibrary(hmodule); hmodule = NULL; } return; } BOOL CtrlHandler( DWORD fdwCtrlType ) { switch( fdwCtrlType ) { // Handle the CTRL-C signal. case CTRL_C_EVENT: case CTRL_CLOSE_EVENT: case CTRL_BREAK_EVENT: case CTRL_LOGOFF_EVENT: case CTRL_SHUTDOWN_EVENT: _break_loop = true; break; default: return FALSE; } return TRUE; }
24.098485
92
0.594467
vmcraft
eda9a8023016c2c2f78c0248d7af05f1c29ba080
9,777
cpp
C++
tests/performance/memory/hipPerfBufferCopySpeed.cpp
parmance/HIP
96ee9d1397f02ac4b4badd9243994728f6a89fe5
[ "MIT" ]
1,935
2017-05-28T04:52:18.000Z
2022-03-30T23:50:43.000Z
tests/performance/memory/hipPerfBufferCopySpeed.cpp
parmance/HIP
96ee9d1397f02ac4b4badd9243994728f6a89fe5
[ "MIT" ]
1,310
2017-05-30T22:16:09.000Z
2022-03-31T08:25:58.000Z
tests/performance/memory/hipPerfBufferCopySpeed.cpp
parmance/HIP
96ee9d1397f02ac4b4badd9243994728f6a89fe5
[ "MIT" ]
495
2017-06-01T01:26:27.000Z
2022-03-28T16:36:51.000Z
/* Copyright (c) 2015 - 2021 Advanced Micro Devices, Inc. All rights reserved. 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. */ /* HIT_START * BUILD: %t %s ../../src/test_common.cpp ../../src/timer.cpp * TEST: %t * HIT_END */ #include <stdio.h> #include <assert.h> #include <string.h> #include <complex> #include "timer.h" #include "test_common.h" // Quiet pesky warnings #ifdef WIN_OS #define SNPRINTF sprintf_s #else #define SNPRINTF snprintf #endif #define NUM_SIZES 9 //4KB, 8KB, 64KB, 256KB, 1 MB, 4MB, 16 MB, 16MB+10 static const unsigned int Sizes[NUM_SIZES] = {4096, 8192, 65536, 262144, 524288, 1048576, 4194304, 16777216, 16777216+10}; static const unsigned int Iterations[2] = {1, 1000}; #define BUF_TYPES 4 // 16 ways to combine 4 different buffer types #define NUM_SUBTESTS (BUF_TYPES*BUF_TYPES) #define CHECK_RESULT(test, msg) \ if ((test)) \ { \ printf("\n%s\n", msg); \ abort(); \ } void setData(void *ptr, unsigned int size, char value) { char *ptr2 = (char *)ptr; for (unsigned int i = 0; i < size ; i++) { ptr2[i] = value; } } void checkData(void *ptr, unsigned int size, char value) { char *ptr2 = (char *)ptr; for (unsigned int i = 0; i < size; i++) { if (ptr2[i] != value) { printf("Data validation failed at %d! Got 0x%08x\n", i, ptr2[i]); printf("Expected 0x%08x\n", value); CHECK_RESULT(true, "Data validation failed!"); break; } } } int main(int argc, char* argv[]) { HipTest::parseStandardArguments(argc, argv, true); hipError_t err = hipSuccess; hipDeviceProp_t props = {0}; hipGetDeviceProperties(&props, p_gpuDevice); CHECK_RESULT(err != hipSuccess, "hipGetDeviceProperties failed" ); printf("Set device to %d : %s\n", p_gpuDevice, props.name); printf("Legend: unp - unpinned(malloc), hM - hipMalloc(device)\n"); printf(" hHR - hipHostRegister(pinned), hHM - hipHostMalloc(prePinned)\n"); err = hipSetDevice(p_gpuDevice); CHECK_RESULT(err != hipSuccess, "hipSetDevice failed" ); unsigned int bufSize_; bool hostMalloc[2] = {false}; bool hostRegister[2] = {false}; bool unpinnedMalloc[2] = {false}; unsigned int numIter; void *memptr[2] = {NULL}; void *alignedmemptr[2] = {NULL}; void* srcBuffer = NULL; void* dstBuffer = NULL; int numTests = (p_tests == -1) ? (NUM_SIZES*NUM_SUBTESTS*2 - 1) : p_tests; int test = (p_tests == -1) ? 0 : p_tests; for(;test <= numTests; test++) { unsigned int srcTest = (test / NUM_SIZES) % BUF_TYPES; unsigned int dstTest = (test / (NUM_SIZES*BUF_TYPES)) % BUF_TYPES; bufSize_ = Sizes[test % NUM_SIZES]; hostMalloc[0] = hostMalloc[1] = false; hostRegister[0] = hostRegister[1] = false; unpinnedMalloc[0] = unpinnedMalloc[1] = false; srcBuffer = dstBuffer = 0; memptr[0] = memptr[1] = NULL; alignedmemptr[0] = alignedmemptr[1] = NULL; if (srcTest == 3) { hostRegister[0] = true; } else if (srcTest == 2) { hostMalloc[0] = true; } else if (srcTest == 1) { unpinnedMalloc[0] = true; } if (dstTest == 1) { unpinnedMalloc[1] = true; } else if (dstTest == 2) { hostMalloc[1] = true; } else if (dstTest == 3) { hostRegister[1] = true; } numIter = Iterations[test / (NUM_SIZES * NUM_SUBTESTS)]; if (hostMalloc[0]) { err = hipHostMalloc((void**)&srcBuffer, bufSize_, 0); setData(srcBuffer, bufSize_, 0xd0); CHECK_RESULT(err != hipSuccess, "hipHostMalloc failed"); } else if (hostRegister[0]) { memptr[0] = malloc(bufSize_ + 4096); alignedmemptr[0] = (void*)(((size_t)memptr[0] + 4095) & ~4095); srcBuffer = alignedmemptr[0]; setData(srcBuffer, bufSize_, 0xd0); err = hipHostRegister(srcBuffer, bufSize_, 0); CHECK_RESULT(err != hipSuccess, "hipHostRegister failed"); } else if (unpinnedMalloc[0]) { memptr[0] = malloc(bufSize_ + 4096); alignedmemptr[0] = (void*)(((size_t)memptr[0] + 4095) & ~4095); srcBuffer = alignedmemptr[0]; setData(srcBuffer, bufSize_, 0xd0); } else { err = hipMalloc(&srcBuffer, bufSize_); CHECK_RESULT(err != hipSuccess, "hipMalloc failed"); err = hipMemset(srcBuffer, 0xd0, bufSize_); CHECK_RESULT(err != hipSuccess, "hipMemset failed"); } if (hostMalloc[1]) { err = hipHostMalloc((void**)&dstBuffer, bufSize_, 0); CHECK_RESULT(err != hipSuccess, "hipHostMalloc failed"); } else if (hostRegister[1]) { memptr[1] = malloc(bufSize_ + 4096); alignedmemptr[1] = (void*)(((size_t)memptr[1] + 4095) & ~4095); dstBuffer = alignedmemptr[1]; err = hipHostRegister(dstBuffer, bufSize_, 0); CHECK_RESULT(err != hipSuccess, "hipHostRegister failed"); } else if (unpinnedMalloc[1]) { memptr[1] = malloc(bufSize_ + 4096); alignedmemptr[1] = (void*)(((size_t)memptr[1] + 4095) & ~4095); dstBuffer = alignedmemptr[1]; } else { err = hipMalloc(&dstBuffer, bufSize_); CHECK_RESULT(err != hipSuccess, "hipMalloc failed"); } CPerfCounter timer; //warm up err = hipMemcpy(dstBuffer, srcBuffer, bufSize_, hipMemcpyDefault); CHECK_RESULT(err, "hipMemcpy failed"); timer.Reset(); timer.Start(); for (unsigned int i = 0; i < numIter; i++) { err = hipMemcpyAsync(dstBuffer, srcBuffer, bufSize_, hipMemcpyDefault, NULL); CHECK_RESULT(err, "hipMemcpyAsync failed"); } err = hipDeviceSynchronize(); CHECK_RESULT(err, "hipDeviceSynchronize failed"); timer.Stop(); double sec = timer.GetElapsedTime(); // Buffer copy bandwidth in GB/s double perf = ((double)bufSize_*numIter*(double)(1e-09)) / sec; const char *strSrc = NULL; const char *strDst = NULL; if (hostMalloc[0]) strSrc = "hHM"; else if (hostRegister[0]) strSrc = "hHR"; else if (unpinnedMalloc[0]) strSrc = "unp"; else strSrc = "hM"; if (hostMalloc[1]) strDst = "hHM"; else if (hostRegister[1]) strDst = "hHR"; else if (unpinnedMalloc[1]) strDst = "unp"; else strDst = "hM"; // Double results when src and dst are both on device if ((!hostMalloc[0] && !hostRegister[0] && !unpinnedMalloc[0]) && (!hostMalloc[1] && !hostRegister[1] && !unpinnedMalloc[1])) perf *= 2.0; // Double results when src and dst are both in sysmem if ((hostMalloc[0] || hostRegister[0] || unpinnedMalloc[0]) && (hostMalloc[1] || hostRegister[1] || unpinnedMalloc[1])) perf *= 2.0; char buf[256]; SNPRINTF(buf, sizeof(buf), "HIPPerfBufferCopySpeed[%d]\t(%8d bytes)\ts:%s d:%s\ti:%4d\t(GB/s) perf\t%f", test, bufSize_, strSrc, strDst, numIter, (float)perf); printf("%s\n", buf); // Verification void* temp = malloc(bufSize_ + 4096); void* chkBuf = (void*)(((size_t)temp + 4095) & ~4095); err = hipMemcpy(chkBuf, dstBuffer, bufSize_, hipMemcpyDefault); CHECK_RESULT(err, "hipMemcpy failed"); checkData(chkBuf, bufSize_, 0xd0); free(temp); //Free src if (hostMalloc[0]) { hipHostFree(srcBuffer); } else if (hostRegister[0]) { hipHostUnregister(srcBuffer); free(memptr[0]); } else if (unpinnedMalloc[0]) { free(memptr[0]); } else { hipFree(srcBuffer); } //Free dst if (hostMalloc[1]) { hipHostFree(dstBuffer); } else if (hostRegister[1]) { hipHostUnregister(dstBuffer); free(memptr[1]); } else if (unpinnedMalloc[1]) { free(memptr[1]); } else { hipFree(dstBuffer); } } passed(); }
31.846906
122
0.561215
parmance
edaa67352a7ea85bdfe3f9ea126b78b8d7ae713a
3,766
cpp
C++
test/InverseKinematicsTest.cpp
EthanQuist/ENPM808X_Midterm
ab01777bd9da910cd750dffbeaf15ba60b619062
[ "BSD-3-Clause" ]
null
null
null
test/InverseKinematicsTest.cpp
EthanQuist/ENPM808X_Midterm
ab01777bd9da910cd750dffbeaf15ba60b619062
[ "BSD-3-Clause" ]
3
2019-10-13T03:34:25.000Z
2019-10-20T23:57:43.000Z
test/InverseKinematicsTest.cpp
EthanQuist/ENPM808X_Midterm
ab01777bd9da910cd750dffbeaf15ba60b619062
[ "BSD-3-Clause" ]
1
2019-10-10T03:52:53.000Z
2019-10-10T03:52:53.000Z
/* Copyright (c) 2019, Acme Robotics, Ethan Quist, Corbyn Yhap * 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <gtest/gtest.h> #include <algorithm> #include "InverseKinematics.hpp" #include "RevoluteJoint.hpp" bool AreSame(double a, double b) { double error = fabs(a - b); double epsilon = 0.00001; return error < epsilon; } TEST(InverseKinematics, checkContract) { InverseKinematicAcmeArm IKsolver; std::vector<JointPtr> result; // Using the Coordinates from the Paper Eigen::Matrix4d T = Eigen::Matrix4d::Identity(); // Transform Matrix - Position T.block<3, 1>(0, 3) = Eigen::Vector3d(2.0, 0.0, 2.5); result = IKsolver.computeIK(T); JointPtr tQ1(new RevoluteJoint(0)); JointPtr tQ2(new RevoluteJoint(0)); JointPtr tQ3(new RevoluteJoint(0)); JointPtr tQ4(new RevoluteJoint(1.5708)); JointPtr tQ5(new RevoluteJoint(1.5708)); JointPtr tQ6(new RevoluteJoint(-1.5708)); std::vector<JointPtr> expected; expected.push_back(tQ1); expected.push_back(tQ2); expected.push_back(tQ3); expected.push_back(tQ4); expected.push_back(tQ5); expected.push_back(tQ6); // Test the number of joints that were output ASSERT_EQ(expected.size(), result.size()); // Test Each element in each matches (in order) JointPtr result1 = result[0]; double r1 = result1->getConfig(); double q1 = tQ1->getConfig(); bool joint_angle1 = AreSame(r1, q1); ASSERT_EQ(joint_angle1, true); JointPtr result2 = result[1]; double r2 = result2->getConfig(); double q2 = tQ2->getConfig(); bool joint_angle2 = AreSame(r2, q2); ASSERT_EQ(joint_angle2, true); JointPtr result3 = result[2]; double r3 = result3->getConfig(); double q3 = tQ3->getConfig(); bool joint_angle3 = AreSame(r3, q3); ASSERT_EQ(joint_angle3, true); JointPtr result4 = result[3]; double r4 = result4->getConfig(); double q4 = tQ4->getConfig(); bool joint_angle4 = AreSame(r4, q4); ASSERT_EQ(joint_angle4, true); JointPtr result5 = result[4]; double r5 = result5->getConfig(); double q5 = tQ5->getConfig(); bool joint_angle5 = AreSame(r5, q5); ASSERT_EQ(joint_angle5, true); JointPtr result6 = result[5]; double r6 = result6->getConfig(); double q6 = tQ6->getConfig(); bool joint_angle6 = AreSame(r6, q6); ASSERT_EQ(joint_angle6, true); }
34.87037
81
0.726766
EthanQuist
edb5df4596b031736b5437b81f07fd520c1413ce
1,797
hpp
C++
include/range/v3/view/unique.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
521
2016-02-14T00:39:01.000Z
2022-03-01T22:39:25.000Z
include/range/v3/view/unique.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
8
2017-02-21T11:47:33.000Z
2018-11-01T09:37:14.000Z
include/range/v3/view/unique.hpp
berolinux/range-v3
d8ce45f1698931399fb09a322307eb95567be832
[ "MIT" ]
48
2017-02-21T10:18:13.000Z
2022-03-25T02:35:20.000Z
/// \file // Range v3 library // // Copyright Eric Niebler 2013-present // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_VIEW_UNIQUE_HPP #define RANGES_V3_VIEW_UNIQUE_HPP #include <utility> #include <meta/meta.hpp> #include <range/v3/range_fwd.hpp> #include <range/v3/functional/bind_back.hpp> #include <range/v3/functional/not_fn.hpp> #include <range/v3/utility/static_const.hpp> #include <range/v3/view/adjacent_filter.hpp> #include <range/v3/view/all.hpp> #include <range/v3/view/view.hpp> namespace ranges { /// \addtogroup group-views /// @{ namespace views { struct unique_fn { private: friend view_access; template<typename C> static constexpr auto CPP_fun(bind)(unique_fn unique, C pred)( // requires(!range<C>)) { return bind_back(unique, std::move(pred)); } public: template<typename Rng, typename C = equal_to> constexpr auto operator()(Rng && rng, C pred = {}) const -> CPP_ret(adjacent_filter_view<all_t<Rng>, logical_negate<C>>)( // requires viewable_range<Rng> && forward_range<Rng> && indirect_relation<C, iterator_t<Rng>>) { return {all(static_cast<Rng &&>(rng)), not_fn(pred)}; } }; /// \relates unique_fn /// \ingroup group-views RANGES_INLINE_VARIABLE(view<unique_fn>, unique) } // namespace views /// @} } // namespace ranges #endif
27.227273
83
0.607123
berolinux
edb6256af3b3e34d3a889492de43c916f3b7dd80
2,261
hpp
C++
include/networkit/coarsening/ClusteringProjector.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
null
null
null
include/networkit/coarsening/ClusteringProjector.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
null
null
null
include/networkit/coarsening/ClusteringProjector.hpp
kmc-kk/networkit
28c1208104acae8ef70911340bf88b3e3dd08db7
[ "MIT" ]
1
2020-02-05T17:39:47.000Z
2020-02-05T17:39:47.000Z
/* * ClusteringProjector.h * * Created on: 07.01.2013 * Author: Christian Staudt ([email protected]) */ #ifndef NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_ #define NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_ #include <networkit/graph/Graph.hpp> #include <networkit/structures/Partition.hpp> namespace NetworKit { /** * @ingroup coarsening */ class ClusteringProjector { public: /** * DEPRECATED * * Given * @param[in] Gcoarse * @param[in] Gfine * @param[in] fineToCoarse * @param[in] zetaCoarse a clustering of the coarse graph * * , project the clustering back to the fine graph to create a clustering of the fine graph. * @param[out] a clustering of the fine graph **/ //virtual Partition projectBack(Graph& Gcoarse, Graph& Gfine, std::vector<node>& fineToCoarse, Partition& zetaCoarse); /** * Given * @param[in] Gcoarse * @param[in] Gfine * @param[in] fineToCoarse * @param[in] zetaCoarse a clustering of the coarse graph * * , project the clustering back to the fine graph to create a clustering of the fine graph. * @param[out] a clustering of the fine graph **/ virtual Partition projectBack(const Graph& Gcoarse, const Graph& Gfine, const std::vector<node>& fineToCoarse, const Partition& zetaCoarse); /** * Project a clustering \zeta^{i} of the coarse graph G^{i} back to * the finest graph G^{0}, using the hierarchy of fine->coarse maps */ virtual Partition projectBackToFinest(const Partition& zetaCoarse, const std::vector<std::vector<node> >& maps, const Graph& Gfinest); /** * Assuming that the coarse graph resulted from contracting and represents a clustering of the finest graph * * @param[in] Gcoarse coarse graph * @param[in] Gfinest finest graph * @param[in] maps hierarchy of maps M^{i->i+1} mapping nodes in finer graph to supernodes in coarser graph */ virtual Partition projectCoarseGraphToFinestClustering(const Graph& Gcoarse, const Graph& Gfinest, const std::vector<std::vector<node> >& maps); }; } /* namespace NetworKit */ #endif // NETWORKIT_COARSENING_CLUSTERING_PROJECTOR_HPP_
30.972603
148
0.678903
kmc-kk
edc232de82b448ad6a4c98b1fad9a09f9615b0a4
90,628
cpp
C++
PhysEngines/tokamak/tokamak_release/tokamaksrc/src/ne_interface.cpp
netpipe/IrrPAL
39cfbe497c0d18a3b63f1a7758a2b979977d8efb
[ "BSD-3-Clause" ]
22
2015-02-18T16:38:52.000Z
2021-04-11T06:25:28.000Z
PhysEngines/tokamak/tokamak_release/tokamaksrc/src/ne_interface.cpp
netpipe/IrrPAL
39cfbe497c0d18a3b63f1a7758a2b979977d8efb
[ "BSD-3-Clause" ]
null
null
null
PhysEngines/tokamak/tokamak_release/tokamaksrc/src/ne_interface.cpp
netpipe/IrrPAL
39cfbe497c0d18a3b63f1a7758a2b979977d8efb
[ "BSD-3-Clause" ]
9
2017-06-27T12:46:15.000Z
2022-03-17T08:27:50.000Z
/************************************************************************* * * * Tokamak Physics Engine, Copyright (C) 2002-2007 David Lam. * * All rights reserved. Email: [email protected] * * Web: www.tokamakphysics.com * * * * 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 files * * LICENSE.TXT for more details. * * * *************************************************************************/ #include "math/ne_type.h" #include "math/ne_debug.h" #include "tokamak.h" #include "containers.h" #include "scenery.h" #include "collision.h" #include "constraint.h" #include "rigidbody.h" #ifdef _WIN32 #include <windows.h> #endif #include "stack.h" #include "simulator.h" #include "message.h" #include "stdio.h" #define CAST_THIS(a, b) a& b = reinterpret_cast<a&>(*this); #ifdef TOKAMAK_COMPILE_DLL BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif /**************************************************************************** * * neGeometry::SetBoxSize * ****************************************************************************/ void neGeometry::SetBoxSize(f32 width, f32 height, f32 depth) { CAST_THIS(TConvex, con); con.SetBoxSize(width, height, depth); } /**************************************************************************** * * neGeometry::SetBoxSize * ****************************************************************************/ void neGeometry::SetBoxSize(const neV3 & boxSize) { CAST_THIS(TConvex, con); con.SetBoxSize(boxSize[0], boxSize[1], boxSize[2]); } /**************************************************************************** * * neGeometry::SetCylinder * ****************************************************************************/ void neGeometry::SetCylinder(f32 diameter, f32 height) { CAST_THIS(TConvex, con); con.type = TConvex::CYLINDER; con.as.cylinder.radius = diameter * 0.5f; con.as.cylinder.radiusSq = con.as.cylinder.radius * con.as.cylinder.radius; con.as.cylinder.halfHeight = height * 0.5f; } /**************************************************************************** * * neGeometry::GetCylinder * ****************************************************************************/ neBool neGeometry::GetCylinder(f32 & diameter, f32 & height) // return false if geometry is not a cylinder { CAST_THIS(TConvex, con); if (con.type != TConvex::CYLINDER) return false; diameter = con.CylinderRadius() * 2.0f; height = con.CylinderHalfHeight() * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetConvexMesh * ****************************************************************************/ void neGeometry::SetConvexMesh(neByte * convexData) { CAST_THIS(TConvex, con); con.SetConvexMesh(convexData); } /**************************************************************************** * * neGeometry::GetConvexMesh * ****************************************************************************/ neBool neGeometry::GetConvexMesh(neByte *& convexData) { CAST_THIS(TConvex, con); if (con.type != TConvex::CONVEXDCD) return false; convexData = con.as.convexDCD.convexData; return true; } /**************************************************************************** * * neGeometry::SetTransform * ****************************************************************************/ void neGeometry::SetTransform(neT3 & t) { CAST_THIS(TConvex, con); con.SetTransform(t); } /**************************************************************************** * * neGeometry::SetMaterialIndex * ****************************************************************************/ void neGeometry::SetMaterialIndex(s32 index) { CAST_THIS(TConvex, con); con.SetMaterialId(index); } /**************************************************************************** * * neGeometry::GetMaterialIndex * ****************************************************************************/ s32 neGeometry::GetMaterialIndex() { CAST_THIS(TConvex, con); return con.matIndex; } /**************************************************************************** * * neGeometry::GetTransform * ****************************************************************************/ neT3 neGeometry::GetTransform() { CAST_THIS(TConvex, con); return con.c2p; } /**************************************************************************** * * neGeometry::SetUserData * ****************************************************************************/ void neGeometry::SetUserData(u32 userData) { CAST_THIS(TConvex, con); con.userData = userData; } /**************************************************************************** * * neGeometry::GetUserData * ****************************************************************************/ u32 neGeometry::GetUserData() { CAST_THIS(TConvex, con); return con.userData; } /**************************************************************************** * * neGeometry::GetBoxSize * ****************************************************************************/ neBool neGeometry::GetBoxSize(neV3 & boxSize) // return false if geometry is not a box { CAST_THIS(TConvex, con); if (con.type != TConvex::BOX) return false; boxSize = con.as.box.boxSize * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetSphereDiameter * ****************************************************************************/ void neGeometry::SetSphereDiameter(f32 diameter) { CAST_THIS(TConvex, con); con.type = TConvex::SPHERE; con.as.sphere.radius = diameter * 0.5f; con.as.sphere.radiusSq = con.as.sphere.radius * con.as.sphere.radius; } /**************************************************************************** * * neGeometry::GetSphereDiameter * ****************************************************************************/ neBool neGeometry::GetSphereDiameter(f32 & diameter) // return false if geometry is not a sphere { CAST_THIS(TConvex, con); if (con.type != TConvex::SPHERE) return false; diameter = con.Radius() * 2.0f; return true; } /**************************************************************************** * * neGeometry::SetBreakFlag * ****************************************************************************/ void neGeometry::SetBreakageFlag(neBreakFlag flag) { CAST_THIS(TConvex, con); con.breakInfo.flag = flag; } /**************************************************************************** * * neGeometry::GetBreakFlag * ****************************************************************************/ neGeometry::neBreakFlag neGeometry::GetBreakageFlag() { CAST_THIS(TConvex, con); return con.breakInfo.flag; } /**************************************************************************** * * neGeometry::SetBreakageMass * ****************************************************************************/ void neGeometry::SetBreakageMass(f32 mass) { CAST_THIS(TConvex, con); con.breakInfo.mass = mass; } /**************************************************************************** * * neGeometry::GetBreakageMass * ****************************************************************************/ f32 neGeometry::GetBreakageMass() { CAST_THIS(TConvex, con); return con.breakInfo.mass; } /**************************************************************************** * * neGeometry::SetBreakageInertiaTensor * ****************************************************************************/ void neGeometry::SetBreakageInertiaTensor(const neV3 & tensor) { CAST_THIS(TConvex, con); con.breakInfo.inertiaTensor = tensor; } /**************************************************************************** * * neGeometry::GetBreakageInertiaTensor * ****************************************************************************/ neV3 neGeometry::GetBreakageInertiaTensor() { CAST_THIS(TConvex, con); return con.breakInfo.inertiaTensor; } /**************************************************************************** * * neGeometry::SetBreakageMagnitude * ****************************************************************************/ void neGeometry::SetBreakageMagnitude(f32 mag) { CAST_THIS(TConvex, con); con.breakInfo.breakMagnitude = mag; } /**************************************************************************** * * neGeometry::GetBreakageMagnitude * ****************************************************************************/ f32 neGeometry::GetBreakageMagnitude() { CAST_THIS(TConvex, con); return con.breakInfo.breakMagnitude; } /**************************************************************************** * * neGeometry::SetBreakageAbsorption * ****************************************************************************/ void neGeometry::SetBreakageAbsorption(f32 absorb) { CAST_THIS(TConvex, con); con.breakInfo.breakAbsorb = absorb; } void neGeometry::SetBreakagePlane(const neV3 & planeNormal) { CAST_THIS(TConvex, con); con.breakInfo.breakPlane = planeNormal; } neV3 neGeometry::GetBreakagePlane() { CAST_THIS(TConvex, con); return con.breakInfo.breakPlane; } /**************************************************************************** * * neGeometry::GetBreakageAbsorption * ****************************************************************************/ f32 neGeometry::GetBreakageAbsorption() { CAST_THIS(TConvex, con); return con.breakInfo.breakAbsorb; } /**************************************************************************** * * neGeometry::SetBreakNeighbourRadius * ****************************************************************************/ void neGeometry::SetBreakageNeighbourRadius(f32 radius) { CAST_THIS(TConvex, con); con.breakInfo.neighbourRadius = radius; } /**************************************************************************** * * neGeometry::GetBreakNeighbourRadius * ****************************************************************************/ f32 neGeometry::GetBreakageNeighbourRadius() { CAST_THIS(TConvex, con); return con.breakInfo.neighbourRadius; } /**************************************************************************** * * neAnimatedBody::GetPos * ****************************************************************************/ neV3 neAnimatedBody::GetPos() { CAST_THIS(neCollisionBody_, cb); return cb.b2w.pos; } /**************************************************************************** * * neAnimatedBody::SetPos * ****************************************************************************/ void neAnimatedBody::SetPos(const neV3 & p) { CAST_THIS(neCollisionBody_, cb); cb.b2w.pos = p; cb.UpdateAABB(); cb.moved = true; } /**************************************************************************** * * neAnimatedBody::GetRotationM3 * ****************************************************************************/ neM3 neAnimatedBody::GetRotationM3() { CAST_THIS(neCollisionBody_, cb); return cb.b2w.rot; } /**************************************************************************** * * neAnimatedBody::GetRotationQ * ****************************************************************************/ neQ neAnimatedBody::GetRotationQ() { CAST_THIS(neCollisionBody_, cb); neQ q; q.SetupFromMatrix3(cb.b2w.rot); return q; } /**************************************************************************** * * neAnimatedBody::SetRotation * ****************************************************************************/ void neAnimatedBody::SetRotation(const neM3 & m) { CAST_THIS(neCollisionBody_, cb); cb.b2w.rot = m; cb.moved = true; } /**************************************************************************** * * neAnimatedBody::SetRotation * ****************************************************************************/ void neAnimatedBody::SetRotation(const neQ & q) { CAST_THIS(neCollisionBody_, cb); cb.b2w.rot = q.BuildMatrix3(); cb.moved = true; } /**************************************************************************** * * neAnimatedBody::GetTransform * ****************************************************************************/ neT3 neAnimatedBody::GetTransform() { CAST_THIS(neCollisionBody_, cb); return cb.b2w; } /**************************************************************************** * * neAnimatedBody::SetCollisionID * ****************************************************************************/ void neAnimatedBody::SetCollisionID(s32 cid) { CAST_THIS(neCollisionBody_, cb); cb.cid = cid; } /**************************************************************************** * * neAnimatedBody::GetCollisionID * ****************************************************************************/ s32 neAnimatedBody::GetCollisionID() { CAST_THIS(neCollisionBody_, cb); return cb.cid; } /**************************************************************************** * * neAnimatedBody::SetUserData * ****************************************************************************/ void neAnimatedBody::SetUserData(u32 cookies) { CAST_THIS(neCollisionBody_, cb); cb.cookies = cookies; } /**************************************************************************** * * neAnimatedBody::GetUserData * ****************************************************************************/ u32 neAnimatedBody::GetUserData() { CAST_THIS(neCollisionBody_, cb); return cb.cookies; } /**************************************************************************** * * neAnimatedBody::GetGeometryCount * ****************************************************************************/ s32 neAnimatedBody::GetGeometryCount() { CAST_THIS(neCollisionBody_, cb); return cb.col.convexCount; } /**************************************************************************** * * neAnimatedBody::GetGeometry * ****************************************************************************/ /* neGeometry * neAnimatedBody::GetGeometry(s32 index) { CAST_THIS(neCollisionBody_, cb); return reinterpret_cast<neGeometry*>(cb.GetConvex(index)); } */ /**************************************************************************** * * neAnimatedBody::SetGeometry * ****************************************************************************/ /* void neAnimatedBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray) { CAST_THIS(neCollisionBody_, cb); //todo } */ /**************************************************************************** * * neAnimatedBody::UpdateBoundingInfo * ****************************************************************************/ void neAnimatedBody::UpdateBoundingInfo() { CAST_THIS(neRigidBodyBase, rb); rb.RecalcBB(); } /**************************************************************************** * * neAnimatedBody::CollideConnected * ****************************************************************************/ void neAnimatedBody::CollideConnected(neBool yes) { CAST_THIS(neRigidBodyBase, rb); rb.CollideConnected(yes); } /**************************************************************************** * * neAnimatedBody::IsCollideConnected * ****************************************************************************/ neBool neAnimatedBody::CollideConnected() { CAST_THIS(neRigidBodyBase, rb); return rb.CollideConnected(); } /**************************************************************************** * * neAnimatedBody::CollideDirectlyConnected * ****************************************************************************/ void neAnimatedBody::CollideDirectlyConnected(neBool yes) { CAST_THIS(neRigidBodyBase, rb); rb.isCollideDirectlyConnected = yes; } /**************************************************************************** * * neAnimatedBody::CollideDirectlyConnected * ****************************************************************************/ neBool neAnimatedBody::CollideDirectlyConnected() { CAST_THIS(neRigidBodyBase, rb); return rb.isCollideDirectlyConnected; } /**************************************************************************** * * neAnimatedBody::AddGeometry * ****************************************************************************/ neGeometry * neAnimatedBody::AddGeometry() { CAST_THIS(neCollisionBody_, ab); TConvex * g = ab.AddGeometry(); return reinterpret_cast<neGeometry *>(g); } /**************************************************************************** * * neAnimatedBody::RemoveGeometry * ****************************************************************************/ neBool neAnimatedBody::RemoveGeometry(neGeometry * g) { CAST_THIS(neCollisionBody_, ab); if (!ab.col.convex) return false; TConvexItem * gi = (TConvexItem *)ab.col.convex; while (gi) { TConvex * convex = reinterpret_cast<TConvex *>(gi); gi = gi->next; if (convex == reinterpret_cast<TConvex *>(g)) { if (ab.col.convex == convex) { ab.col.convex = (TConvex*)gi; } ab.sim->geometryHeap.Dealloc(convex, 1); ab.col.convexCount--; if (ab.col.convexCount == 0) { ab.col.convex = NULL; if (ab.IsInRegion() && !ab.isCustomCD) ab.sim->region.RemoveBody(&ab); } return true; } } return false; } /**************************************************************************** * * neAnimatedBody::BeginIterateGeometry * ****************************************************************************/ void neAnimatedBody::BeginIterateGeometry() { CAST_THIS(neCollisionBody_, ab); ab.BeginIterateGeometry(); } /**************************************************************************** * * neAnimatedBody::GetNextGeometry * ****************************************************************************/ neGeometry * neAnimatedBody::GetNextGeometry() { CAST_THIS(neCollisionBody_, ab); return reinterpret_cast<neGeometry *>(ab.GetNextGeometry()); } /**************************************************************************** * * neAnimatedBody::BreakGeometry * ****************************************************************************/ neRigidBody * neAnimatedBody::BreakGeometry(neGeometry * g) { CAST_THIS(neCollisionBody_, ab); neRigidBody_ * newBody = ab.sim->CreateRigidBodyFromConvex((TConvex*)g, &ab); return (neRigidBody *)newBody; } /**************************************************************************** * * neAnimatedBody::UseCustomCollisionDetection * ****************************************************************************/ void neAnimatedBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius) { CAST_THIS(neCollisionBody_, ab); if (yes) { ab.obb = *obb; ab.col.boundingRadius = boundingRadius; ab.isCustomCD = yes; if (ab.isActive && !ab.IsInRegion()) { ab.sim->region.AddBody(&ab, NULL); } } else { ab.isCustomCD = yes; this->UpdateBoundingInfo(); if (ab.IsInRegion() && GetGeometryCount() == 0) { ab.sim->region.RemoveBody(&ab); } } } /**************************************************************************** * * neAnimatedBody::UseCustomCollisionDetection * ****************************************************************************/ neBool neAnimatedBody::UseCustomCollisionDetection() { CAST_THIS(neCollisionBody_, ab); return ab.isCustomCD; } /**************************************************************************** * * neAnimatedBody::AddSensor * ****************************************************************************/ neSensor * neAnimatedBody::AddSensor() { CAST_THIS(neRigidBodyBase, ab); neSensor_ * s = ab.AddSensor(); return reinterpret_cast<neSensor *>(s); } /**************************************************************************** * * neAnimatedBody::RemoveSensor * ****************************************************************************/ neBool neAnimatedBody::RemoveSensor(neSensor * s) { CAST_THIS(neRigidBodyBase, ab); if (!ab.sensors) return false; neSensorItem * si = (neSensorItem *)ab.sensors; while (si) { neSensor_ * sensor = (neSensor_ *) si; si = si->next; if (sensor == reinterpret_cast<neSensor_*>(s)) { //reinterpret_cast<neSensorItem *>(s)->Remove(); ab.sim->sensorHeap.Dealloc(sensor, 1); return true; } } return false; } /**************************************************************************** * * neAnimatedBody::BeginIterateSensor * ****************************************************************************/ void neAnimatedBody::BeginIterateSensor() { CAST_THIS(neRigidBodyBase, ab); ab.BeginIterateSensor(); } /**************************************************************************** * * neAnimatedBody::GetNextSensor * ****************************************************************************/ neSensor * neAnimatedBody::GetNextSensor() { CAST_THIS(neRigidBodyBase, ab); return reinterpret_cast<neSensor *>(ab.GetNextSensor()); } /**************************************************************************** * * neAnimatedBody::Active * ****************************************************************************/ void neAnimatedBody::Active(neBool yes, neRigidBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::Active * ****************************************************************************/ void neAnimatedBody::Active(neBool yes, neAnimatedBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::IsActive * ****************************************************************************/ neBool neAnimatedBody::Active() { CAST_THIS(neRigidBodyBase, ab); return ab.isActive; } /**************************************************************************** * * neRigidBody::GetMass * ****************************************************************************/ f32 neRigidBody::GetMass() { CAST_THIS(neRigidBody_, rb); return rb.mass; } /**************************************************************************** * * neRigidBody::SetMass * ****************************************************************************/ void neRigidBody::SetMass(f32 mass) { CAST_THIS(neRigidBody_, rb); ASSERT(neIsFinite(mass)); rb.mass = mass; rb.oneOnMass = 1.0f / mass; } /**************************************************************************** * * neRigidBody::SetInertiaTensor * ****************************************************************************/ void neRigidBody::SetInertiaTensor(const neM3 & tensor) { CAST_THIS(neRigidBody_, rb); rb.Ibody = tensor; rb.IbodyInv.SetInvert(tensor); //ASSERT(tensor.Invert(rb.IbodyInv)); } /**************************************************************************** * * neRigidBody::SetInertiaTensor * ****************************************************************************/ void neRigidBody::SetInertiaTensor(const neV3 & tensor) { CAST_THIS(neRigidBody_, rb); neM3 i; i.SetIdentity(); i[0][0] = tensor[0]; i[1][1] = tensor[1]; i[2][2] = tensor[2]; rb.Ibody = i; rb.IbodyInv.SetInvert(rb.Ibody); } /**************************************************************************** * * neRigidBody::SetCollisionID * ****************************************************************************/ void neRigidBody::SetCollisionID(s32 cid) { CAST_THIS(neRigidBodyBase, rb); rb.cid = cid; } /**************************************************************************** * * neRigidBody::GetCollisionID * ****************************************************************************/ s32 neRigidBody::GetCollisionID() { CAST_THIS(neRigidBodyBase, rb); return rb.cid; } /**************************************************************************** * * neRigidBody::SetUserData * ****************************************************************************/ void neRigidBody::SetUserData(u32 cookies) { CAST_THIS(neRigidBodyBase, rb); rb.cookies = cookies; } /**************************************************************************** * * neRigidBody::GetUserData * ****************************************************************************/ u32 neRigidBody::GetUserData() { CAST_THIS(neRigidBodyBase, rb); return rb.cookies; } /**************************************************************************** * * neRigidBody::GetGeometryCount * ****************************************************************************/ s32 neRigidBody::GetGeometryCount() { CAST_THIS(neRigidBodyBase, rb); return rb.col.convexCount; } void neRigidBody::SetLinearDamping(f32 damp) { CAST_THIS(neRigidBody_, rb); rb.linearDamp = neAbs(damp); } f32 neRigidBody::GetLinearDamping() { CAST_THIS(neRigidBody_, rb); return rb.linearDamp; } void neRigidBody::SetAngularDamping(f32 damp) { CAST_THIS(neRigidBody_, rb); rb.angularDamp = neAbs(damp); } f32 neRigidBody::GetAngularDamping() { CAST_THIS(neRigidBody_, rb); return rb.angularDamp; } void neRigidBody::SetSleepingParameter(f32 sleepingParam) { CAST_THIS(neRigidBody_, rb); rb.sleepingParam = sleepingParam; } f32 neRigidBody::GetSleepingParameter() { CAST_THIS(neRigidBody_, rb); return rb.sleepingParam; } /**************************************************************************** * * neRigidBody::GetGeometry * ****************************************************************************/ /* neGeometry * neRigidBody::GetGeometry(s32 index) { CAST_THIS(neRigidBodyBase, rb); return reinterpret_cast<neGeometry*>(rb.GetConvex(index)); } */ /**************************************************************************** * * neRigidBody::SetGeometry * ****************************************************************************/ /* void neRigidBody::SetGeometry(s32 geometryCount, neGeometry * geometryArray) { //todo } */ /**************************************************************************** * * neRigidBody::GetPos * ****************************************************************************/ neV3 neRigidBody::GetPos() { CAST_THIS(neRigidBody_, rb); return rb.GetPos(); } /**************************************************************************** * * neRigidBody::SetPos * ****************************************************************************/ void neRigidBody::SetPos(const neV3 & p) { CAST_THIS(neRigidBody_, rb); rb.SetPos(p); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::GetRotationM3 * ****************************************************************************/ neM3 neRigidBody::GetRotationM3() { CAST_THIS(neRigidBody_, rb); return rb.State().rot(); } /**************************************************************************** * * neRigidBody::GetRotationQ * ****************************************************************************/ neQ neRigidBody::GetRotationQ() { CAST_THIS(neRigidBody_, rb); return rb.State().q; } /**************************************************************************** * * neRigidBody::SetRotation * ****************************************************************************/ void neRigidBody::SetRotation(const neM3 & m) { ASSERT(m.IsOrthogonalNormal()); CAST_THIS(neRigidBody_, rb); rb.State().rot() = m; rb.State().q.SetupFromMatrix3(m); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::SetRotation * ****************************************************************************/ void neRigidBody::SetRotation(const neQ & q) { CAST_THIS(neRigidBody_, rb); rb.State().q = q; rb.State().rot() = q.BuildMatrix3(); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::GetTransform * ****************************************************************************/ neT3 neRigidBody::GetTransform() { CAST_THIS(neRigidBody_, rb); rb.State().b2w.rot[0].v[3] = 0.0f; rb.State().b2w.rot[1].v[3] = 0.0f; rb.State().b2w.rot[2].v[3] = 0.0f; rb.State().b2w.pos.v[3] = 1.0f; return rb.State().b2w; } /**************************************************************************** * * neRigidBody::GetVelocity * ****************************************************************************/ neV3 neRigidBody::GetVelocity() { CAST_THIS(neRigidBody_, rb); return rb.Derive().linearVel; } /**************************************************************************** * * neRigidBody::SetVelocity * ****************************************************************************/ void neRigidBody::SetVelocity(const neV3 & v) { CAST_THIS(neRigidBody_, rb); rb.Derive().linearVel = v; rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::GetAngularVelocity * ****************************************************************************/ neV3 neRigidBody::GetAngularVelocity() { CAST_THIS(neRigidBody_, rb); return rb.Derive().angularVel; } /**************************************************************************** * * neRigidBody::GetAngularMomentum * ****************************************************************************/ neV3 neRigidBody::GetAngularMomentum() { CAST_THIS(neRigidBody_, rb); return rb.State().angularMom; } /**************************************************************************** * * neRigidBody::SetAngularMomemtum * ****************************************************************************/ void neRigidBody::SetAngularMomentum(const neV3& am) { CAST_THIS(neRigidBody_, rb); rb.SetAngMom(am); rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::GetVelocityAtPoint * ****************************************************************************/ neV3 neRigidBody::GetVelocityAtPoint(const neV3 & pt) { CAST_THIS(neRigidBody_, rb); return rb.VelocityAtPoint(pt); } /**************************************************************************** * * neRigidBody::UpdateBoundingInfo * ****************************************************************************/ void neRigidBody::UpdateBoundingInfo() { CAST_THIS(neRigidBodyBase, rb); rb.RecalcBB(); } /**************************************************************************** * * neRigidBody::UpdateInertiaTensor * ****************************************************************************/ void neRigidBody::UpdateInertiaTensor() { CAST_THIS(neRigidBody_, rb); rb.RecalcInertiaTensor(); } /**************************************************************************** * * neRigidBody::SetForce * ****************************************************************************/ void neRigidBody::SetForce(const neV3 & force, const neV3 & pos) { CAST_THIS(neRigidBody_, rb); if (force.IsConsiderZero()) { rb.force = force; rb.torque = ((pos - rb.GetPos()).Cross(force)); return; } rb.force = force; rb.torque = ((pos - rb.GetPos()).Cross(force)); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::SetForce * ****************************************************************************/ void neRigidBody::SetTorque(const neV3 & torque) { CAST_THIS(neRigidBody_, rb); if (torque.IsConsiderZero()) { rb.torque = torque; return; } rb.torque = torque; rb.WakeUp(); } /**************************************************************************** * * neRigidBody::ApplyForceCOG * ****************************************************************************/ void neRigidBody::SetForce(const neV3 & force) { CAST_THIS(neRigidBody_, rb); if (force.IsConsiderZero()) { rb.force = force; return; } rb.force = force; rb.WakeUp(); } neV3 neRigidBody::GetForce() { CAST_THIS(neRigidBody_, rb); return rb.force; } neV3 neRigidBody::GetTorque() { CAST_THIS(neRigidBody_, rb); return rb.torque; } /**************************************************************************** * * neRigidBody::AddImpulse * ****************************************************************************/ void neRigidBody::ApplyImpulse(const neV3 & impulse) { CAST_THIS(neRigidBody_, rb); neV3 dv = impulse * rb.oneOnMass; rb.Derive().linearVel += dv; //rb.WakeUp(); rb.WakeUpAllJoint(); } /**************************************************************************** * * neRigidBody::AddImpulseWithTwist * ****************************************************************************/ void neRigidBody::ApplyImpulse(const neV3 & impulse, const neV3 & pos) { CAST_THIS(neRigidBody_, rb); neV3 dv = impulse * rb.oneOnMass; neV3 da = (pos - rb.GetPos()).Cross(impulse); rb.Derive().linearVel += dv; neV3 newAM = rb.State().angularMom + da; rb.SetAngMom(newAM); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::ApplyTwist * ****************************************************************************/ void neRigidBody::ApplyTwist(const neV3 & twist) { CAST_THIS(neRigidBody_, rb); neV3 newAM = twist; rb.SetAngMom(newAM); rb.WakeUp(); } /**************************************************************************** * * neRigidBody::AddController * ****************************************************************************/ neRigidBodyController * neRigidBody::AddController(neRigidBodyControllerCallback * controller, s32 period) { CAST_THIS(neRigidBody_, rb); return (neRigidBodyController *)rb.AddController(controller, period); } /**************************************************************************** * * neRigidBody::RemoveController * ****************************************************************************/ neBool neRigidBody::RemoveController(neRigidBodyController * rbController) { CAST_THIS(neRigidBody_, rb); if (!rb.controllers) return false; neControllerItem * ci = (neControllerItem *)rb.controllers; while (ci) { neController * con = reinterpret_cast<neController *>(ci); ci = ci->next; if (con == reinterpret_cast<neController *>(rbController)) { //reinterpret_cast<neControllerItem *>(con)->Remove(); rb.sim->controllerHeap.Dealloc(con, 1); return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateController * ****************************************************************************/ void neRigidBody::BeginIterateController() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateController(); } /**************************************************************************** * * neRigidBody::GetNextController * ****************************************************************************/ neRigidBodyController * neRigidBody::GetNextController() { CAST_THIS(neRigidBody_, rb); return (neRigidBodyController *)rb.GetNextController(); } /**************************************************************************** * * neRigidBody::GravityEnable * ****************************************************************************/ void neRigidBody::GravityEnable(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.GravityEnable(yes); } /**************************************************************************** * * neRigidBody::GravityEnable * ****************************************************************************/ neBool neRigidBody::GravityEnable() { CAST_THIS(neRigidBody_, rb); return rb.gravityOn; } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ void neRigidBody::CollideConnected(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.CollideConnected(yes); } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ neBool neRigidBody::CollideConnected() { CAST_THIS(neRigidBody_, rb); return rb.CollideConnected(); } /**************************************************************************** * * neRigidBody::CollideDirectlyConnected * ****************************************************************************/ void neRigidBody::CollideDirectlyConnected(neBool yes) { CAST_THIS(neRigidBody_, rb); rb.isCollideDirectlyConnected = yes; } /**************************************************************************** * * neRigidBody::CollideConnected * ****************************************************************************/ neBool neRigidBody::CollideDirectlyConnected() { CAST_THIS(neRigidBody_, rb); return rb.isCollideDirectlyConnected; } /**************************************************************************** * * neRigidBody::AddGeometry * ****************************************************************************/ neGeometry * neRigidBody::AddGeometry() { CAST_THIS(neRigidBody_, rb); TConvex * g = rb.AddGeometry(); return reinterpret_cast<neGeometry *>(g); } /**************************************************************************** * * neRigidBody::RemoveGeometry * ****************************************************************************/ neBool neRigidBody::RemoveGeometry(neGeometry * g) { CAST_THIS(neRigidBody_, rb); if (!rb.col.convex) return false; TConvexItem * gi = (TConvexItem *)rb.col.convex; while (gi) { TConvex * convex = reinterpret_cast<TConvex *>(gi); gi = gi->next; if (convex == reinterpret_cast<TConvex *>(g)) { if (rb.col.convex == convex) { rb.col.convex = (TConvex*)gi; } rb.sim->geometryHeap.Dealloc(convex, 1); rb.col.convexCount--; if (rb.col.convexCount == 0) { rb.col.convex = NULL; if (rb.IsInRegion() && !rb.isCustomCD) rb.sim->region.RemoveBody(&rb); } return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateGeometry * ****************************************************************************/ void neRigidBody::BeginIterateGeometry() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateGeometry(); } /**************************************************************************** * * neRigidBody::GetNextGeometry * ****************************************************************************/ neGeometry * neRigidBody::GetNextGeometry() { CAST_THIS(neRigidBody_, rb); return reinterpret_cast<neGeometry *>(rb.GetNextGeometry()); } /**************************************************************************** * * neRigidBody::BreakGeometry * ****************************************************************************/ neRigidBody * neRigidBody::BreakGeometry(neGeometry * g) { CAST_THIS(neRigidBody_, rb); neRigidBody_ * newBody = rb.sim->CreateRigidBodyFromConvex((TConvex*)g, &rb); return (neRigidBody *)newBody; } /**************************************************************************** * * neRigidBody::UseCustomCollisionDetection * ****************************************************************************/ void neRigidBody::UseCustomCollisionDetection(neBool yes, const neT3 * obb, f32 boundingRadius) { CAST_THIS(neRigidBody_, rb); if (yes) { rb.obb = *obb; rb.col.boundingRadius = boundingRadius; rb.isCustomCD = yes; if (rb.isActive && !rb.IsInRegion()) { rb.sim->region.AddBody(&rb, NULL); } } else { rb.isCustomCD = yes; this->UpdateBoundingInfo(); if (rb.IsInRegion() && GetGeometryCount() == 0) { rb.sim->region.RemoveBody(&rb); } } } /**************************************************************************** * * neRigidBody::UseCustomCollisionDetection * ****************************************************************************/ neBool neRigidBody::UseCustomCollisionDetection() { CAST_THIS(neRigidBody_, rb); return rb.isCustomCD; } /**************************************************************************** * * neRigidBody::AddSensor * ****************************************************************************/ neSensor * neRigidBody::AddSensor() { CAST_THIS(neRigidBody_, rb); neSensor_ * s = rb.AddSensor(); return reinterpret_cast<neSensor *>(s); } /**************************************************************************** * * neRigidBody::RemoveSensor * ****************************************************************************/ neBool neRigidBody::RemoveSensor(neSensor * s) { CAST_THIS(neRigidBody_, rb); if (!rb.sensors) return false; neSensorItem * si = (neSensorItem *)rb.sensors; while (si) { neSensor_ * sensor = reinterpret_cast<neSensor_ *>(si); si = si->next; if (sensor == reinterpret_cast<neSensor_ *>(s)) { //reinterpret_cast<neSensorItem *>(s)->Remove(); rb.sim->sensorHeap.Dealloc(sensor, 1); return true; } } return false; } /**************************************************************************** * * neRigidBody::BeginIterateSensor * ****************************************************************************/ void neRigidBody::BeginIterateSensor() { CAST_THIS(neRigidBody_, rb); rb.BeginIterateSensor(); } /**************************************************************************** * * neRigidBody::GetNextSensor * ****************************************************************************/ neSensor * neRigidBody::GetNextSensor() { CAST_THIS(neRigidBody_, rb); return reinterpret_cast<neSensor *>(rb.GetNextSensor()); } /**************************************************************************** * * neRigidBody::Active * ****************************************************************************/ void neRigidBody::Active(neBool yes, neRigidBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neRigidBody::Active * ****************************************************************************/ void neRigidBody::Active(neBool yes, neAnimatedBody * hint) { CAST_THIS(neRigidBodyBase, ab); ab.Active(yes, (neRigidBodyBase *)hint); } /**************************************************************************** * * neAnimatedBody::IsActive * ****************************************************************************/ neBool neRigidBody::Active() { CAST_THIS(neRigidBodyBase, ab); return ab.isActive; } neBool neRigidBody::IsIdle() { CAST_THIS(neRigidBody_, rb); return (rb.status == neRigidBody_::NE_RBSTATUS_IDLE); } /**************************************************************************** * * neSimulator::CreateSimulator * ****************************************************************************/ neSimulator * neSimulator::CreateSimulator(const neSimulatorSizeInfo & sizeInfo, neAllocatorAbstract * alloc, const neV3 * grav) { neFixedTimeStepSimulator * s = new neFixedTimeStepSimulator(sizeInfo, alloc, grav); return reinterpret_cast<neSimulator*>(s); } /**************************************************************************** * * neSimulator::DestroySimulator(neSimulator * sim); * ****************************************************************************/ void neSimulator::DestroySimulator(neSimulator * sim) { neFixedTimeStepSimulator * s = reinterpret_cast<neFixedTimeStepSimulator *>(sim); delete s; } /**************************************************************************** * * neSimulator::Gravity * ****************************************************************************/ neV3 neSimulator::Gravity() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.gravity; } /**************************************************************************** * * neSimulator::Gravity * ****************************************************************************/ void neSimulator::Gravity(const neV3 & g) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetGravity(g); /* sim.gravity = g; sim.gravityVector = g; sim.gravityVector.Normalize(); */ } /**************************************************************************** * * neSimulator::CreateRigidBody * ****************************************************************************/ neRigidBody * neSimulator::CreateRigidBody() { CAST_THIS(neFixedTimeStepSimulator, sim); neRigidBody_ * ret = sim.CreateRigidBody(); return reinterpret_cast<neRigidBody *>(ret); } /**************************************************************************** * * neSimulator::CreateRigidParticle * ****************************************************************************/ neRigidBody * neSimulator::CreateRigidParticle() { CAST_THIS(neFixedTimeStepSimulator, sim); neRigidBody_ * ret = sim.CreateRigidBody(true); return reinterpret_cast<neRigidBody *>(ret); } /**************************************************************************** * * neSimulator::CreateCollisionBody() * ****************************************************************************/ neAnimatedBody * neSimulator::CreateAnimatedBody() { CAST_THIS(neFixedTimeStepSimulator, sim); neCollisionBody_ * ret = sim.CreateCollisionBody(); return reinterpret_cast<neAnimatedBody *>(ret); } /**************************************************************************** * * neSimulator::FreeBody * ****************************************************************************/ void neSimulator::FreeRigidBody(neRigidBody * body) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Free(reinterpret_cast<neRigidBody_*>(body)); } /**************************************************************************** * * neSimulator::FreeCollisionBody * ****************************************************************************/ void neSimulator::FreeAnimatedBody(neAnimatedBody * body) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Free(reinterpret_cast<neRigidBody_*>(body)); } /**************************************************************************** * * neSimulator::GetCollisionTable * ****************************************************************************/ neCollisionTable * neSimulator::GetCollisionTable() { CAST_THIS(neFixedTimeStepSimulator, sim); return (neCollisionTable *)(&sim.colTable); } /**************************************************************************** * * neSimulator::GetMaterial * ****************************************************************************/ bool neSimulator::SetMaterial(s32 index, f32 friction, f32 restitution) { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.SetMaterial(index, friction, restitution, 0.0f); } /**************************************************************************** * * neSimulator::GetMaterial * ****************************************************************************/ bool neSimulator::GetMaterial(s32 index, f32& friction, f32& restitution) { CAST_THIS(neFixedTimeStepSimulator, sim); f32 density; return sim.GetMaterial(index, friction, restitution, density); } /**************************************************************************** * * neSimulator::Advance * ****************************************************************************/ void neSimulator::Advance(f32 sec, s32 step, nePerformanceReport * perfReport) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Advance(sec, step, perfReport); } void neSimulator::Advance(f32 sec, f32 minTimeStep, f32 maxTimeStep, nePerformanceReport * perfReport) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.Advance(sec, minTimeStep, maxTimeStep, perfReport); } /**************************************************************************** * * neSimulator::SetTerrainMesh * ****************************************************************************/ void neSimulator::SetTerrainMesh(neTriangleMesh * tris) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetTerrainMesh(tris); } void neSimulator::FreeTerrainMesh() { CAST_THIS(neFixedTimeStepSimulator, sim); sim.FreeTerrainMesh(); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neRigidBody * bodyB) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; if (!bodyB) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); constr->bodyB = (neRigidBodyBase*)bodyB; neRigidBody_ * bb = (neRigidBody_*)bodyB; bb->constraintCollection.Add(&constr->bodyBHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::CreateJoint * ****************************************************************************/ neJoint * neSimulator::CreateJoint(neRigidBody * bodyA, neAnimatedBody * bodyB) { CAST_THIS(neFixedTimeStepSimulator, sim); if (!bodyA) return NULL; if (!bodyB) return NULL; _neConstraint * constr = sim.constraintHeap.Alloc(1); // 1 means make it solo if (!constr) { sprintf(sim.logBuffer, MSG_CONSTRAINT_FULL); sim.LogOutput(neSimulator::LOG_OUTPUT_LEVEL_ONE); return NULL; } constr->Reset(); constr->sim = &sim; constr->bodyA = (neRigidBody_*)bodyA; neRigidBody_ * ba = (neRigidBody_*)bodyA; ba->constraintCollection.Add(&constr->bodyAHandle); constr->bodyB = (neRigidBodyBase*)bodyB; neRigidBodyBase * bb = (neRigidBodyBase*)bodyB; bb->constraintCollection.Add(&constr->bodyBHandle); return reinterpret_cast<neJoint*>(constr); } /**************************************************************************** * * neSimulator::FreeJoint * ****************************************************************************/ void neSimulator::FreeJoint(neJoint * constraint) { CAST_THIS(neFixedTimeStepSimulator, sim); _neConstraint * c = (_neConstraint *)constraint; ASSERT(sim.constraintHeap.CheckBelongAndInUse(c)); if (c->bodyA) { c->bodyA->constraintCollection.Remove(&c->bodyAHandle); if (c->bodyB) c->bodyB->constraintCollection.Remove(&c->bodyBHandle); neConstraintHeader * h = c->bodyA->GetConstraintHeader(); if (h) { h->Remove(c); h->flag = neConstraintHeader::FLAG_NEED_REORG; } sim.constraintHeap.Dealloc(c, 1); if (c->bodyA->constraintCollection.count == 0) c->bodyA->RemoveConstraintHeader(); if (c->bodyB && c->bodyB->constraintCollection.count == 0) c->bodyB->RemoveConstraintHeader(); } else { sim.constraintHeap.Dealloc(c, 1); } } /**************************************************************************** * * neSimulator::SetCollisionCallback * ****************************************************************************/ void neSimulator::SetCollisionCallback(neCollisionCallback * fn) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetCollisionCallback(fn); } /**************************************************************************** * * neSimulator::GetCollisionCallback * ****************************************************************************/ neCollisionCallback * neSimulator::GetCollisionCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.collisionCallback; } /**************************************************************************** * * neSimulator::SetBreakageCallback * ****************************************************************************/ void neSimulator::SetBreakageCallback(neBreakageCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.breakageCallback = cb; } /**************************************************************************** * * neSimulator::GetBreakageCallback * ****************************************************************************/ neBreakageCallback * neSimulator::GetBreakageCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.breakageCallback; } /**************************************************************************** * * neSimulator::SetTerrainTriangleQueryCallback * ****************************************************************************/ void neSimulator::SetTerrainTriangleQueryCallback(neTerrainTriangleQueryCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.terrainQueryCallback = cb; } /**************************************************************************** * * neSimulator::GetTerrainTriangleQueryCallback * ****************************************************************************/ neTerrainTriangleQueryCallback * neSimulator::GetTerrainTriangleQueryCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.terrainQueryCallback; } /**************************************************************************** * * neSimulator::SetCustomCDRB2RBCallback * ****************************************************************************/ void neSimulator::SetCustomCDRB2RBCallback(neCustomCDRB2RBCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.customCDRB2RBCallback = cb; } /**************************************************************************** * * neSimulator::GetCustomCDRB2RBCallback * ****************************************************************************/ neCustomCDRB2RBCallback * neSimulator::GetCustomCDRB2RBCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.customCDRB2RBCallback; } /**************************************************************************** * * neSimulator::SetCustomCDRB2ABCallback * ****************************************************************************/ void neSimulator::SetCustomCDRB2ABCallback(neCustomCDRB2ABCallback * cb) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.customCDRB2ABCallback = cb; } /**************************************************************************** * * neSimulator::GetCustomCDRB2ABCallback * ****************************************************************************/ neCustomCDRB2ABCallback * neSimulator::GetCustomCDRB2ABCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.customCDRB2ABCallback; } /**************************************************************************** * * neSimulator::SetLogOutputCallback * ****************************************************************************/ void neSimulator::SetLogOutputCallback(neLogOutputCallback * fn) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetLogOutputCallback(fn); } /* f32 neSimulator::GetMagicNumber() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.magicNumber; } */ /**************************************************************************** * * neSimulator::GetLogOutputCallback * ****************************************************************************/ neLogOutputCallback * neSimulator::GetLogOutputCallback() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.logCallback; } /**************************************************************************** * * neSimulator::SetLogOutputLevel * ****************************************************************************/ void neSimulator::SetLogOutputLevel(LOG_OUTPUT_LEVEL lvl) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.SetLogOutputLevel(lvl); } /**************************************************************************** * * neSimulator::GetCurrentSizeInfo * ****************************************************************************/ neSimulatorSizeInfo neSimulator::GetCurrentSizeInfo() { CAST_THIS(neFixedTimeStepSimulator, sim); neSimulatorSizeInfo ret; ret.rigidBodiesCount = sim.rigidBodyHeap.GetUsedCount(); ret.animatedBodiesCount = sim.collisionBodyHeap.GetUsedCount(); ret.rigidParticleCount = sim.rigidParticleHeap.GetUsedCount(); ret.controllersCount = sim.controllerHeap.GetUsedCount(); ret.overlappedPairsCount = sim.region.overlappedPairs.GetUsedCount(); ret.geometriesCount = sim.geometryHeap.GetUsedCount(); ret.constraintsCount = sim.constraintHeap.GetUsedCount(); ret.constraintSetsCount = sim.constraintHeaders.GetUsedCount(); // ret.constraintBufferSize = sim.miniConstraintHeap.GetUsedCount(); ret.sensorsCount = sim.sensorHeap.GetUsedCount(); ret.terrainNodesStartCount = sim.region.terrainTree.nodes.GetUsedCount(); ret.terrainNodesGrowByCount = sim.sizeInfo.terrainNodesGrowByCount; return ret; } /**************************************************************************** * * neSimulator::GetStartSizeInfo * ****************************************************************************/ neSimulatorSizeInfo neSimulator::GetStartSizeInfo() { CAST_THIS(neFixedTimeStepSimulator, sim); return sim.sizeInfo; } /**************************************************************************** * * neSimulator::GetMemoryUsage * ****************************************************************************/ void neSimulator::GetMemoryAllocated(s32 & memoryAllocated) { CAST_THIS(neFixedTimeStepSimulator, sim); sim.GetMemoryAllocated(memoryAllocated); } /**************************************************************************** * * neJoint::SetType * ****************************************************************************/ void neJoint::SetType(ConstraintType t) { CAST_THIS(_neConstraint, c); c.SetType(t); } /**************************************************************************** * * neJoint::GetType * ****************************************************************************/ neJoint::ConstraintType neJoint::GetType() { CAST_THIS(_neConstraint, c); return c.type; } /**************************************************************************** * * neJoint::GetRigidBodyA * ****************************************************************************/ neRigidBody * neJoint::GetRigidBodyA() { CAST_THIS(_neConstraint, c); return reinterpret_cast<neRigidBody *>(c.bodyA); } /**************************************************************************** * * neJoint::GetRigidBodyB * ****************************************************************************/ neRigidBody * neJoint::GetRigidBodyB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) return NULL; if (c.bodyB->AsCollisionBody()) return NULL; return reinterpret_cast<neRigidBody *>(c.bodyB); } /**************************************************************************** * * neJoint::GetAnimatedBodyB * ****************************************************************************/ neAnimatedBody * neJoint::GetAnimatedBodyB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) return NULL; if (c.bodyB->AsRigidBody()) return NULL; return reinterpret_cast<neAnimatedBody *>(c.bodyB); } /**************************************************************************** * * neJoint::SetJointFrameA * ****************************************************************************/ void neJoint::SetJointFrameA(const neT3 & frameA) { CAST_THIS(_neConstraint, c); c.frameA = frameA; } /**************************************************************************** * * neJoint::SetJointFrameB * ****************************************************************************/ void neJoint::SetJointFrameB(const neT3 & frameB) { CAST_THIS(_neConstraint, c); c.frameB = frameB; } void neJoint::SetJointFrameWorld(const neT3 & frame) { CAST_THIS(_neConstraint, c); neT3 w2b; w2b = c.bodyA->GetB2W().FastInverse(); c.frameA = w2b * frame; if (!c.bodyB) { c.frameB = frame; return; } w2b = c.bodyB->GetB2W().FastInverse(); c.frameB = w2b * frame; } /**************************************************************************** * * neJoint::GetJointFrameA * ****************************************************************************/ neT3 neJoint::GetJointFrameA() { CAST_THIS(_neConstraint, c); if (!c.bodyA) { return c.frameA; } neT3 ret; ret = c.bodyA->State().b2w * c.frameA; return ret; } /**************************************************************************** * * neJoint::GetJointFrameB * ****************************************************************************/ neT3 neJoint::GetJointFrameB() { CAST_THIS(_neConstraint, c); if (!c.bodyB) { return c.frameB; } neT3 ret; neCollisionBody_ * cb = c.bodyB->AsCollisionBody(); if (cb) { ret = cb->b2w * c.frameB; } else { neRigidBody_ * rb = c.bodyB->AsRigidBody(); ret = rb->State().b2w * c.frameB; } return ret; } /**************************************************************************** * * neJoint::SetJointLength * ****************************************************************************/ void neJoint::SetJointLength(f32 length) { CAST_THIS(_neConstraint, c); c.jointLength = length; } /**************************************************************************** * * neJoint::GetJointLength * ****************************************************************************/ f32 neJoint::GetJointLength() { CAST_THIS(_neConstraint, c); return c.jointLength; } /**************************************************************************** * * neJoint::Enable * ****************************************************************************/ void neJoint::Enable(neBool yes) { CAST_THIS(_neConstraint, c); c.Enable(yes); } /**************************************************************************** * * neJoint::IsEnable * ****************************************************************************/ neBool neJoint::Enable() { CAST_THIS(_neConstraint, c); return c.enable; } /**************************************************************************** * * neJoint::InfiniteMassB * ****************************************************************************/ /* void neJoint::InfiniteMassB(neBool yes) { CAST_THIS(_neConstraint, c); c.InfiniteMassB(yes); } */ /**************************************************************************** * * neJoint::SetDampingFactor * ****************************************************************************/ void neJoint::SetDampingFactor(f32 damp) { CAST_THIS(_neConstraint, c); c.jointDampingFactor = damp; } /**************************************************************************** * * neJoint::GetDampingFactor * ****************************************************************************/ f32 neJoint::GetDampingFactor() { CAST_THIS(_neConstraint, c); return c.jointDampingFactor; } /**************************************************************************** * * neJoint::SetEpsilon * ****************************************************************************/ void neJoint::SetEpsilon(f32 t) { CAST_THIS(_neConstraint, c); c.accuracy = t; } /**************************************************************************** * * neJoint::GetEpsilon * ****************************************************************************/ f32 neJoint::GetEpsilon() { CAST_THIS(_neConstraint, c); if (c.accuracy <= 0.0f) return DEFAULT_CONSTRAINT_EPSILON; return c.accuracy; } /**************************************************************************** * * neJoint::SetIteration2 * ****************************************************************************/ void neJoint::SetIteration(s32 i) { CAST_THIS(_neConstraint, c); c.iteration = i; } /**************************************************************************** * * neJoint::GetIteration2 * ****************************************************************************/ s32 neJoint::GetIteration() { CAST_THIS(_neConstraint, c); return c.iteration; } /**************************************************************************** * * neJoint::GetUpperLimit * ****************************************************************************/ f32 neJoint::GetUpperLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].upperLimit; } /**************************************************************************** * * neJoint::SetUpperLimit * ****************************************************************************/ void neJoint::SetUpperLimit(f32 upperLimit) { CAST_THIS(_neConstraint, c); c.limitStates[0].upperLimit = upperLimit; } /**************************************************************************** * * neJoint::GetLowerLimit * ****************************************************************************/ f32 neJoint::GetLowerLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].lowerLimit; } /**************************************************************************** * * neJoint::SetLowerLimit * ****************************************************************************/ void neJoint::SetLowerLimit(f32 lowerLimit) { CAST_THIS(_neConstraint, c); c.limitStates[0].lowerLimit = lowerLimit; } /**************************************************************************** * * neJoint::IsEnableLimit * ****************************************************************************/ neBool neJoint::EnableLimit() { CAST_THIS(_neConstraint, c); return c.limitStates[0].enableLimit; } /**************************************************************************** * * neJoint::EnableLimite * ****************************************************************************/ void neJoint::EnableLimit(neBool yes) { CAST_THIS(_neConstraint, c); c.limitStates[0].enableLimit = yes; } /**************************************************************************** * * neJoint::GetUpperLimit2 * ****************************************************************************/ f32 neJoint::GetUpperLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].upperLimit; } /**************************************************************************** * * neJoint::SetUpperLimit2 * ****************************************************************************/ void neJoint::SetUpperLimit2(f32 upperLimit) { CAST_THIS(_neConstraint, c); c.limitStates[1].upperLimit = upperLimit; } /**************************************************************************** * * neJoint::GetLowerLimit2 * ****************************************************************************/ f32 neJoint::GetLowerLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].lowerLimit; } /**************************************************************************** * * neJoint::SetLowerLimit2 * ****************************************************************************/ void neJoint::SetLowerLimit2(f32 lowerLimit) { CAST_THIS(_neConstraint, c); c.limitStates[1].lowerLimit = lowerLimit; } /**************************************************************************** * * neJoint::IsEnableLimit2 * ****************************************************************************/ neBool neJoint::EnableLimit2() { CAST_THIS(_neConstraint, c); return c.limitStates[1].enableLimit; } /**************************************************************************** * * neJoint::EnableMotor * ****************************************************************************/ neBool neJoint::EnableMotor() { CAST_THIS(_neConstraint, c); return c.motors[0].enable; } /**************************************************************************** * * neJoint::EnableMotor * ****************************************************************************/ void neJoint::EnableMotor(neBool yes) { CAST_THIS(_neConstraint, c); c.motors[0].enable = yes; } /**************************************************************************** * * neJoint::SetMotor * ****************************************************************************/ void neJoint::SetMotor(MotorType motorType, f32 desireValue, f32 maxForce) { CAST_THIS(_neConstraint, c); c.motors[0].motorType = motorType; c.motors[0].desireVelocity = desireValue; c.motors[0].maxForce = neAbs(maxForce); } /**************************************************************************** * * neJoint::GetMotor * ****************************************************************************/ void neJoint::GetMotor(MotorType & motorType, f32 & desireValue, f32 & maxForce) { CAST_THIS(_neConstraint, c); motorType = c.motors[0].motorType; desireValue = c.motors[0].desireVelocity; maxForce = c.motors[0].maxForce; } /**************************************************************************** * * neJoint::EnableMotor2 * ****************************************************************************/ neBool neJoint::EnableMotor2() { CAST_THIS(_neConstraint, c); return c.motors[1].enable; } /**************************************************************************** * * neJoint::EnableMotor2 * ****************************************************************************/ void neJoint::EnableMotor2(neBool yes) { CAST_THIS(_neConstraint, c); c.motors[1].enable = yes; } /**************************************************************************** * * neJoint::SetMotor2 * ****************************************************************************/ void neJoint::SetMotor2(MotorType motorType, f32 desireValue, f32 maxForce) { CAST_THIS(_neConstraint, c); c.motors[1].motorType = motorType; c.motors[1].desireVelocity = desireValue; c.motors[1].maxForce = neAbs(maxForce); } /**************************************************************************** * * neJoint::GetMotor2 * ****************************************************************************/ void neJoint::GetMotor2(MotorType & motorType, f32 & desireValue, f32 & maxForce) { CAST_THIS(_neConstraint, c); motorType = c.motors[1].motorType; desireValue = c.motors[1].desireVelocity; maxForce = c.motors[1].maxForce; } /**************************************************************************** * * neJoint::EnableLimite * ****************************************************************************/ void neJoint::EnableLimit2(neBool yes) { CAST_THIS(_neConstraint, c); c.limitStates[1].enableLimit = yes; } /**************************************************************************** * * neJoint::AddController * ****************************************************************************/ neJointController * neJoint::AddController(neJointControllerCallback * controller, s32 period) { CAST_THIS(_neConstraint, c); return (neJointController *)c.AddController(controller, period); } /**************************************************************************** * * neJoint::RemoveController * ****************************************************************************/ neBool neJoint::RemoveController(neJointController * jController) { CAST_THIS(_neConstraint, c); if (!c.controllers) return false; neControllerItem * ci = (neControllerItem *)c.controllers; while (ci) { neController * con = reinterpret_cast<neController *>(ci); ci = ci->next; if (con == reinterpret_cast<neController *>(jController)) { //reinterpret_cast<neControllerItem *>(con)->Remove(); c.sim->controllerHeap.Dealloc(con, 1); return true; } } return false; } /**************************************************************************** * * neJoint::BeginIterateController * ****************************************************************************/ void neJoint::BeginIterateController() { CAST_THIS(_neConstraint, c); c.BeginIterateController(); } /**************************************************************************** * * neJoint::GetNextController * ****************************************************************************/ neJointController * neJoint::GetNextController() { CAST_THIS(_neConstraint, c); return (neJointController *)c.GetNextController(); } /**************************************************************************** * * neJoint::SetBSPoints * ****************************************************************************/ /* neBool neJoint::SetBSPoints(const neV3 & pointA, const neV3 & pointB) { CAST_THIS(_neConstraint, c); if (c.type != NE_Constraint_BALLSOCKET) return false; c.cpointsA[0].PtBody() = pointA; c.cpointsB[0].PtBody() = pointB; return true; } */ /**************************************************************************** * * neJoint::SetHingePoints * ****************************************************************************/ /* neBool neJoint::SetHingePoints(const neV3 & pointA1, const neV3 & pointA2, const neV3 & pointB1, const neV3 & pointB2) { CAST_THIS(_neConstraint, c); if (c.type != NE_Constraint_HINGE) return false; c.cpointsA[0].PtBody() = pointA1; c.cpointsA[1].PtBody() = pointA2; c.cpointsB[0].PtBody() = pointB1; c.cpointsB[1].PtBody() = pointB2; return true; } */ /**************************************************************************** * * neSensor::SetLineSensor * ****************************************************************************/ void neSensor::SetLineSensor(const neV3 & pos, const neV3 & lineVector) { CAST_THIS(neSensor_, sensor); sensor.pos = pos; sensor.dir = lineVector; sensor.dirNormal = lineVector; sensor.dirNormal.Normalize(); sensor.length = lineVector.Length(); } /**************************************************************************** * * neSensor::SetUserData * ****************************************************************************/ void neSensor::SetUserData(u32 cookies) { CAST_THIS(neSensor_, sensor); sensor.cookies = cookies; } /**************************************************************************** * * neSensor::GetUserData * ****************************************************************************/ u32 neSensor::GetUserData() { CAST_THIS(neSensor_, sensor); return sensor.cookies; } /**************************************************************************** * * neSensor::GetLineNormal * ****************************************************************************/ neV3 neSensor::GetLineVector() { CAST_THIS(neSensor_, sensor); return sensor.dir; } /**************************************************************************** * * neSensor::GetLineNormal * ****************************************************************************/ neV3 neSensor::GetLineUnitVector() { CAST_THIS(neSensor_, sensor); return sensor.dirNormal ; } /**************************************************************************** * * neSensor::GetLinePos * ****************************************************************************/ neV3 neSensor::GetLinePos() { CAST_THIS(neSensor_, sensor); return sensor.pos; } /**************************************************************************** * * neSensor::GetDetectDepth * ****************************************************************************/ f32 neSensor::GetDetectDepth() { CAST_THIS(neSensor_, sensor); return sensor.depth; } /**************************************************************************** * * neSensor::GetDetectNormal * ****************************************************************************/ neV3 neSensor::GetDetectNormal() { CAST_THIS(neSensor_, sensor); return sensor.normal; } /**************************************************************************** * * neSensor::GetDetectContactPoint * ****************************************************************************/ neV3 neSensor::GetDetectContactPoint() { CAST_THIS(neSensor_, sensor); return sensor.contactPoint; } /**************************************************************************** * * neSensor::GetDetectRigidBody * ****************************************************************************/ neRigidBody * neSensor::GetDetectRigidBody() { CAST_THIS(neSensor_, sensor); if (!sensor.body) return NULL; if (sensor.body->AsCollisionBody()) return NULL; return (neRigidBody *)sensor.body; } /**************************************************************************** * * neSensor::GetDetectAnimatedBody * ****************************************************************************/ neAnimatedBody * neSensor::GetDetectAnimatedBody() { CAST_THIS(neSensor_, sensor); if (!sensor.body) return NULL; if (sensor.body->AsRigidBody()) return NULL; return (neAnimatedBody *)sensor.body; } /**************************************************************************** * * neSensor:: * ****************************************************************************/ s32 neSensor::GetDetectMaterial() { CAST_THIS(neSensor_, sensor); return sensor.materialID; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neRigidBody * neRigidBodyController::GetRigidBody() { CAST_THIS(neController, c); return (neRigidBody *)c.rb; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neV3 neRigidBodyController::GetControllerForce() { CAST_THIS(neController, c); return c.forceA; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ neV3 neRigidBodyController::GetControllerTorque() { CAST_THIS(neController, c); return c.torqueA; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerForce(const neV3 & force) { CAST_THIS(neController, c); c.forceA = force; } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerForceWithTorque(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceA = force; c.torqueA = ((pos - c.rb->GetPos()).Cross(force)); } /**************************************************************************** * * neRigidBodyController:: * ****************************************************************************/ void neRigidBodyController::SetControllerTorque(const neV3 & torque) { CAST_THIS(neController, c); c.torqueA = torque; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neJoint * neJointController::GetJoint() { CAST_THIS(neController, c); return (neJoint *)c.constraint; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerForceBodyA() { CAST_THIS(neController, c); return c.forceA; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerForceBodyB() { CAST_THIS(neController, c); return c.forceB; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerTorqueBodyA() { CAST_THIS(neController, c); return c.torqueA; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ neV3 neJointController::GetControllerTorqueBodyB() { CAST_THIS(neController, c); return c.torqueB; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceBodyA(const neV3 & force) { CAST_THIS(neController, c); c.forceA = force; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceWithTorqueBodyA(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceA = force; c.torqueA = ((pos - c.constraint->bodyA->GetPos()).Cross(force)); } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceWithTorqueBodyB(const neV3 & force, const neV3 & pos) { CAST_THIS(neController, c); c.forceB = force; if (c.constraint->bodyB && !c.constraint->bodyB->AsCollisionBody()) { neRigidBody_ * rb = (neRigidBody_*)c.constraint->bodyB; c.torqueB = ((pos - rb->GetPos()).Cross(force)); } } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerForceBodyB(const neV3 & force) { CAST_THIS(neController, c); c.forceB = force; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerTorqueBodyA(const neV3 & torque) { CAST_THIS(neController, c); c.torqueA = torque; } /**************************************************************************** * * neJointController:: * ****************************************************************************/ void neJointController::SetControllerTorqueBodyB(const neV3 & torque) { CAST_THIS(neController, c); c.torqueB = torque; } /**************************************************************************** * * neCollisionTable::Set * ****************************************************************************/ void neCollisionTable::Set(s32 collisionID1, s32 collisionID2, neReponseBitFlag response) { CAST_THIS(neCollisionTable_, ct); ct.Set(collisionID1, collisionID2, response); } /**************************************************************************** * * neCollisionTable::Get * ****************************************************************************/ neCollisionTable::neReponseBitFlag neCollisionTable::Get(s32 collisionID1, s32 collisionID2) { CAST_THIS(neCollisionTable_, ct); ASSERT(collisionID1 < NE_COLLISION_TABLE_MAX); ASSERT(collisionID2 < NE_COLLISION_TABLE_MAX); if (collisionID1 < NE_COLLISION_TABLE_MAX && collisionID2 < NE_COLLISION_TABLE_MAX) { return ct.table[collisionID1][collisionID2]; } else { return RESPONSE_IGNORE; } } /**************************************************************************** * * neCollisionTable::GetMaxCollisionID * ****************************************************************************/ s32 neCollisionTable::GetMaxCollisionID() { return NE_COLLISION_TABLE_MAX; } /**************************************************************************** * * Helper functions * ****************************************************************************/ /**************************************************************************** * * BoxInertiaTensor * ****************************************************************************/ neV3 neBoxInertiaTensor(const neV3 & boxSize, f32 mass) { return neBoxInertiaTensor(boxSize[0], boxSize[1], boxSize[2], mass); } neV3 neBoxInertiaTensor(f32 width, f32 height, f32 depth, f32 mass) { neV3 ret; f32 maxdim = width; if (height > maxdim) maxdim = height; if (depth > maxdim) maxdim = depth; #if 0 f32 xsq = width; f32 ysq = height; f32 zsq = depth; #else f32 xsq = maxdim; f32 ysq = maxdim; f32 zsq = maxdim; #endif xsq *= xsq; ysq *= ysq; zsq *= zsq; ret[0] = (ysq + zsq) * mass / 3.0f; ret[1] = (xsq + zsq) * mass / 3.0f; ret[2] = (xsq + ysq) * mass / 3.0f; return ret; } neV3 neSphereInertiaTensor(f32 diameter, f32 mass) { f32 radius = diameter * 0.5f; f32 value = 2.0f / 5.0f * mass * radius * radius; neV3 ret; ret.Set(value); return ret; } neV3 neCylinderInertiaTensor(f32 diameter, f32 height, f32 mass) { // if (height > diameter) // { // diameter = height; // } f32 radius = diameter * 0.5f; f32 radiusSq = radius * radius; f32 Ixz = 1.0f / 12.0f * mass * height * height + 0.25f * mass * radiusSq; f32 Iyy = 0.5f * mass * radiusSq; neV3 ret; ret.Set(Ixz, Iyy, Ixz); return ret; } /* neBool IsEnableLimit(); void EnableLimit(neBool yes); f32 GetUpperLimit(); void SetUpperLimit(f32 upperLimit); f32 GetLowerLimit(); void SetLowerLimit(f32 lowerLimit); */
23.601042
129
0.399534
netpipe
edc4d3e8316cf5389f8c279780ec97dff650f17e
4,851
cpp
C++
sensing/pointcloud_preprocessor/src/downsample_filter/voxel_grid_downsample_filter_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
sensing/pointcloud_preprocessor/src/downsample_filter/voxel_grid_downsample_filter_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
sensing/pointcloud_preprocessor/src/downsample_filter/voxel_grid_downsample_filter_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2020 Tier IV, 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. /* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: voxel_grid.cpp 35876 2011-02-09 01:04:36Z rusu $ * */ #include "pointcloud_preprocessor/downsample_filter/voxel_grid_downsample_filter_nodelet.hpp" #include <pcl/kdtree/kdtree_flann.h> #include <pcl/search/kdtree.h> #include <pcl/segmentation/segment_differences.h> #include <vector> namespace pointcloud_preprocessor { VoxelGridDownsampleFilterComponent::VoxelGridDownsampleFilterComponent( const rclcpp::NodeOptions & options) : Filter("VoxelGridDownsampleFilter", options) { // set initial parameters { voxel_size_x_ = static_cast<double>(declare_parameter("voxel_size_x", 0.3)); voxel_size_y_ = static_cast<double>(declare_parameter("voxel_size_y", 0.3)); voxel_size_z_ = static_cast<double>(declare_parameter("voxel_size_z", 0.1)); } using std::placeholders::_1; set_param_res_ = this->add_on_set_parameters_callback( std::bind(&VoxelGridDownsampleFilterComponent::paramCallback, this, _1)); } void VoxelGridDownsampleFilterComponent::filter( const PointCloud2ConstPtr & input, const IndicesPtr & /*indices*/, PointCloud2 & output) { std::scoped_lock lock(mutex_); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_input(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr pcl_output(new pcl::PointCloud<pcl::PointXYZ>); pcl::fromROSMsg(*input, *pcl_input); pcl_output->points.reserve(pcl_input->points.size()); pcl::VoxelGrid<pcl::PointXYZ> filter; filter.setInputCloud(pcl_input); // filter.setSaveLeafLayout(true); filter.setLeafSize(voxel_size_x_, voxel_size_y_, voxel_size_z_); filter.filter(*pcl_output); pcl::toROSMsg(*pcl_output, output); output.header = input->header; } rcl_interfaces::msg::SetParametersResult VoxelGridDownsampleFilterComponent::paramCallback( const std::vector<rclcpp::Parameter> & p) { std::scoped_lock lock(mutex_); if (get_param(p, "voxel_size_x", voxel_size_x_)) { RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_x_); } if (get_param(p, "voxel_size_y", voxel_size_y_)) { RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_y_); } if (get_param(p, "voxel_size_z", voxel_size_z_)) { RCLCPP_DEBUG(get_logger(), "Setting new distance threshold to: %f.", voxel_size_z_); } rcl_interfaces::msg::SetParametersResult result; result.successful = true; result.reason = "success"; return result; } } // namespace pointcloud_preprocessor #include <rclcpp_components/register_node_macro.hpp> RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_preprocessor::VoxelGridDownsampleFilterComponent)
40.425
93
0.754277
meliketanrikulu
edc7747afbbb09fe4f58400834f2ad809d5c0017
1,822
cpp
C++
Tests/Unit/TestMilestone3.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
17
2018-03-29T15:24:40.000Z
2022-01-10T05:01:09.000Z
Tests/Unit/TestMilestone3.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
null
null
null
Tests/Unit/TestMilestone3.cpp
EDFilms/GCAP
4d68809efe3528cb0b9a0039d3082512400c84da
[ "MIT" ]
3
2018-04-07T06:02:05.000Z
2019-01-21T00:37:18.000Z
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "SceneTrackStatic.h" #include "TestCommon.h" #include "tinydir/tinydir.h" #include "TestCRC.h" typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef float f32; typedef double f64; typedef u8 stByte; struct SoundClass { u32 type; u32 speaker; u32 volume; u32 length; }; struct SpeakerClass { u32 type; u32 position; }; typedef u32 Speaker; typedef u32 Sound; SCENARIO("Events") { u32 recording = stCreateRecording(); stAppendSaveRecording("events.st", ST_FORMAT_BINARY, 2); SoundClass soundClass; soundClass.type = stCreateObjectType(ST_FREQUENCY_EVENT); soundClass.speaker = stAddObjectTypeComponent(soundClass.type, ST_KIND_PARENT, ST_TYPE_UINT32, 1); soundClass.volume = stAddObjectTypeComponent(soundClass.type, ST_KIND_INTENSITY, ST_TYPE_FLOAT32, 1); soundClass.length = stAddObjectTypeComponent(soundClass.type, ST_KIND_LENGTH, ST_TYPE_FLOAT32, 1); SpeakerClass speakerClass; speakerClass.type = stCreateObjectType(ST_FREQUENCY_DYNAMIC); speakerClass.position = stAddObjectTypeComponent(speakerClass.type, ST_KIND_POSITION, ST_TYPE_FLOAT32, 3); Speaker speaker = stCreateObject(speakerClass.type); stSetValue_3_float32(speaker, speakerClass.position, 3.0f, 4.0f, 5.0f); Sound sound1 = stCreateObject(soundClass.type); stSetValue_uint32(sound1, soundClass.speaker, speaker); stSubmit(1.0f); Sound sound2 = stCreateObject(soundClass.type); stSetValue_uint32(sound2, soundClass.speaker, speaker); stSubmit(1.0f); stCloseRecording(recording); }
25.661972
108
0.75247
EDFilms
edc7ce61fd54c22657f483cd36b8869abcf969aa
1,929
cpp
C++
Plugins/UE4-DialogueSystem-master/Source/DialogueSystem/Private/BTComposite_Context.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
1
2018-07-07T16:51:34.000Z
2018-07-07T16:51:34.000Z
Plugins/UE4-DialogueSystem-master/Source/DialogueSystem/Private/BTComposite_Context.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
null
null
null
Plugins/UE4-DialogueSystem-master/Source/DialogueSystem/Private/BTComposite_Context.cpp
crimsonstrife/velorum-defunct
1a6e1eab9057293da2aa045eff021d069df54c5e
[ "CC0-1.0" ]
1
2019-10-02T01:19:21.000Z
2019-10-02T01:19:21.000Z
//Copyright (c) 2016 Artem A. Mavrin and other contributors #include "DialogueSystemPrivatePCH.h" #include "BTComposite_Context.h" UBTComposite_Context::UBTComposite_Context(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { NodeName = "Context"; ExecutionMode = EContextExecutionMode::CE_Sequence; OnNextChild.BindUObject(this, &UBTComposite_Context::GetNextChildHandler); } bool UBTComposite_Context::VerifyExecution(EBTNodeResult::Type LastResult) const { if (ExecutionMode == EContextExecutionMode::CE_Sequence) return LastResult == EBTNodeResult::Succeeded; else return LastResult == EBTNodeResult::Failed; } int32 UBTComposite_Context::GetNextChildHandler(struct FBehaviorTreeSearchData& SearchData, int32 PrevChild, EBTNodeResult::Type LastResult) const { int32 NextChildIdx = BTSpecialChild::ReturnToParent; if (PrevChild == BTSpecialChild::NotInitialized) { NextChildIdx = 0; } else if (VerifyExecution(LastResult) && (PrevChild + 1) < GetChildrenNum()) { NextChildIdx = PrevChild + 1; } return NextChildIdx; } #if WITH_EDITOR FName UBTComposite_Context::GetNodeIconName() const { return FName("BTEditor.Graph.BTNode.Decorator.DoesPathExist.Icon"); } #endif FString UBTComposite_Context::GetStaticDescription() const { FString Description = ""; Description += (ExecutionMode == EContextExecutionMode::CE_Sequence) ? TEXT("Sequence \n\n") : TEXT("Selector \n\n"); for (const FBTDialogueParameter& DialogueParameter : DialogueParameters) Description += DialogueParameter.StringKey + " : " + DialogueParameter.BlackboardKey.SelectedKeyName.ToString() + TEXT(" \n"); return Description; } void UBTComposite_Context::PushArguments(FFormatNamedArguments& DialogueArguments, UBlackboardComponent * Blackboard) const { for (const FBTDialogueParameter& DialogueParameter : DialogueParameters) DialogueParameter.PushArgument(DialogueArguments, Blackboard); }
29.227273
146
0.790565
crimsonstrife
edc9c39634b83f0e12b48c78ea9bb66b3d5a3c86
10,251
cpp
C++
src/core/mp2v_hdr.cpp
fxslava/tiny_mp2v_enc
cd7f6fe8fc0652f060e466f7bb51397807c8e571
[ "MIT" ]
1
2022-02-19T15:29:18.000Z
2022-02-19T15:29:18.000Z
src/core/mp2v_hdr.cpp
fxslava/tiny_mp2v_enc
cd7f6fe8fc0652f060e466f7bb51397807c8e571
[ "MIT" ]
null
null
null
src/core/mp2v_hdr.cpp
fxslava/tiny_mp2v_enc
cd7f6fe8fc0652f060e466f7bb51397807c8e571
[ "MIT" ]
null
null
null
#include "mp2v_hdr.h" #include "misc.hpp" bool write_sequence_header(bitstream_writer_c* m_bs, sequence_header_t &sh) { m_bs->align(); m_bs->write_bits(START_CODE(sequence_header_code), 32); m_bs->write_bits(sh.horizontal_size_value, 12); m_bs->write_bits(sh.vertical_size_value, 12); m_bs->write_bits(sh.aspect_ratio_information, 4); m_bs->write_bits(sh.frame_rate_code, 4); m_bs->write_bits(sh.bit_rate_value, 18); m_bs->one_bit(); m_bs->write_bits(sh.vbv_buffer_size_value, 10); m_bs->write_bits(sh.constrained_parameters_flag, 1); m_bs->write_bits(sh.load_intra_quantiser_matrix, 1); if (sh.load_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, sh.intra_quantiser_matrix); m_bs->write_bits(sh.load_non_intra_quantiser_matrix, 1); if (sh.load_non_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, sh.non_intra_quantiser_matrix); return true; } bool write_sequence_extension(bitstream_writer_c* m_bs, sequence_extension_t &sext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(sequence_extension_id, 4); m_bs->write_bits(sext.profile_and_level_indication, 8); m_bs->write_bits(sext.progressive_sequence, 1); m_bs->write_bits(sext.chroma_format, 2); m_bs->write_bits(sext.horizontal_size_extension, 2); m_bs->write_bits(sext.vertical_size_extension, 2); m_bs->write_bits(sext.bit_rate_extension, 12); m_bs->one_bit(); m_bs->write_bits(sext.vbv_buffer_size_extension, 8); m_bs->write_bits(sext.low_delay, 1); m_bs->write_bits(sext.frame_rate_extension_n, 2); m_bs->write_bits(sext.frame_rate_extension_d, 5); return true; } bool write_sequence_display_extension(bitstream_writer_c* m_bs, sequence_display_extension_t & sdext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(sequence_display_extension_id, 4); m_bs->write_bits(sdext.video_format, 3); m_bs->write_bits(sdext.colour_description, 1); if (sdext.colour_description) { m_bs->write_bits(sdext.colour_primaries, 8); m_bs->write_bits(sdext.transfer_characteristics, 8); m_bs->write_bits(sdext.matrix_coefficients, 8); } m_bs->write_bits(sdext.display_horizontal_size, 14); m_bs->one_bit(); m_bs->write_bits(sdext.display_vertical_size, 14); return true; } bool write_sequence_scalable_extension(bitstream_writer_c* m_bs, sequence_scalable_extension_t &ssext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(sequence_scalable_extension_id, 4); m_bs->write_bits(ssext.scalable_mode, 2); m_bs->write_bits(ssext.layer_id, 4); if (ssext.scalable_mode == scalable_mode_spatial_scalability) { m_bs->write_bits(ssext.lower_layer_prediction_horizontal_size, 14); m_bs->one_bit(); m_bs->write_bits(ssext.lower_layer_prediction_vertical_size, 14); m_bs->write_bits(ssext.horizontal_subsampling_factor_m, 5); m_bs->write_bits(ssext.horizontal_subsampling_factor_n, 5); m_bs->write_bits(ssext.vertical_subsampling_factor_m, 5); m_bs->write_bits(ssext.vertical_subsampling_factor_n, 5); } if (ssext.scalable_mode == scalable_mode_temporal_scalability) { m_bs->write_bits(ssext.picture_mux_enable, 1); if (ssext.picture_mux_enable) m_bs->write_bits(ssext.mux_to_progressive_sequence, 1); m_bs->write_bits(ssext.picture_mux_order, 3); m_bs->write_bits(ssext.picture_mux_factor, 3); } return true; } bool write_group_of_pictures_header(bitstream_writer_c* m_bs, group_of_pictures_header_t &gph) { m_bs->align(); m_bs->write_bits(START_CODE(group_start_code), 32); m_bs->write_bits(gph.time_code, 25); m_bs->write_bits(gph.closed_gop, 1); m_bs->write_bits(gph.broken_link, 1); return true; } bool write_picture_header(bitstream_writer_c* m_bs, picture_header_t & ph) { m_bs->align(); m_bs->write_bits(START_CODE(picture_start_code), 32); m_bs->write_bits(ph.temporal_reference, 10); m_bs->write_bits(ph.picture_coding_type, 3); m_bs->write_bits(ph.vbv_delay, 16); if (ph.picture_coding_type == 2 || ph.picture_coding_type == 3) { m_bs->write_bits(ph.full_pel_forward_vector, 1); m_bs->write_bits(ph.forward_f_code, 3); } if (ph.picture_coding_type == 3) { m_bs->write_bits(ph.full_pel_backward_vector, 1); m_bs->write_bits(ph.backward_f_code, 3); } m_bs->zero_bit(); // skip all extra_information_picture return true; } bool write_picture_coding_extension(bitstream_writer_c* m_bs, picture_coding_extension_t &pcext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_coding_extension_id, 4); m_bs->write_bits(pcext.f_code[0][0], 4); m_bs->write_bits(pcext.f_code[0][1], 4); m_bs->write_bits(pcext.f_code[1][0], 4); m_bs->write_bits(pcext.f_code[1][1], 4); m_bs->write_bits(pcext.intra_dc_precision, 2); m_bs->write_bits(pcext.picture_structure, 2); m_bs->write_bits(pcext.top_field_first, 1); m_bs->write_bits(pcext.frame_pred_frame_dct, 1); m_bs->write_bits(pcext.concealment_motion_vectors, 1); m_bs->write_bits(pcext.q_scale_type, 1); m_bs->write_bits(pcext.intra_vlc_format, 1); m_bs->write_bits(pcext.alternate_scan, 1); m_bs->write_bits(pcext.repeat_first_field, 1); m_bs->write_bits(pcext.chroma_420_type, 1); m_bs->write_bits(pcext.progressive_frame, 1); m_bs->write_bits(pcext.composite_display_flag, 1); if (pcext.composite_display_flag) { m_bs->write_bits(pcext.v_axis, 1); m_bs->write_bits(pcext.field_sequence, 3); m_bs->write_bits(pcext.sub_carrier, 1); m_bs->write_bits(pcext.burst_amplitude, 7); m_bs->write_bits(pcext.sub_carrier_phase, 8); } return true; } bool write_quant_matrix_extension(bitstream_writer_c* m_bs, quant_matrix_extension_t &qmext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(quant_matrix_extension_id, 4); m_bs->write_bits(qmext.load_intra_quantiser_matrix, 1); if (qmext.load_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.intra_quantiser_matrix); m_bs->write_bits(qmext.load_non_intra_quantiser_matrix, 1); if (qmext.load_non_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.non_intra_quantiser_matrix); m_bs->write_bits(qmext.load_chroma_intra_quantiser_matrix, 1); if (qmext.load_chroma_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.chroma_intra_quantiser_matrix); m_bs->write_bits(qmext.load_chroma_non_intra_quantiser_matrix, 1); if (qmext.load_chroma_non_intra_quantiser_matrix) local_write_array<uint8_t, 64>(m_bs, qmext.chroma_non_intra_quantiser_matrix); return true; } bool write_picture_display_extension(bitstream_writer_c* m_bs, picture_display_extension_t &pdext, sequence_extension_t &sext, picture_coding_extension_t &pcext) { /* calculta number_of_frame_centre_offsets */ int number_of_frame_centre_offsets; if (sext.progressive_sequence == 1) { if (pcext.repeat_first_field == 1) { if (pcext.top_field_first == 1) number_of_frame_centre_offsets = 3; else number_of_frame_centre_offsets = 2; } else number_of_frame_centre_offsets = 1; } else { if (pcext.picture_structure == picture_structure_topfield || pcext.picture_structure == picture_structure_botfield) number_of_frame_centre_offsets = 1; else { if (pcext.repeat_first_field == 1) number_of_frame_centre_offsets = 3; else number_of_frame_centre_offsets = 2; } } m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_display_extension_id, 4); for (int i = 0; i < number_of_frame_centre_offsets; i++) { m_bs->write_bits(pdext.frame_centre_horizontal_offset[i], 16); m_bs->one_bit(); m_bs->write_bits(pdext.frame_centre_vertical_offset[i], 16); m_bs->one_bit(); } return true; } bool write_picture_temporal_scalable_extension(bitstream_writer_c* m_bs, picture_temporal_scalable_extension_t& ptsext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_temporal_scalable_extension_id, 4); m_bs->write_bits(ptsext.reference_select_code, 2); m_bs->write_bits(ptsext.forward_temporal_reference, 10); m_bs->one_bit(); m_bs->write_bits(ptsext.backward_temporal_reference, 10); return true; } bool write_picture_spatial_scalable_extension(bitstream_writer_c* m_bs, picture_spatial_scalable_extension_t& pssext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(picture_spatial_scalable_extension_id, 4); m_bs->write_bits(pssext.lower_layer_temporal_reference, 10); m_bs->one_bit(); m_bs->write_bits(pssext.lower_layer_horizontal_offset, 15); m_bs->one_bit(); m_bs->write_bits(pssext.lower_layer_vertical_offset, 15); m_bs->write_bits(pssext.spatial_temporal_weight_code_table_index, 2); m_bs->write_bits(pssext.lower_layer_progressive_frame, 1); m_bs->write_bits(pssext.lower_layer_deinterlaced_field_select, 1); return true; } bool write_copyright_extension(bitstream_writer_c* m_bs, copyright_extension_t& crext) { m_bs->align(); m_bs->write_bits(START_CODE(extension_start_code), 32); m_bs->write_bits(copiright_extension_id, 4); m_bs->write_bits(crext.copyright_flag, 1); m_bs->write_bits(crext.copyright_identifier, 8); m_bs->write_bits(crext.original_or_copy, 1); m_bs->write_bits(crext.reserved, 7); m_bs->one_bit(); m_bs->write_bits(crext.copyright_number_1, 20); m_bs->one_bit(); m_bs->write_bits(crext.copyright_number_2, 22); m_bs->one_bit(); m_bs->write_bits(crext.copyright_number_3, 22); return true; }
43.253165
163
0.727441
fxslava
edcb4239510c0b7f3e41f6388f3a86013aa56364
2,969
cpp
C++
roomedit/owl-6.43/source/owlcore/timegadg.cpp
marcelkauf/Meridian59-101
a83e2779e39bc529dc61dc02db091db7db29734c
[ "FSFAP" ]
214
2015-01-02T23:36:42.000Z
2022-03-30T01:41:41.000Z
roomedit/owl-6.43/source/owlcore/timegadg.cpp
marcelkauf/Meridian59-101
a83e2779e39bc529dc61dc02db091db7db29734c
[ "FSFAP" ]
100
2015-01-01T13:51:57.000Z
2022-03-28T15:49:36.000Z
roomedit/owl-6.43/source/owlcore/timegadg.cpp
marcelkauf/Meridian59-101
a83e2779e39bc529dc61dc02db091db7db29734c
[ "FSFAP" ]
85
2015-01-08T16:09:04.000Z
2022-02-22T05:24:56.000Z
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1995, 1996 by Borland International, All Rights Reserved // //---------------------------------------------------------------------------- #include <owl/pch.h> #if !defined(OWL_TIMEGADG_H) # include <owl/timegadg.h> #endif #include <owl/time.h> #include <owl/pointer.h> namespace owl { OWL_DIAGINFO; // /// Constructor for TTimeGadget. // TTimeGadget::TTimeGadget(TGetTimeFunc timeFunc, int id, TBorderStyle border, TAlign align, uint numChars, LPCTSTR text, TFont* font) : TTextGadget(id, border, align, numChars, text, font), TimeFunc(timeFunc) { SetShrinkWrap(false, true); } // /// String-aware overload // TTimeGadget::TTimeGadget( TGetTimeFunc timeFunc, int id, TBorderStyle border, TAlign align, uint numChars, const tstring& text, TFont* font ) : TTextGadget(id, border, align, numChars, text, font), TimeFunc(timeFunc) { SetShrinkWrap(false, true); } // /// Overriden from TGadget to inform gadget window to setup a timer // void TTimeGadget::Created() { TGadget::Created(); GetGadgetWindow()->EnableTimer(); } // /// Overridden from TGadget to display the current time. // bool TTimeGadget::IdleAction(long count) { TGadget::IdleAction(count); tstring newTime; TimeFunc(newTime); SetText(newTime.c_str()); // NOTE: Don't return true to drain system. Let GadgetWindow Timer // message indirectly trigger IdleAction. // return false; } // /// Retrieves the current time. // void TTimeGadget::GetTTime(tstring& newTime) { TTime time; newTime = time.AsString(); } // // Win32 specific // // /// Retrieves the system time using the Win32 API. // void TTimeGadget::GetSystemTime(tstring& newTime) { TAPointer<tchar> dateBuffer(new tchar[100]); TAPointer<tchar> timeBuffer(new tchar[100]); LCID lcid = ::GetUserDefaultLCID(); SYSTEMTIME systemTime; ::GetSystemTime(&systemTime); if (::GetTimeFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, timeBuffer, 100)) { if (::GetDateFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, dateBuffer, 100)) { newTime += dateBuffer; newTime += _T(" "); newTime += timeBuffer; } } } // /// Retrieves the local time using the Win32 API // void TTimeGadget::GetLocalTime(tstring& newTime) { TAPointer<tchar> dateBuffer(new tchar[100]); TAPointer<tchar> timeBuffer(new tchar[100]); LCID lcid = ::GetUserDefaultLCID(); SYSTEMTIME systemTime; ::GetLocalTime(&systemTime); if (::GetTimeFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, timeBuffer, 100)) { if (::GetDateFormat(lcid, LOCALE_NOUSEROVERRIDE, &systemTime, 0, dateBuffer, 100)) { newTime += dateBuffer; newTime += _T(" "); newTime += timeBuffer; } } } } // OWL namespace /* ========================================================================== */
21.671533
88
0.6258
marcelkauf
edcd90b9ca77108547b2914295385a5947d5bdf0
19,610
cpp
C++
unix/disp_sdl.cpp
acekiller/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
1
2015-06-21T05:27:57.000Z
2015-06-21T05:27:57.000Z
unix/disp_sdl.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
unix/disp_sdl.cpp
binji/povray
ae6837fb8625bb9ca00830f8871c90c87dd21b75
[ "Zlib" ]
null
null
null
/******************************************************************************* * disp_sdl.cpp * * Written by Christoph Hormann <[email protected]> * * SDL (Simple direct media layer) based render display system * * from Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. * Copyright 2003-2009 Persistence of Vision Raytracer Pty. Ltd. * --------------------------------------------------------------------------- * NOTICE: This source code file is provided so that users may experiment * with enhancements to POV-Ray and to port the software to platforms other * than those supported by the POV-Ray developers. There are strict rules * regarding how you are permitted to use this file. These rules are contained * in the distribution and derivative versions licenses which should have been * provided with this file. * * These licences may be found online, linked from the end-user license * agreement that is located at http://www.povray.org/povlegal.html * --------------------------------------------------------------------------- * POV-Ray is based on the popular DKB raytracer version 2.12. * DKBTrace was originally written by David K. Buck. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. * --------------------------------------------------------------------------- * $File: //depot/povray/smp/unix/disp_sdl.cpp $ * $Revision: #19 $ * $Change: 5604 $ * $DateTime: 2012/01/28 15:37:41 $ * $Author: jgrimbert $ *******************************************************************************/ /********************************************************************************* * NOTICE * * This file is part of a BETA-TEST version of POV-Ray version 3.7. It is not * final code. Use of this source file is governed by both the standard POV-Ray * licences referred to in the copyright header block above this notice, and the * following additional restrictions numbered 1 through 4 below: * * 1. This source file may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. * * 2. This notice may not be altered or removed. * * 3. Binaries generated from this source file by individuals for their own * personal use may not be re-distributed without the written permission * of Persistence of Vision Raytracer Pty. Ltd. Such personal-use binaries * are not required to have a timeout, and thus permission is granted in * these circumstances only to disable the timeout code contained within * the beta software. * * 4. Binaries generated from this source file for use within an organizational * unit (such as, but not limited to, a company or university) may not be * distributed beyond the local organizational unit in which they were made, * unless written permission is obtained from Persistence of Vision Raytracer * Pty. Ltd. Additionally, the timeout code implemented within the beta may * not be disabled or otherwise bypassed in any manner. * * The following text is not part of the above conditions and is provided for * informational purposes only. * * The purpose of the no-redistribution clause is to attempt to keep the * circulating copies of the beta source fresh. The only authorized distribution * point for the source code is the POV-Ray website and Perforce server, where * the code will be kept up to date with recent fixes. Additionally the beta * timeout code mentioned above has been a standard part of POV-Ray betas since * version 1.0, and is intended to reduce bug reports from old betas as well as * keep any circulating beta binaries relatively fresh. * * All said, however, the POV-Ray developers are open to any reasonable request * for variations to the above conditions and will consider them on a case-by-case * basis. * * Additionally, the developers request your co-operation in fixing bugs and * generally improving the program. If submitting a bug-fix, please ensure that * you quote the revision number of the file shown above in the copyright header * (see the '$Revision:' field). This ensures that it is possible to determine * what specific copy of the file you are working with. The developers also would * like to make it known that until POV-Ray 3.7 is out of beta, they would prefer * to emphasize the provision of bug fixes over the addition of new features. * * Persons wishing to enhance this source are requested to take the above into * account. It is also strongly suggested that such enhancements are started with * a recent copy of the source. * * The source code page (see http://www.povray.org/beta/source/) sets out the * conditions under which the developers are willing to accept contributions back * into the primary source tree. Please refer to those conditions prior to making * any changes to this source, if you wish to submit those changes for inclusion * with POV-Ray. * *********************************************************************************/ #include "config.h" #ifdef HAVE_LIBSDL #include "disp_sdl.h" #include <algorithm> // this must be the last file included #include "syspovdebug.h" namespace pov_frontend { using namespace std; using namespace vfe; using namespace vfePlatform; extern boost::shared_ptr<Display> gDisplay; const UnixOptionsProcessor::Option_Info UnixSDLDisplay::Options[] = { // command line/povray.conf/environment options of this display mode can be added here // section name, option name, default, has_param, command line parameter, environment variable name, help text UnixOptionsProcessor::Option_Info("display", "scaled", "on", false, "", "POV_DISPLAY_SCALED", "scale render view to fit screen"), UnixOptionsProcessor::Option_Info("", "", "", false, "", "", "") // has to be last }; bool UnixSDLDisplay::Register(vfeUnixSession *session) { session->GetUnixOptions()->Register(Options); // TODO: correct display detection return true; } UnixSDLDisplay::UnixSDLDisplay(unsigned int w, unsigned int h, GammaCurvePtr gamma, vfeSession *session, bool visible) : UnixDisplay(w, h, gamma, session, visible) { m_valid = false; m_display_scaled = false; m_display_scale = 1.; m_screen = NULL; m_display = NULL; } UnixSDLDisplay::~UnixSDLDisplay() { Close(); } void UnixSDLDisplay::Initialise() { if (m_VisibleOnCreation) Show(); } void UnixSDLDisplay::Hide() { } bool UnixSDLDisplay::TakeOver(UnixDisplay *display) { UnixSDLDisplay *p = dynamic_cast<UnixSDLDisplay *>(display); if (p == NULL) return false; if ((GetWidth() != p->GetWidth()) || (GetHeight() != p->GetHeight())) return false; m_valid = p->m_valid; m_display_scaled = p->m_display_scaled; m_display_scale = p->m_display_scale; m_screen = p->m_screen; m_display = p->m_display; if (m_display_scaled) { int width = GetWidth(); int height = GetHeight(); // allocate a new pixel counters, dropping influence of previous picture m_PxCount.clear(); // not useful, vector was created empty, just to be sure m_PxCount.reserve(width*height); // we need that, and the loop! for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++) (*iter) = 0; } return true; } void UnixSDLDisplay::Close() { if (!m_valid) return; // FIXME: should handle this correctly for the last frame // SDL_FreeSurface(m_display); // SDL_Quit(); m_PxCount.clear(); m_valid = false; } void UnixSDLDisplay::SetCaption(bool paused) { if (!m_valid) return; boost::format f; if (m_display_scaled) f = boost::format(PACKAGE_NAME " " VERSION_BASE " SDL display (scaled at %.0f%%)%s") % (m_display_scale*100) % (paused ? " [paused]" : ""); else f = boost::format(PACKAGE_NAME " " VERSION_BASE " SDL display%s") % (paused ? " [paused]" : ""); // FIXME: SDL_WM_SetCaption() causes locks on some distros, see http://bugs.povray.org/23 // FIXME: SDL_WM_SetCaption(f.str().c_str(), PACKAGE_NAME); } void UnixSDLDisplay::Show() { if (gDisplay.get() != this) gDisplay = m_Session->GetDisplay(); if (!m_valid) { // Initialize SDL if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s.\n", SDL_GetError()); return; } int desired_bpp = 0; Uint32 video_flags = 0; int width = GetWidth(); int height = GetHeight(); vfeUnixSession *UxSession = dynamic_cast<vfeUnixSession *>(m_Session); if (UxSession->GetUnixOptions()->isOptionSet("display", "scaled")) // determine maximum display area (wrong and ugly) { SDL_Rect **modes = SDL_ListModes(NULL, SDL_FULLSCREEN); if (modes != NULL) { width = min(modes[0]->w - 10, width); height = min(modes[0]->h - 80, height); } } // calculate display area float AspectRatio = float(width)/float(height); float AspectRatio_Full = float(GetWidth())/float(GetHeight()); if (AspectRatio > AspectRatio_Full) width = int(AspectRatio_Full*float(height)); else if (AspectRatio != AspectRatio_Full) height = int(float(width)/AspectRatio_Full); // Initialize the display m_screen = SDL_SetVideoMode(width, height, desired_bpp, video_flags); if ( m_screen == NULL ) { fprintf(stderr, "Couldn't set %dx%dx%d video mode: %s\n", width, height, desired_bpp, SDL_GetError()); return; } SDL_Surface *temp = SDL_CreateRGBSurface(SDL_SWSURFACE, width, height, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF); if ( temp == NULL ) { fprintf(stderr, "Couldn't create render display surface: %s\n", SDL_GetError()); return; } m_display = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); if ( m_display == NULL ) { fprintf(stderr, "Couldn't convert bar surface: %s\n", SDL_GetError()); return; } m_PxCount.clear(); m_PxCount.reserve(width*height); for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++) (*iter) = 0; m_update_rect.x = 0; m_update_rect.y = 0; m_update_rect.w = width; m_update_rect.h = height; m_screen_rect.x = 0; m_screen_rect.y = 0; m_screen_rect.w = width; m_screen_rect.h = height; m_valid = true; m_PxCnt = UpdateInterval; if ((width == GetWidth()) && (height == GetHeight())) { m_display_scaled = false; m_display_scale = 1.; } else { m_display_scaled = true; m_display_scale = float(width) / GetWidth(); } SetCaption(false); } } inline void UnixSDLDisplay::SetPixel(unsigned int x, unsigned int y, const RGBA8& colour) { Uint8 *p = (Uint8 *) m_display->pixels + y * m_display->pitch + x * m_display->format->BytesPerPixel; Uint32 sdl_col = SDL_MapRGBA(m_display->format, colour.red, colour.green, colour.blue, colour.alpha); switch (m_display->format->BytesPerPixel) { case 1: *p = sdl_col; break; case 2: *(Uint16 *) p = sdl_col; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (sdl_col >> 16) & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = sdl_col & 0xFF; } else { p[0] = sdl_col & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = (sdl_col >> 16) & 0xFF; } break; case 4: *(Uint32 *) p = sdl_col; break; } } inline void UnixSDLDisplay::SetPixelScaled(unsigned int x, unsigned int y, const RGBA8& colour) { unsigned int ix = x * m_display_scale; unsigned int iy = y * m_display_scale; Uint8 *p = (Uint8 *) m_display->pixels + iy * m_display->pitch + ix * m_display->format->BytesPerPixel; Uint8 r, g, b, a; Uint32 old = *(Uint32 *) p; SDL_GetRGBA(old, m_display->format, &r, &g, &b, &a); unsigned int ofs = ix + iy * m_display->w; r = (r*m_PxCount[ofs] + colour.red ) / (m_PxCount[ofs]+1); g = (g*m_PxCount[ofs] + colour.green) / (m_PxCount[ofs]+1); b = (b*m_PxCount[ofs] + colour.blue ) / (m_PxCount[ofs]+1); a = (a*m_PxCount[ofs] + colour.alpha) / (m_PxCount[ofs]+1); Uint32 sdl_col = SDL_MapRGBA(m_display->format, r, g, b, a); switch (m_display->format->BytesPerPixel) { case 1: *p = sdl_col; break; case 2: *(Uint16 *) p = sdl_col; break; case 3: if (SDL_BYTEORDER == SDL_BIG_ENDIAN) { p[0] = (sdl_col >> 16) & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = sdl_col & 0xFF; } else { p[0] = sdl_col & 0xFF; p[1] = (sdl_col >> 8) & 0xFF; p[2] = (sdl_col >> 16) & 0xFF; } break; case 4: *(Uint32 *) p = sdl_col; break; } ++m_PxCount[ofs]; } void UnixSDLDisplay::UpdateCoord(unsigned int x, unsigned int y) { unsigned int rx2 = m_update_rect.x + m_update_rect.w; unsigned int ry2 = m_update_rect.y + m_update_rect.h; m_update_rect.x = min((unsigned int)m_update_rect.x, x); m_update_rect.y = min((unsigned int)m_update_rect.y, y); rx2 = max(rx2, x); ry2 = max(ry2, y); m_update_rect.w = rx2 - m_update_rect.x; m_update_rect.h = ry2 - m_update_rect.y; } void UnixSDLDisplay::UpdateCoord(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2) { unsigned int rx2 = m_update_rect.x + m_update_rect.w; unsigned int ry2 = m_update_rect.y + m_update_rect.h; m_update_rect.x = min((unsigned int)m_update_rect.x, x1); m_update_rect.y = min((unsigned int)m_update_rect.y, y1); rx2 = max(rx2, x2); ry2 = max(ry2, y2); m_update_rect.w = rx2 - m_update_rect.x; m_update_rect.h = ry2 - m_update_rect.y; } void UnixSDLDisplay::UpdateCoordScaled(unsigned int x, unsigned int y) { UpdateCoord(static_cast<unsigned int>(x * m_display_scale), static_cast<unsigned int>(y * m_display_scale)); } void UnixSDLDisplay::UpdateCoordScaled(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2) { UpdateCoord(static_cast<unsigned int>(x1 * m_display_scale), static_cast<unsigned int>(y1 * m_display_scale), static_cast<unsigned int>(x2 * m_display_scale), static_cast<unsigned int>(y2 * m_display_scale)); } void UnixSDLDisplay::DrawPixel(unsigned int x, unsigned int y, const RGBA8& colour) { if (!m_valid || x >= GetWidth() || y >= GetHeight()) return; if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0) return; if (m_display_scaled) { SetPixelScaled(x, y, colour); UpdateCoordScaled(x, y); } else { SetPixel(x, y, colour); UpdateCoord(x, y); } m_PxCnt++; if (SDL_MUSTLOCK(m_display)) SDL_UnlockSurface(m_display); } void UnixSDLDisplay::DrawRectangleFrame(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8& colour) { if (!m_valid) return; int ix1 = min(x1, GetWidth()-1); int ix2 = min(x2, GetWidth()-1); int iy1 = min(y1, GetHeight()-1); int iy2 = min(y2, GetHeight()-1); if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0) return; if (m_display_scaled) { for(unsigned int x = ix1; x <= ix2; x++) { SetPixelScaled(x, iy1, colour); SetPixelScaled(x, iy2, colour); } for(unsigned int y = iy1; y <= iy2; y++) { SetPixelScaled(ix1, y, colour); SetPixelScaled(ix2, y, colour); } UpdateCoordScaled(ix1, iy1, ix2, iy2); } else { for(unsigned int x = ix1; x <= ix2; x++) { SetPixel(x, iy1, colour); SetPixel(x, iy2, colour); } for(unsigned int y = iy1; y <= iy2; y++) { SetPixel(ix1, y, colour); SetPixel(ix2, y, colour); } UpdateCoord(ix1, iy1, ix2, iy2); } if (SDL_MUSTLOCK(m_display)) SDL_UnlockSurface(m_display); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::DrawFilledRectangle(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8& colour) { if (!m_valid) return; unsigned int ix1 = min(x1, GetWidth()-1); unsigned int ix2 = min(x2, GetWidth()-1); unsigned int iy1 = min(y1, GetHeight()-1); unsigned int iy2 = min(y2, GetHeight()-1); if (m_display_scaled) { ix1 *= m_display_scale; iy1 *= m_display_scale; ix2 *= m_display_scale; iy2 *= m_display_scale; } UpdateCoord(ix1, iy1, ix2, iy2); Uint32 sdl_col = SDL_MapRGBA(m_display->format, colour.red, colour.green, colour.blue, colour.alpha); SDL_Rect tempRect; tempRect.x = ix1; tempRect.y = iy1; tempRect.w = ix2 - ix1 + 1; tempRect.h = iy2 - iy1 + 1; SDL_FillRect(m_display, &tempRect, sdl_col); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::DrawPixelBlock(unsigned int x1, unsigned int y1, unsigned int x2, unsigned int y2, const RGBA8 *colour) { if (!m_valid) return; unsigned int ix1 = min(x1, GetWidth()-1); unsigned int ix2 = min(x2, GetWidth()-1); unsigned int iy1 = min(y1, GetHeight()-1); unsigned int iy2 = min(y2, GetHeight()-1); if (SDL_MUSTLOCK(m_display) && SDL_LockSurface(m_display) < 0) return; if (m_display_scaled) { for(unsigned int y = iy1, i = 0; y <= iy2; y++) for(unsigned int x = ix1; x <= ix2; x++, i++) SetPixelScaled(x, y, colour[i]); UpdateCoordScaled(ix1, iy1, ix2, iy2); } else { for(unsigned int y = y1, i = 0; y <= iy2; y++) for(unsigned int x = ix1; x <= ix2; x++, i++) SetPixel(x, y, colour[i]); UpdateCoord(ix1, iy1, ix2, iy2); } if (SDL_MUSTLOCK(m_display)) SDL_UnlockSurface(m_display); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::Clear() { for(vector<unsigned char>::iterator iter = m_PxCount.begin(); iter != m_PxCount.end(); iter++) (*iter) = 0; m_update_rect.x = 0; m_update_rect.y = 0; m_update_rect.w = m_display->w; m_update_rect.h = m_display->h; SDL_FillRect(m_display, &m_update_rect, (Uint32)0); m_PxCnt = UpdateInterval; } void UnixSDLDisplay::UpdateScreen(bool Force = false) { if (!m_valid) return; if (Force || m_PxCnt >= UpdateInterval) { SDL_BlitSurface(m_display, &m_update_rect, m_screen, &m_update_rect); SDL_UpdateRect(m_screen, m_update_rect.x, m_update_rect.y, m_update_rect.w, m_update_rect.h); m_PxCnt = 0; } } void UnixSDLDisplay::PauseWhenDoneNotifyStart() { if (!m_valid) return; fprintf(stderr, "Press a key or click the display to continue..."); SetCaption(true); } void UnixSDLDisplay::PauseWhenDoneNotifyEnd() { if (!m_valid) return; SetCaption(false); fprintf(stderr, "\n\n"); } bool UnixSDLDisplay::PauseWhenDoneResumeIsRequested() { if (!m_valid) return true; SDL_Event event; bool do_quit = false; if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if ( event.key.keysym.sym == SDLK_q || event.key.keysym.sym == SDLK_RETURN || event.key.keysym.sym == SDLK_KP_ENTER ) do_quit = true; break; case SDL_MOUSEBUTTONDOWN: do_quit = true; break; } } return do_quit; } bool UnixSDLDisplay::HandleEvents() { if (!m_valid) return false; SDL_Event event; bool do_quit = false; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: if ( event.key.keysym.sym == SDLK_q ) do_quit = true; else if ( event.key.keysym.sym == SDLK_p ) { if (!m_Session->IsPausable()) break; if (m_Session->Paused()) { if (m_Session->Resume()) SetCaption(false); } else { if (m_Session->Pause()) SetCaption(true); } } break; case SDL_QUIT: do_quit = true; break; } if (do_quit) break; } return do_quit; } } #endif /* HAVE_LIBSDL */
28.753666
131
0.647119
acekiller
edcdb5fc493944a65db3ff558874a10ebd9fcb87
2,630
cpp
C++
src/caffe/layers/tile_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
123
2017-05-04T02:15:47.000Z
2021-01-04T05:04:24.000Z
src/caffe/layers/tile_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
43
2017-05-10T11:21:25.000Z
2021-01-28T14:53:01.000Z
src/caffe/layers/tile_layer_hip.cpp
emerth/hipCaffe
8996c92bed2fbe353d1f31ab3ad116ab8831cd94
[ "BSD-2-Clause" ]
32
2017-05-10T11:08:18.000Z
2020-12-17T20:03:45.000Z
#include <vector> #include "caffe/layers/tile_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> __global__ void Tile(const int nthreads, const Dtype* bottom_data, const int tile_size, const int num_tiles, const int bottom_tile_axis, Dtype* top_data) { HIP_KERNEL_LOOP(index, nthreads) { const int d = index % tile_size; const int b = (index / tile_size / num_tiles) % bottom_tile_axis; const int n = index / tile_size / num_tiles / bottom_tile_axis; const int bottom_index = (n * bottom_tile_axis + b) * tile_size + d; top_data[index] = bottom_data[bottom_index]; } } template <typename Dtype> void TileLayer<Dtype>::Forward_gpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); const int bottom_tile_axis = bottom[0]->shape(axis_); const int nthreads = top[0]->count(); hipLaunchKernelGGL(Tile<Dtype>, //) NOLINT_NEXT_LINE(whitespace/operators) dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0, nthreads, bottom_data, inner_dim_, tiles_, bottom_tile_axis, top_data); } template <typename Dtype> __global__ void TileBackward(const int nthreads, const Dtype* top_diff, const int tile_size, const int num_tiles, const int bottom_tile_axis, Dtype* bottom_diff) { HIP_KERNEL_LOOP(index, nthreads) { const int d = index % tile_size; const int b = (index / tile_size) % bottom_tile_axis; const int n = index / tile_size / bottom_tile_axis; bottom_diff[index] = 0; int top_index = (n * num_tiles * bottom_tile_axis + b) * tile_size + d; for (int t = 0; t < num_tiles; ++t) { bottom_diff[index] += top_diff[top_index]; top_index += bottom_tile_axis * tile_size; } } } template <typename Dtype> void TileLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } const Dtype* top_diff = top[0]->gpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); const int bottom_tile_axis = bottom[0]->shape(axis_); const int tile_size = inner_dim_ / bottom_tile_axis; const int nthreads = bottom[0]->count(); hipLaunchKernelGGL(TileBackward<Dtype>, // NOLINT_NEXT_LINE(whitespace/operators) dim3(CAFFE_GET_BLOCKS(nthreads)), dim3(CAFFE_HIP_NUM_THREADS), 0, 0, nthreads, top_diff, tile_size, tiles_, bottom_tile_axis, bottom_diff); } INSTANTIATE_LAYER_GPU_FUNCS(TileLayer); } // namespace caffe
39.253731
84
0.715209
emerth
edd24c2c54966acc08d2d649d9dee402dfb77ae1
15,269
cpp
C++
src/compile.cpp
fstromback/mymake
1ccb9adbc5a336e29ca222f11e9368cdd026ee1b
[ "MIT" ]
3
2017-05-30T11:29:06.000Z
2021-09-04T15:32:23.000Z
src/compile.cpp
fstromback/mymake
1ccb9adbc5a336e29ca222f11e9368cdd026ee1b
[ "MIT" ]
5
2016-01-22T20:06:19.000Z
2019-02-03T18:30:58.000Z
src/compile.cpp
fstromback/mymake
1ccb9adbc5a336e29ca222f11e9368cdd026ee1b
[ "MIT" ]
null
null
null
#include "std.h" #include "compile.h" #include "wildcard.h" #include "process.h" #include "env.h" namespace compile { Target::Target(const Path &wd, const Config &config) : wd(wd), config(config), includes(wd, config), compileVariants(config.getArray("compile")), buildDir(wd + Path(config.getVars("buildDir"))), intermediateExt(config.getVars("intermediateExt")), pchHeader(config.getVars("pch")), pchFile(buildDir + Path(config.getVars("pchFile"))), combinedPch(config.getBool("pchCompileCombined")), appendExt(config.getBool("appendExt", false)), absolutePath(config.getBool("absolutePath", false)) { buildDir.makeDir(); linkOutput = config.getBool("linkOutput", false); forwardDeps = config.getBool("forwardDeps", false); if (absolutePath) { vector<String> inc = this->config.getArray("include"); this->config.clear("include"); for (nat i = 0; i < inc.size(); i++) { this->config.add("include", toS(Path(inc[i]).makeAbsolute(wd))); } } // Add file extensions. We don't bother with uniqueness here, and let the ExtCache deal with that. validExts = config.getArray("ext"); vector<String> ign = config.getArray("ignore"); for (nat i = 0; i < ign.size(); i++) ignore << Wildcard(ign[i]); // Create build directory if it is not already created. buildDir.createDir(); // Load cached data if possible. includes.ignore(config.getArray("noIncludes")); if (!force) { includes.load(buildDir + "includes"); commands.load(buildDir + "commands"); } } Target::~Target() { // We do this in "save", since if we execute the binary, the destructor will not be executed. // includes.save(buildDir + "includes"); } void Target::clean() { DEBUG("Cleaning " << buildDir.makeRelative(wd) << "...", NORMAL); buildDir.recursiveDelete(); Path e = wd + Path(config.getVars("execDir")); e.makeDir(); DEBUG("Cleaning " << e.makeRelative(wd) << "...", NORMAL); e.recursiveDelete(); } bool Target::find() { DEBUG("Finding dependencies for target in " << wd, INFO); toCompile.clear(); ExtCache cache(validExts); CompileQueue q; String outputName = config.getVars("output"); // Compile pre-compiled header first. String pchStr = config.getVars("pch"); if (!pchStr.empty()) { if (!addFile(q, cache, pchStr, true)) { PLN("Failed to find an implementation file for the precompiled header."); PLN("Make sure to create both a header file '" << pchStr << "' and a corresponding implementation file."); return false; } } // Add initial files. addFiles(q, cache, config.getArray("input")); // Process files... while (q.any()) { Compile now = q.pop(); if (ignored(toS(now.makeRelative(wd)))) continue; if (!now.isPch && !now.autoFound && outputName.empty()) outputName = now.title(); // Check if 'now' is inside the working directory. if (!now.isChild(wd)) { // No need to follow further! DEBUG("Ignoring file outside of working directory: " << now.makeRelative(wd), VERBOSE); continue; } toCompile << now; // Add all other files we need. IncludeInfo info = includes.info(now); // Check so that any pch file is included first. if (!info.ignored && !pchStr.empty() && pchStr != info.firstInclude) { PLN(now << ":1: Precompiled header " << pchStr << " not used."); PLN("The precompiled header " << pchStr << " must be included first in each implementation file."); PLN("You need to use '#include \"" << pchStr << "\"' (exactly like that), and use 'include=./'."); return false; } for (IncludeInfo::PathSet::const_iterator i = info.includes.begin(); i != info.includes.end(); ++i) { DEBUG(now << " depends on " << *i, VERBOSE); addFile(q, cache, *i); // Is this a reference to another sub-project? if (!i->isChild(wd)) { Path parentRel = i->makeRelative(wd.parent()); if (parentRel.first() != "..") { dependsOn << parentRel.first(); } } } } if (toCompile.empty()) { PLN("No input files."); return false; } // Try to add the files which should be created by the pre-build step (if any). addPreBuildFiles(q, config.getArray("preBuildCreates")); while (q.any()) { Compile now = q.pop(); DEBUG("Adding file created by pre-build step currently not existing: " << now.makeRelative(wd), INFO); toCompile << now; } if (outputName.empty()) outputName = wd.title(); Path execDir = wd + Path(config.getVars("execDir")); execDir.createDir(); output = execDir + Path(outputName).titleNoExt(); output.makeExt(config.getStr("execExt")); return true; } // Save command line on exit. class SaveOnExit : public ProcessCallback { public: SaveOnExit(Commands *to, const String &file, const String &command) : to(to), key(file), command(command) {} // Save to. Commands *to; // Source file used as key. String key; // Command line. String command; virtual void exited(int result) { if (result == 0) to->set(key, command); } }; Process *Target::saveShellProcess(const String &file, const String &command, const Path &cwd, const Env *env) { Process *p = shellProcess(command, cwd, env); p->callback = new SaveOnExit(&commands, file, command); return p; } bool Target::compile() { nat threads = to<nat>(config.getStr("maxThreads", "1")); // Force serial execution? if (!config.getBool("parallel", true)) threads = 1; DEBUG("Using max " << threads << " threads.", VERBOSE); ProcGroup group(threads, outputState); DEBUG("Compiling target in " << wd, INFO); Env env(config); // Run pre-compile steps. { map<String, String> stepData; stepData["output"] = toS(output.makeRelative(wd)); if (!runSteps("preBuild", group, env, stepData)) return false; } map<String, String> data; data["file"] = ""; data["output"] = ""; data["pchFile"] = toS(pchFile.makeRelative(wd)); TimeCache timeCache; Timestamp latestModified(0); ostringstream intermediateFiles; for (nat i = 0; i < toCompile.size(); i++) { const Compile &src = toCompile[i]; Path output = src.makeRelative(wd).makeAbsolute(buildDir); if (appendExt) { String t = output.titleNoExt() + "_" + output.ext() + "." + intermediateExt; output.makeTitle(t); } else { output.makeExt(intermediateExt); } output.parent().createDir(); String file = toS(src.makeRelative(wd)); String out = toS(output.makeRelative(wd)); if (i > 0) intermediateFiles << ' '; intermediateFiles << out; if (ignored(file)) continue; Timestamp lastModified = includes.info(src).lastModified(timeCache); bool pchValid = true; if (src.isPch) { // Note: This implies that pchFile exists as well. pchValid = pchFile.mTime() >= lastModified; } bool skip = !force // Never skip a file if the force flag is set. && pchValid // If the pch is invalid, don't skip. && output.mTime() >= lastModified; // If the output exists and is new enough, we can skip. if (!combinedPch && src.isPch) { String cmd = config.getStr("pchCompile"); Path pchPath = Path(pchHeader).makeAbsolute(wd); String pchFile = toS(pchPath.makeRelative(wd)); data["file"] = preparePath(pchPath); data["output"] = data["pchFile"]; cmd = config.expandVars(cmd, data); if (skip && commands.check(pchFile, cmd)) { DEBUG("Skipping header " << file << "...", INFO); } else { DEBUG("Compiling header " << file << "...", NORMAL); DEBUG("Command line: " << cmd, INFO); if (!group.spawn(saveShellProcess(pchFile, cmd, wd, &env))) { return false; } // Wait for it to complete... if (!group.wait()) { return false; } } } String cmd; if (combinedPch && src.isPch) cmd = config.getStr("pchCompile"); else cmd = chooseCompile(file); if (cmd == "") { PLN("No suitable compile command-line for " << file); return false; } data["file"] = preparePath(src); data["output"] = out; cmd = config.expandVars(cmd, data); if (skip && commands.check(file, cmd)) { DEBUG("Skipping " << file << "...", INFO); DEBUG("Source modified: " << lastModified << ", output modified " << output.mTime(), DEBUG); } else { DEBUG("Compiling " << file << "...", NORMAL); DEBUG("Command line: " << cmd, INFO); if (!group.spawn(saveShellProcess(file, cmd, wd, &env))) return false; // If it is a pch, wait for it to finish. if (src.isPch) { if (!group.wait()) return false; } } // Update 'last modified'. We always want to do this, even if we did not need to compile the file. if (i == 0) latestModified = lastModified; else latestModified = max(latestModified, lastModified); } // Wait for compilation to terminate. if (!group.wait()) return false; vector<String> libs = config.getArray("localLibrary"); for (nat i = 0; i < libs.size(); i++) { Path libPath(libs[i]); if (libPath.exists()) { latestModified = max(latestModified, libPath.mTime()); } else { WARNING("Local library " << libPath << " not found. Use 'library' for system libraries."); } } // Link the output. bool skipLink = !force && output.mTime() >= latestModified; String finalOutput = toS(output.makeRelative(wd)); data["files"] = intermediateFiles.str(); data["output"] = finalOutput; vector<String> linkCmds = config.getArray("link"); std::ostringstream allCmds; for (nat i = 0; i < linkCmds.size(); i++) { linkCmds[i] = config.expandVars(linkCmds[i], data); if (i > 0) allCmds << ";"; allCmds << linkCmds[i]; } if (skipLink && commands.check(finalOutput, allCmds.str())) { DEBUG("Skipping linking.", INFO); DEBUG("Output modified " << output.mTime() << ", input modified " << latestModified, DEBUG); return true; } DEBUG("Linking " << output.title() << "...", NORMAL); for (nat i = 0; i < linkCmds.size(); i++) { const String &cmd = linkCmds[i]; DEBUG("Command line: " << cmd, INFO); if (!group.spawn(shellProcess(cmd, wd, &env))) return false; if (!group.wait()) return false; } commands.set(finalOutput, allCmds.str()); { // Run post-build steps. map<String, String> stepData; stepData["output"] = data["output"]; if (!runSteps("postBuild", group, env, stepData)) return false; } return true; } String Target::preparePath(const Path &file) { if (absolutePath) { return toS(file.makeAbsolute(wd)); } else { return toS(file.makeRelative(wd)); } } bool Target::ignored(const String &file) { for (nat j = 0; j < ignore.size(); j++) { if (ignore[j].matches(file)) { DEBUG("Ignoring " << file << " as per " << ignore[j], INFO); return true; } } return false; } bool Target::runSteps(const String &key, ProcGroup &group, const Env &env, const map<String, String> &options) { vector<String> steps = config.getArray(key); for (nat i = 0; i < steps.size(); i++) { String expanded = config.expandVars(steps[i], options); DEBUG("Running " << expanded, INFO); if (!group.spawn(shellProcess(expanded, wd, &env))) { PLN("Failed running " << key << ": " << expanded); return false; } if (!group.wait()) { PLN("Failed running " << key << ": " << expanded); return false; } } return true; } void Target::save() const { includes.save(buildDir + "includes"); commands.save(buildDir + "commands"); } int Target::execute(const vector<String> &params) const { if (!config.getBool("execute")) return 0; Path execPath = wd; if (config.has("execPath")) { execPath = Path(config.getStr("execPath")).makeAbsolute(wd); } DEBUG("Executing " << output.makeRelative(execPath) << " " << join(params) << " in " << execPath, INFO); return exec(output, params, execPath, null); } void Target::addLib(const Path &p) { config.add("localLibrary", toS(p)); } vector<Path> Target::findExt(const Path &path, ExtCache &cache) { // Earlier implementation did way too many queries for files, and has therefore been optimized. // for (nat i = 0; i < validExts.size(); i++) { // path.makeExt(validExts[i]); // if (path.exists()) // return true; // } const vector<String> &exts = cache.find(path); vector<Path> result; for (nat i = 0; i < exts.size(); i++) { result.push_back(path); result.back().makeExt(exts[i]); } if (!appendExt && result.size() > 1) { WARNING("Multiple files with the same name scheduled for compilation."); PLN("This leads to a name collision in the temporary files, leading to"); PLN("incorrect compilation, and probably also linker errors."); PLN("If you intend to compile all files below, add 'appendExt=yes' to this target."); PLN("Colliding files:\n" << join(result, "\n")); } return result; } void Target::addFiles(CompileQueue &to, ExtCache &cache, const vector<String> &src) { for (nat i = 0; i < src.size(); i++) { addFile(to, cache, src[i], false); } } void Target::addFilesRecursive(CompileQueue &to, const Path &at) { vector<Path> children = at.children(); for (nat i = 0; i < children.size(); i++) { if (children[i].isDir()) { DEBUG("Found directory " << children[i], DEBUG); addFilesRecursive(to, children[i]); } else { DEBUG("Found file " << children[i], DEBUG); if (std::find(validExts.begin(), validExts.end(), children[i].ext()) != validExts.end()) { DEBUG("Adding file " << children[i], VERBOSE); to << Compile(children[i], false, true); } } } } bool Target::addFile(CompileQueue &to, ExtCache &cache, const String &src, bool pch) { if (src.empty()) return false; if (src == "*") { addFilesRecursive(to, wd); return true; } Path path(src); path = path.makeAbsolute(wd); vector<Path> exts = findExt(path, cache); if (exts.empty()) { WARNING("The file " << src << " does not exist with any of the extensions " << join(validExts)); return false; } for (nat i = 0; i < exts.size(); i++) { to.push(Compile(exts[i], pch, false)); } return true; } void Target::addFile(CompileQueue &to, ExtCache &cache, const Path &header) { vector<Path> exts = findExt(header, cache); // No big deal if no cpp file is found for every h file. for (nat i = 0; i < exts.size(); i++) { to.push(Compile(exts[i], false, true)); } } void Target::addPreBuildFiles(CompileQueue &to, const vector<String> &src) { for (nat i = 0; i < src.size(); i++) addPreBuildFile(to, src[i]); } void Target::addPreBuildFile(CompileQueue &to, const String &src) { Path path = Path(src).makeAbsolute(wd); to.push(Compile(path, false, true)); } String Target::chooseCompile(const String &file) { for (nat i = compileVariants.size(); i > 0; i--) { const String &variant = compileVariants[i - 1]; nat colon = variant.find(':'); if (colon == String::npos) { WARNING("Compile variable without telling what filetypes it is for: " << variant); continue; } Wildcard w(variant.substr(0, colon)); if (w.matches(file)) return variant.substr(colon + 1); DEBUG("No match for " << file << " using " << variant, INFO); } return ""; } }
27.812386
113
0.62604
fstromback
edd5a33abc925ca38060f1594ba3d6cda727aa0c
11,056
cpp
C++
AVSCommon/Utils/test/Common/MockMediaPlayer.cpp
jbfitbit/avs-device-sdk
2e9428e9dfc9fa7c3b4bfd5106323f8c2f1643c9
[ "Apache-2.0" ]
1
2019-10-22T06:08:20.000Z
2019-10-22T06:08:20.000Z
AVSCommon/Utils/test/Common/MockMediaPlayer.cpp
yodaos-project/voice-interface-avs
d01136637f92df952be894bb1869d420889689ac
[ "Apache-2.0" ]
null
null
null
AVSCommon/Utils/test/Common/MockMediaPlayer.cpp
yodaos-project/voice-interface-avs
d01136637f92df952be894bb1869d420889689ac
[ "Apache-2.0" ]
1
2020-09-30T12:34:56.000Z
2020-09-30T12:34:56.000Z
/* * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "AVSCommon/Utils/MediaPlayer/MediaPlayerObserverInterface.h" #include "AVSCommon/Utils/MediaPlayer/MockMediaPlayer.h" namespace alexaClientSDK { namespace avsCommon { namespace utils { namespace mediaPlayer { namespace test { using namespace testing; const static std::chrono::milliseconds WAIT_LOOP_INTERVAL{1}; std::shared_ptr<NiceMock<MockMediaPlayer>> MockMediaPlayer::create() { auto result = std::make_shared<NiceMock<MockMediaPlayer>>(); ON_CALL(*result.get(), attachmentSetSource(_, _)) .WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource)); ON_CALL(*result.get(), urlSetSource(_)) .WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource)); ON_CALL(*result.get(), streamSetSource(_, _)) .WillByDefault(InvokeWithoutArgs(result.get(), &MockMediaPlayer::mockSetSource)); ON_CALL(*result.get(), play(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockPlay)); ON_CALL(*result.get(), stop(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockStop)); ON_CALL(*result.get(), pause(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockPause)); ON_CALL(*result.get(), resume(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockResume)); ON_CALL(*result.get(), getOffset(_)).WillByDefault(Invoke(result.get(), &MockMediaPlayer::mockGetOffset)); return result; } MockMediaPlayer::MockMediaPlayer() : RequiresShutdown{"MockMediaPlayer"}, m_playerObserver{nullptr} { // Create a 'source' for sourceId = 0 mockSetSource(); } MediaPlayerInterface::SourceId MockMediaPlayer::setSource( std::shared_ptr<avsCommon::avs::attachment::AttachmentReader> attachmentReader, const avsCommon::utils::AudioFormat* audioFormat) { return attachmentSetSource(attachmentReader, audioFormat); } MediaPlayerInterface::SourceId MockMediaPlayer::setSource( const std::string& url, std::chrono::milliseconds offset, bool repeat) { return urlSetSource(url); } MediaPlayerInterface::SourceId MockMediaPlayer::setSource(std::shared_ptr<std::istream> stream, bool repeat) { return streamSetSource(stream, repeat); } void MockMediaPlayer::setObserver(std::shared_ptr<MediaPlayerObserverInterface> playerObserver) { m_playerObserver = playerObserver; } std::shared_ptr<MediaPlayerObserverInterface> MockMediaPlayer::getObserver() const { return m_playerObserver; } void MockMediaPlayer::doShutdown() { std::lock_guard<std::mutex> lock(m_mutex); m_playerObserver.reset(); m_sources.clear(); } MediaPlayerInterface::SourceId MockMediaPlayer::mockSetSource() { std::lock_guard<std::mutex> lock(m_mutex); SourceId result = m_sources.size(); m_sources.emplace_back(std::make_shared<Source>(this, result)); return result; } bool MockMediaPlayer::mockPlay(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } EXPECT_TRUE(source->stopwatch.start()); source->started.trigger(); return true; } bool MockMediaPlayer::mockPause(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } // Ideally we would EXPECT_TRUE on pause(), however ACSDK-734 doesn't guarantee that will be okay. source->stopwatch.pause(); source->resumed.resetStateReached(); source->paused.trigger(); return true; } bool MockMediaPlayer::mockResume(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } EXPECT_TRUE(source->stopwatch.resume()); source->paused.resetStateReached(); source->resumed.trigger(); return true; } bool MockMediaPlayer::mockStop(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } source->stopwatch.stop(); source->stopped.trigger(); return true; } bool MockMediaPlayer::mockFinished(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } source->stopwatch.stop(); source->finished.trigger(); return true; } bool MockMediaPlayer::mockError(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return false; } source->stopwatch.stop(); source->error.trigger(); return true; } bool MockMediaPlayer::mockSetOffset(SourceId sourceId, std::chrono::milliseconds offset) { auto source = getCurrentSource(sourceId); if (!source) { return false; } std::lock_guard<std::mutex> lock(m_mutex); source->offset = offset; return true; } std::chrono::milliseconds MockMediaPlayer::mockGetOffset(SourceId sourceId) { auto source = getCurrentSource(sourceId); if (!source) { return MEDIA_PLAYER_INVALID_OFFSET; } return source->stopwatch.getElapsed() + source->offset; } bool MockMediaPlayer::waitUntilNextSetSource(const std::chrono::milliseconds timeout) { auto originalSourceId = getCurrentSourceId(); auto timeLimit = std::chrono::steady_clock::now() + timeout; while (std::chrono::steady_clock::now() < timeLimit) { if (getCurrentSourceId() != originalSourceId) { return true; } std::this_thread::sleep_for(WAIT_LOOP_INTERVAL); } return false; } bool MockMediaPlayer::waitUntilPlaybackStarted(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->started.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackPaused(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->paused.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackResumed(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->resumed.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackStopped(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->stopped.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackFinished(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->finished.wait(timeout); } bool MockMediaPlayer::waitUntilPlaybackError(std::chrono::milliseconds timeout) { return m_sources[getCurrentSourceId()]->error.wait(timeout); } MediaPlayerInterface::SourceId MockMediaPlayer::getCurrentSourceId() { std::unique_lock<std::mutex> lock(m_mutex); return m_sources.size() - 1; } MockMediaPlayer::SourceState::SourceState( Source* source, const std::string& name, std::function<void(std::shared_ptr<observer>, SourceId)> notifyFunction) : m_source{source}, m_name{name}, m_notifyFunction{notifyFunction}, m_stateReached{false}, m_shutdown{false} { } MockMediaPlayer::SourceState::~SourceState() { { std::lock_guard<std::mutex> lock(m_mutex); m_shutdown = true; } m_wake.notify_all(); if (m_thread.joinable()) { m_thread.join(); } } void MockMediaPlayer::SourceState::trigger() { std::lock_guard<std::mutex> lock(m_mutex); if (m_stateReached) { return; } m_thread = std::thread(&MockMediaPlayer::SourceState::notify, this, DEFAULT_TIME); m_stateReached = true; m_wake.notify_all(); } void MockMediaPlayer::SourceState::notify(const std::chrono::milliseconds timeout) { std::unique_lock<std::mutex> lock(m_mutex); auto observer = m_source->mockMediaPlayer->m_playerObserver; if (!m_wake.wait_for(lock, timeout, [this]() { return (m_stateReached || m_shutdown); })) { if (observer) { lock.unlock(); observer->onPlaybackError( m_source->sourceId, ErrorType::MEDIA_ERROR_UNKNOWN, m_name + ": wait to notify timed out"); } return; } if (observer) { m_notifyFunction(observer, m_source->sourceId); } return; } bool MockMediaPlayer::SourceState::wait(const std::chrono::milliseconds timeout) { std::unique_lock<std::mutex> lock(m_mutex); if (!m_wake.wait_for(lock, timeout, [this]() { return (m_stateReached || m_shutdown); })) { return false; } return m_stateReached; } void MockMediaPlayer::SourceState::resetStateReached() { if (m_thread.joinable()) { m_thread.join(); } std::unique_lock<std::mutex> lock(m_mutex); m_stateReached = false; } static void notifyPlaybackStarted( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackStarted(sourceId); } static void notifyPlaybackPaused( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackPaused(sourceId); } static void notifyPlaybackResumed( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackResumed(sourceId); } static void notifyPlaybackStopped( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackStopped(sourceId); } static void notifyPlaybackFinished( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackFinished(sourceId); } static void notifyPlaybackError( std::shared_ptr<MediaPlayerObserverInterface> observer, MediaPlayerInterface::SourceId sourceId) { observer->onPlaybackError(sourceId, ErrorType::MEDIA_ERROR_INTERNAL_SERVER_ERROR, "mock error"); } MockMediaPlayer::Source::Source(MockMediaPlayer* player, SourceId id) : mockMediaPlayer{player}, sourceId{id}, offset{MEDIA_PLAYER_INVALID_OFFSET}, started{this, "started", notifyPlaybackStarted}, paused{this, "paused", notifyPlaybackPaused}, resumed{this, "resumed", notifyPlaybackResumed}, stopped{this, "stopped", notifyPlaybackStopped}, finished{this, "finished", notifyPlaybackFinished}, error{this, "error", notifyPlaybackError} { } std::shared_ptr<MockMediaPlayer::Source> MockMediaPlayer::getCurrentSource(SourceId sourceId) { if (ERROR == sourceId || sourceId != getCurrentSourceId()) { return nullptr; } return m_sources[static_cast<size_t>(sourceId)]; } } // namespace test } // namespace mediaPlayer } // namespace utils } // namespace avsCommon } // namespace alexaClientSDK
32.807122
110
0.714182
jbfitbit
edd9480978f68420ed90cb40f63dbcc1603bfd59
4,026
cpp
C++
src/server/sqlrqueries.cpp
davidwed/sqlrelay
2c830ff2517bfdb1c70a880038cd326eb7a7f0d1
[ "PHP-3.01", "CC-BY-3.0" ]
16
2018-04-23T09:58:33.000Z
2022-01-31T13:40:20.000Z
src/server/sqlrqueries.cpp
davidwed/sqlrelay
2c830ff2517bfdb1c70a880038cd326eb7a7f0d1
[ "PHP-3.01", "CC-BY-3.0" ]
null
null
null
src/server/sqlrqueries.cpp
davidwed/sqlrelay
2c830ff2517bfdb1c70a880038cd326eb7a7f0d1
[ "PHP-3.01", "CC-BY-3.0" ]
4
2020-12-23T12:17:54.000Z
2022-01-04T20:46:34.000Z
// Copyright (c) 1999-2018 David Muse // See the file COPYING for more information #include <sqlrelay/sqlrserver.h> #include <rudiments/domnode.h> #include <rudiments/stdio.h> //#define DEBUG_MESSAGES 1 #include <rudiments/debugprint.h> #include <config.h> #ifndef SQLRELAY_ENABLE_SHARED extern "C" { #include "sqlrquerydeclarations.cpp" } #endif class sqlrqueryplugin { public: sqlrquery *qr; dynamiclib *dl; }; class sqlrqueriesprivate { friend class sqlrqueries; private: sqlrservercontroller *_cont; singlylinkedlist< sqlrqueryplugin * > _llist; }; sqlrqueries::sqlrqueries(sqlrservercontroller *cont) { debugFunction(); pvt=new sqlrqueriesprivate; pvt->_cont=cont; } sqlrqueries::~sqlrqueries() { debugFunction(); unload(); delete pvt; } bool sqlrqueries::load(domnode *parameters) { debugFunction(); unload(); // run through the query list for (domnode *query=parameters->getFirstTagChild(); !query->isNullNode(); query=query->getNextTagSibling()) { debugPrintf("loading query ...\n"); // load query loadQuery(query); } return true; } void sqlrqueries::unload() { debugFunction(); for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { sqlrqueryplugin *sqlrlp=node->getValue(); delete sqlrlp->qr; delete sqlrlp->dl; delete sqlrlp; } pvt->_llist.clear(); } void sqlrqueries::loadQuery(domnode *query) { debugFunction(); // ignore non-queries if (charstring::compare(query->getName(),"query")) { return; } // get the query name const char *module=query->getAttributeValue("module"); if (!charstring::length(module)) { // try "file", that's what it used to be called module=query->getAttributeValue("file"); if (!charstring::length(module)) { return; } } debugPrintf("loading query: %s\n",module); #ifdef SQLRELAY_ENABLE_SHARED // load the query module stringbuffer modulename; modulename.append(pvt->_cont->getPaths()->getLibExecDir()); modulename.append(SQLR); modulename.append("query_"); modulename.append(module)->append(".")->append(SQLRELAY_MODULESUFFIX); dynamiclib *dl=new dynamiclib(); if (!dl->open(modulename.getString(),true,true)) { stdoutput.printf("failed to load query module: %s\n",module); char *error=dl->getError(); stdoutput.printf("%s\n",(error)?error:""); delete[] error; delete dl; return; } // load the query itself stringbuffer functionname; functionname.append("new_sqlrquery_")->append(module); sqlrquery *(*newQuery)(sqlrservercontroller *, sqlrqueries *, domnode *)= (sqlrquery *(*)(sqlrservercontroller *, sqlrqueries *, domnode *)) dl->getSymbol(functionname.getString()); if (!newQuery) { stdoutput.printf("failed to load query: %s\n",module); char *error=dl->getError(); stdoutput.printf("%s\n",(error)?error:""); delete[] error; dl->close(); delete dl; return; } sqlrquery *qr=(*newQuery)(pvt->_cont,this,query); #else dynamiclib *dl=NULL; sqlrquery *qr; #include "sqlrqueryassignments.cpp" { qr=NULL; } #endif // add the plugin to the list sqlrqueryplugin *sqlrlp=new sqlrqueryplugin; sqlrlp->qr=qr; sqlrlp->dl=dl; pvt->_llist.append(sqlrlp); } sqlrquerycursor *sqlrqueries::match(sqlrserverconnection *sqlrcon, const char *querystring, uint32_t querylength, uint16_t id) { debugFunction(); for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { sqlrquery *qr=node->getValue()->qr; if (qr->match(querystring,querylength)) { return qr->newCursor(sqlrcon,id); } } return NULL; } void sqlrqueries::endTransaction(bool commit) { for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { node->getValue()->qr->endTransaction(commit); } } void sqlrqueries::endSession() { for (listnode< sqlrqueryplugin * > *node= pvt->_llist.getFirst(); node; node=node->getNext()) { node->getValue()->qr->endSession(); } }
22.120879
71
0.687531
davidwed
edda8f308f1510c8fcb5d8dc78057614569da231
794
cpp
C++
aws-cpp-sdk-connect/source/model/UpdateInstanceAttributeRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-connect/source/model/UpdateInstanceAttributeRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-connect/source/model/UpdateInstanceAttributeRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/connect/model/UpdateInstanceAttributeRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Connect::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateInstanceAttributeRequest::UpdateInstanceAttributeRequest() : m_instanceIdHasBeenSet(false), m_attributeType(InstanceAttributeType::NOT_SET), m_attributeTypeHasBeenSet(false), m_valueHasBeenSet(false) { } Aws::String UpdateInstanceAttributeRequest::SerializePayload() const { JsonValue payload; if(m_valueHasBeenSet) { payload.WithString("Value", m_value); } return payload.View().WriteReadable(); }
20.358974
69
0.755668
perfectrecall
eddba8dcff316a0908619f8e46fe2f8cbf86638c
6,253
ipp
C++
include/stats_incl/prob/plnorm.ipp
JohnGalbraith/stats
309c0e92d2326a58cad4544124c614e6a8a46079
[ "Apache-2.0" ]
381
2017-07-16T17:34:02.000Z
2022-03-30T09:47:58.000Z
include/stats_incl/prob/plnorm.ipp
myhhub/stats
309c0e92d2326a58cad4544124c614e6a8a46079
[ "Apache-2.0" ]
29
2017-07-14T20:45:42.000Z
2022-01-25T20:59:08.000Z
include/stats_incl/prob/plnorm.ipp
myhhub/stats
309c0e92d2326a58cad4544124c614e6a8a46079
[ "Apache-2.0" ]
70
2017-10-25T14:16:11.000Z
2022-01-25T20:57:02.000Z
/*################################################################################ ## ## Copyright (C) 2011-2021 Keith O'Hara ## ## This file is part of the StatsLib C++ library. ## ## 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. ## ################################################################################*/ /* * cdf of the univariate log-normal distribution */ // // single input namespace internal { template<typename T> statslib_constexpr T plnorm_vals_check(const T x, const T mu_par, const T sigma_par, const bool log_form) { return( !lnorm_sanity_check(x,mu_par,sigma_par) ? \ STLIM<T>::quiet_NaN() : // STLIM<T>::epsilon() > x ? \ log_zero_if<T>(log_form) : // pnorm(stmath::log(x),mu_par,sigma_par,log_form) ); } template<typename T1, typename T2, typename T3, typename TC = common_return_t<T1,T2,T3>> statslib_constexpr TC plnorm_type_check(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form) noexcept { return plnorm_vals_check(static_cast<TC>(x),static_cast<TC>(mu_par), static_cast<TC>(sigma_par),log_form); } } /** * @brief Distribution function of the Log-Normal distribution * * @param x a real-valued input. * @param mu_par the mean parameter, a real-valued input. * @param sigma_par the standard deviation parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return the cumulative distribution function evaluated at \c x. * * Example: * \code{.cpp} stats::plnorm(2.0,1.0,2.0,false); \endcode */ template<typename T1, typename T2, typename T3> statslib_constexpr common_return_t<T1,T2,T3> plnorm(const T1 x, const T2 mu_par, const T3 sigma_par, const bool log_form) noexcept { return internal::plnorm_type_check(x,mu_par,sigma_par,log_form); } // // vector/matrix input namespace internal { #ifdef STATS_ENABLE_INTERNAL_VEC_FEATURES template<typename eT, typename T1, typename T2, typename rT> statslib_inline void plnorm_vec(const eT* __stats_pointer_settings__ vals_in, const T1 mu_par, const T2 sigma_par, const bool log_form, rT* __stats_pointer_settings__ vals_out, const ullint_t num_elem) { EVAL_DIST_FN_VEC(plnorm,vals_in,vals_out,num_elem,mu_par,sigma_par,log_form); } #endif } /** * @brief Distribution function of the Log-Normal distribution * * @param x a standard vector. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a vector of CDF values corresponding to the elements of \c x. * * Example: * \code{.cpp} * std::vector<double> x = {0.0, 1.0, 2.0}; * stats::plnorm(x,1.0,2.0,false); * \endcode */ #ifdef STATS_ENABLE_STDVEC_WRAPPERS template<typename eT, typename T1, typename T2, typename rT> statslib_inline std::vector<rT> plnorm(const std::vector<eT>& x, const T1 mu_par, const T2 sigma_par, const bool log_form) { STDVEC_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } #endif /** * @brief Distribution function of the Log-Normal distribution * * @param X a matrix of input values. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a matrix of CDF values corresponding to the elements of \c X. * * Example: * \code{.cpp} * arma::mat X = { {0.2, 1.7, 0.1}, * {0.9, 4.0, 0.3} }; * stats::plnorm(X,1.0,1.0,false); * \endcode */ #ifdef STATS_ENABLE_ARMA_WRAPPERS template<typename eT, typename T1, typename T2, typename rT> statslib_inline ArmaMat<rT> plnorm(const ArmaMat<eT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { ARMA_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } template<typename mT, typename tT, typename T1, typename T2> statslib_inline mT plnorm(const ArmaGen<mT,tT>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { return plnorm(X.eval(),mu_par,sigma_par,log_form); } #endif /** * @brief Distribution function of the Log-Normal distribution * * @param X a matrix of input values. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a matrix of CDF values corresponding to the elements of \c X. * * Example: * \code{.cpp} * stats::plnorm(X,1.0,1.0,false); * \endcode */ #ifdef STATS_ENABLE_BLAZE_WRAPPERS template<typename eT, typename T1, typename T2, typename rT, bool To> statslib_inline BlazeMat<rT,To> plnorm(const BlazeMat<eT,To>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { BLAZE_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } #endif /** * @brief Distribution function of the Log-Normal distribution * * @param X a matrix of input values. * @param mu_par the location parameter, a real-valued input. * @param sigma_par the scale parameter, a real-valued input. * @param log_form return the log-probability or the true form. * * @return a matrix of CDF values corresponding to the elements of \c X. * * Example: * \code{.cpp} * stats::plnorm(X,1.0,1.0,false); * \endcode */ #ifdef STATS_ENABLE_EIGEN_WRAPPERS template<typename eT, typename T1, typename T2, typename rT, int iTr, int iTc> statslib_inline EigenMat<rT,iTr,iTc> plnorm(const EigenMat<eT,iTr,iTc>& X, const T1 mu_par, const T2 sigma_par, const bool log_form) { EIGEN_DIST_FN(plnorm_vec,mu_par,sigma_par,log_form); } #endif
29.356808
115
0.691028
JohnGalbraith
eddcffc19694dcb2ae1dd0da87ee1484aecc6aca
10,522
cpp
C++
src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst/generic.cpp
MaximMilashchenko/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
2,313
2017-03-24T16:25:28.000Z
2022-03-31T03:00:30.000Z
src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst/generic.cpp
0xgpapad/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
952
2017-03-28T07:05:58.000Z
2022-03-30T09:54:02.000Z
src/core/NEON/kernels/arm_conv/depthwise/kernels/sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst/generic.cpp
0xgpapad/ComputeLibrary
91ee4d0a9ef128b16936921470a0e3ffef347536
[ "MIT" ]
714
2017-03-24T22:21:51.000Z
2022-03-18T19:49:57.000Z
/* * Copyright (c) 2021 Arm Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <cstddef> #include <cstdint> #if defined(ARM_COMPUTE_ENABLE_SVE) namespace arm_conv { namespace depthwise { void sve_fp32_nhwc_3x3_s1_output2x2_mla_depthfirst_impl( const float *const *const input_ptrs, float *const *const outptrs, const void *params, unsigned int n_channels, const float activation_min, const float activation_max ) { const float *const inptrs[16] = { input_ptrs[0], input_ptrs[1], input_ptrs[4], input_ptrs[5], input_ptrs[2], input_ptrs[6], input_ptrs[3], input_ptrs[7], input_ptrs[8], input_ptrs[9], input_ptrs[10], input_ptrs[11], input_ptrs[12], input_ptrs[13], input_ptrs[14], input_ptrs[15], }; const float minmax_vals[2] = { activation_min, activation_max }; __asm__ __volatile__( "ldp x26, x23, [%x[inptrs], #0x0]\n" "ptrue p2.b\n" "ldp x25, x16, [%x[inptrs], #0x10]\n" "mov x15, #0x0\n" "ld1w { z15.s }, p2/Z, [%x[params]]\n" "mov z14.d, z15.d\n" "ld1w { z13.s }, p2/Z, [%x[params], #1, MUL VL]\n" "cntw x14\n" "mov z12.d, z15.d\n" "ld1w { z11.s }, p2/Z, [%x[params], #2, MUL VL]\n" "sub x13, XZR, x14\n" "mov z10.d, z15.d\n" "ld1w { z9.s }, p2/Z, [%x[params], #3, MUL VL]\n" "whilelt p1.s, XZR, %x[n_channels]\n" "mov z8.d, z15.d\n" "ld1w { z7.s }, p2/Z, [%x[params], #4, MUL VL]\n" "cmp x14, %x[n_channels]\n" "ld1w { z6.s }, p2/Z, [%x[params], #5, MUL VL]\n" "ld1w { z5.s }, p2/Z, [%x[params], #6, MUL VL]\n" "ld1w { z4.s }, p2/Z, [%x[params], #7, MUL VL]\n" "addvl %x[params], %x[params], #16\n" "ld1w { z3.s }, p1/Z, [x26, x15, LSL #2]\n" "ld1w { z2.s }, p2/Z, [%x[params], #-8, MUL VL]\n" "ld1w { z1.s }, p2/Z, [%x[params], #-7, MUL VL]\n" "addvl %x[params], %x[params], #-6\n" "ld1w { z0.s }, p1/Z, [x23, x15, LSL #2]\n" "ld1w { z31.s }, p1/Z, [x25, x15, LSL #2]\n" "ld1w { z30.s }, p1/Z, [x16, x15, LSL #2]\n" "ldp x24, x12, [%x[inptrs], #0x20]\n" "ldp x23, x11, [%x[inptrs], #0x30]\n" "ldp x10, x9, [%x[inptrs], #0x40]\n" "ld1w { z29.s }, p1/Z, [x24, x15, LSL #2]\n" "ld1w { z28.s }, p1/Z, [x12, x15, LSL #2]\n" "ld1w { z27.s }, p1/Z, [x23, x15, LSL #2]\n" "ld1w { z26.s }, p1/Z, [x11, x15, LSL #2]\n" "ld1w { z25.s }, p1/Z, [x10, x15, LSL #2]\n" "ld1w { z24.s }, p1/Z, [x9, x15, LSL #2]\n" "ldp x28, x27, [%x[inptrs], #0x50]\n" "ldp x26, x25, [%x[inptrs], #0x60]\n" "ldp x24, x23, [%x[inptrs], #0x70]\n" "ld1w { z23.s }, p1/Z, [x28, x15, LSL #2]\n" "ld1w { z22.s }, p1/Z, [x27, x15, LSL #2]\n" "ld1w { z21.s }, p1/Z, [x26, x15, LSL #2]\n" "ld1w { z20.s }, p1/Z, [x25, x15, LSL #2]\n" "ld1w { z19.s }, p1/Z, [x24, x15, LSL #2]\n" "ld1w { z18.s }, p1/Z, [x23, x15, LSL #2]\n" "ldp x22, x21, [%x[outptrs], #0x0]\n" "ldp x20, x19, [%x[outptrs], #0x10]\n" "ld1rw { z17.s }, p2/Z, [%x[minmax_vals]]\n" "ld1rw { z16.s }, p2/Z, [%x[minmax_vals], #4]\n" "bge 1f\n" "1:" // Loop "fmla z14.s, p2/M, z13.s, z3.s\n" "ld1w { z15.s }, p2/Z, [%x[params]]\n" "incw x13\n" "fmla z12.s, p2/M, z13.s, z0.s\n" "ldp x26, x23, [%x[inptrs], #0x0]\n" "mov p0.b, p1.b\n" "fmla z10.s, p2/M, z13.s, z31.s\n" "ldp x25, x16, [%x[inptrs], #0x10]\n" "mov x15, x14\n" "fmla z8.s, p2/M, z13.s, z30.s\n" "ld1w { z13.s }, p2/Z, [%x[params], #1, MUL VL]\n" "incw x14\n" "fmla z14.s, p2/M, z11.s, z0.s\n" "ldp x24, x12, [%x[inptrs], #0x20]\n" "whilelt p1.s, x15, %x[n_channels]\n" "fmla z12.s, p2/M, z11.s, z29.s\n" "ld1w { z3.s }, p1/Z, [x26, x15, LSL #2]\n" "cmp x14, %x[n_channels]\n" "fmla z10.s, p2/M, z11.s, z30.s\n" "ld1w { z0.s }, p1/Z, [x23, x15, LSL #2]\n" "ldp x23, x11, [%x[inptrs], #0x30]\n" "fmla z8.s, p2/M, z11.s, z28.s\n" "ld1w { z11.s }, p2/Z, [%x[params], #2, MUL VL]\n" "fmla z14.s, p2/M, z9.s, z29.s\n" "ld1w { z29.s }, p1/Z, [x24, x15, LSL #2]\n" "fmla z12.s, p2/M, z9.s, z27.s\n" "ld1w { z27.s }, p1/Z, [x23, x15, LSL #2]\n" "fmla z10.s, p2/M, z9.s, z28.s\n" "ldp x10, x9, [%x[inptrs], #0x40]\n" "fmla z8.s, p2/M, z9.s, z26.s\n" "ld1w { z9.s }, p2/Z, [%x[params], #3, MUL VL]\n" "fmla z14.s, p2/M, z7.s, z31.s\n" "ld1w { z31.s }, p1/Z, [x25, x15, LSL #2]\n" "fmla z12.s, p2/M, z7.s, z30.s\n" "ldp x28, x27, [%x[inptrs], #0x50]\n" "fmla z10.s, p2/M, z7.s, z25.s\n" "ldp x26, x25, [%x[inptrs], #0x60]\n" "fmla z8.s, p2/M, z7.s, z24.s\n" "ld1w { z7.s }, p2/Z, [%x[params], #4, MUL VL]\n" "fmla z14.s, p2/M, z6.s, z30.s\n" "ld1w { z30.s }, p1/Z, [x16, x15, LSL #2]\n" "fmla z12.s, p2/M, z6.s, z28.s\n" "ldp x24, x23, [%x[inptrs], #0x70]\n" "fmla z10.s, p2/M, z6.s, z24.s\n" "fmla z8.s, p2/M, z6.s, z23.s\n" "ld1w { z6.s }, p2/Z, [%x[params], #5, MUL VL]\n" "fmla z14.s, p2/M, z5.s, z28.s\n" "ld1w { z28.s }, p1/Z, [x12, x15, LSL #2]\n" "fmla z12.s, p2/M, z5.s, z26.s\n" "ld1w { z26.s }, p1/Z, [x11, x15, LSL #2]\n" "fmla z10.s, p2/M, z5.s, z23.s\n" "fmla z8.s, p2/M, z5.s, z22.s\n" "ld1w { z5.s }, p2/Z, [%x[params], #6, MUL VL]\n" "fmla z14.s, p2/M, z4.s, z25.s\n" "ld1w { z25.s }, p1/Z, [x10, x15, LSL #2]\n" "fmla z12.s, p2/M, z4.s, z24.s\n" "fmla z10.s, p2/M, z4.s, z21.s\n" "ld1w { z21.s }, p1/Z, [x26, x15, LSL #2]\n" "fmla z8.s, p2/M, z4.s, z20.s\n" "ld1w { z4.s }, p2/Z, [%x[params], #7, MUL VL]\n" "addvl %x[params], %x[params], #16\n" "fmla z14.s, p2/M, z2.s, z24.s\n" "ld1w { z24.s }, p1/Z, [x9, x15, LSL #2]\n" "fmla z12.s, p2/M, z2.s, z23.s\n" "fmla z10.s, p2/M, z2.s, z20.s\n" "ld1w { z20.s }, p1/Z, [x25, x15, LSL #2]\n" "fmla z8.s, p2/M, z2.s, z19.s\n" "ld1w { z2.s }, p2/Z, [%x[params], #-8, MUL VL]\n" "fmla z14.s, p2/M, z1.s, z23.s\n" "ld1w { z23.s }, p1/Z, [x28, x15, LSL #2]\n" "fmla z12.s, p2/M, z1.s, z22.s\n" "ld1w { z22.s }, p1/Z, [x27, x15, LSL #2]\n" "fmla z10.s, p2/M, z1.s, z19.s\n" "ld1w { z19.s }, p1/Z, [x24, x15, LSL #2]\n" "fmla z8.s, p2/M, z1.s, z18.s\n" "ld1w { z1.s }, p2/Z, [%x[params], #-7, MUL VL]\n" "addvl %x[params], %x[params], #-6\n" "fmax z14.s, p2/M, z14.s, z17.s\n" "ld1w { z18.s }, p1/Z, [x23, x15, LSL #2]\n" "fmax z12.s, p2/M, z12.s, z17.s\n" "fmax z10.s, p2/M, z10.s, z17.s\n" "fmax z8.s, p2/M, z8.s, z17.s\n" "fmin z14.s, p2/M, z14.s, z16.s\n" "st1w { z14.s }, p0, [x22, x13, LSL #2]\n" "mov z14.d, z15.d\n" "fmin z12.s, p2/M, z12.s, z16.s\n" "st1w { z12.s }, p0, [x21, x13, LSL #2]\n" "mov z12.d, z15.d\n" "fmin z10.s, p2/M, z10.s, z16.s\n" "st1w { z10.s }, p0, [x20, x13, LSL #2]\n" "mov z10.d, z15.d\n" "fmin z8.s, p2/M, z8.s, z16.s\n" "st1w { z8.s }, p0, [x19, x13, LSL #2]\n" "mov z8.d, z15.d\n" "blt 1b\n" "2:" // Tail "fmla z14.s, p2/M, z13.s, z3.s\n" "incw x13\n" "fmla z12.s, p2/M, z13.s, z0.s\n" "mov p0.b, p1.b\n" "fmla z10.s, p2/M, z13.s, z31.s\n" "fmla z8.s, p2/M, z13.s, z30.s\n" "fmla z14.s, p2/M, z11.s, z0.s\n" "fmla z12.s, p2/M, z11.s, z29.s\n" "fmla z10.s, p2/M, z11.s, z30.s\n" "fmla z8.s, p2/M, z11.s, z28.s\n" "fmla z14.s, p2/M, z9.s, z29.s\n" "fmla z12.s, p2/M, z9.s, z27.s\n" "fmla z10.s, p2/M, z9.s, z28.s\n" "fmla z8.s, p2/M, z9.s, z26.s\n" "fmla z14.s, p2/M, z7.s, z31.s\n" "fmla z12.s, p2/M, z7.s, z30.s\n" "fmla z10.s, p2/M, z7.s, z25.s\n" "fmla z8.s, p2/M, z7.s, z24.s\n" "fmla z14.s, p2/M, z6.s, z30.s\n" "fmla z12.s, p2/M, z6.s, z28.s\n" "fmla z10.s, p2/M, z6.s, z24.s\n" "fmla z8.s, p2/M, z6.s, z23.s\n" "fmla z14.s, p2/M, z5.s, z28.s\n" "fmla z12.s, p2/M, z5.s, z26.s\n" "fmla z10.s, p2/M, z5.s, z23.s\n" "fmla z8.s, p2/M, z5.s, z22.s\n" "fmla z14.s, p2/M, z4.s, z25.s\n" "fmla z12.s, p2/M, z4.s, z24.s\n" "fmla z10.s, p2/M, z4.s, z21.s\n" "fmla z8.s, p2/M, z4.s, z20.s\n" "fmla z14.s, p2/M, z2.s, z24.s\n" "fmla z12.s, p2/M, z2.s, z23.s\n" "fmla z10.s, p2/M, z2.s, z20.s\n" "fmla z8.s, p2/M, z2.s, z19.s\n" "fmla z14.s, p2/M, z1.s, z23.s\n" "fmla z12.s, p2/M, z1.s, z22.s\n" "fmla z10.s, p2/M, z1.s, z19.s\n" "fmla z8.s, p2/M, z1.s, z18.s\n" "fmax z14.s, p2/M, z14.s, z17.s\n" "fmax z12.s, p2/M, z12.s, z17.s\n" "fmax z10.s, p2/M, z10.s, z17.s\n" "fmax z8.s, p2/M, z8.s, z17.s\n" "fmin z14.s, p2/M, z14.s, z16.s\n" "st1w { z14.s }, p0, [x22, x13, LSL #2]\n" "fmin z12.s, p2/M, z12.s, z16.s\n" "fmin z10.s, p2/M, z10.s, z16.s\n" "st1w { z12.s }, p0, [x21, x13, LSL #2]\n" "fmin z8.s, p2/M, z8.s, z16.s\n" "st1w { z10.s }, p0, [x20, x13, LSL #2]\n" "st1w { z8.s }, p0, [x19, x13, LSL #2]\n" : [params] "+r" (params) : [inptrs] "r" (inptrs), [minmax_vals] "r" (minmax_vals), [n_channels] "r" ((unsigned long) n_channels), [outptrs] "r" (outptrs) : "cc", "memory", "p0", "p1", "p2", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "z0", "z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8", "z9", "z10", "z11", "z12", "z13", "z14", "z15", "z16", "z17", "z18", "z19", "z20", "z21", "z22", "z23", "z24", "z25", "z26", "z27", "z28", "z29", "z30", "z31" ); } } // namespace depthwise } // namespace arm_conv #endif // defined(ARM_COMPUTE_ENABLE_SVE)
41.101563
377
0.529272
MaximMilashchenko
eddd0157faf869511f780c3e1521ca932fc1a630
7,434
cpp
C++
lib/SILGen/SwitchEnumBuilder.cpp
cachemeifyoucan/swift
6780f3d8c71904ba26c0fca33a1004b5776b9be2
[ "Apache-2.0" ]
null
null
null
lib/SILGen/SwitchEnumBuilder.cpp
cachemeifyoucan/swift
6780f3d8c71904ba26c0fca33a1004b5776b9be2
[ "Apache-2.0" ]
null
null
null
lib/SILGen/SwitchEnumBuilder.cpp
cachemeifyoucan/swift
6780f3d8c71904ba26c0fca33a1004b5776b9be2
[ "Apache-2.0" ]
null
null
null
//===--- SwitchEnumBuilder.cpp --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "SwitchEnumBuilder.h" #include "SILGenFunction.h" #include "swift/SIL/SILLocation.h" using namespace swift; using namespace Lowering; //===----------------------------------------------------------------------===// // SwitchCaseFullExpr Implementation //===----------------------------------------------------------------------===// SwitchCaseFullExpr::SwitchCaseFullExpr(SILGenFunction &SGF, CleanupLocation loc) : SGF(SGF), scope(SGF, loc), loc(loc), branchDest() {} SwitchCaseFullExpr::SwitchCaseFullExpr(SILGenFunction &SGF, CleanupLocation loc, SwitchCaseBranchDest branchDest) : SGF(SGF), scope(SGF, loc), loc(loc), branchDest(branchDest) {} void SwitchCaseFullExpr::exitAndBranch(SILLocation loc, ArrayRef<SILValue> branchArgs) { assert(bool(branchDest) && "Must have a branch destination!"); assert(SGF.B.hasValidInsertionPoint()); scope.pop(); // Then either do a direct branch or a branch + cleanups. if (SILBasicBlock *block = branchDest.getBlock()) { SGF.B.createBranch(loc, block, branchArgs); return; } SGF.Cleanups.emitBranchAndCleanups(branchDest.getJumpDest(), loc, branchArgs); } void SwitchCaseFullExpr::exit() { assert(!bool(branchDest) && "Should not call this if we do have a continuation block"); assert(SGF.B.hasValidInsertionPoint()); scope.pop(); } SwitchCaseFullExpr::~SwitchCaseFullExpr() { assert(!scope.isValid() && "Did not pop scope?!"); } void SwitchCaseFullExpr::unreachableExit() { // This is important to ensure that we do not actually emit any cleanups since // we already know that an unreachable was emitted. assert(!SGF.B.hasValidInsertionPoint() && "Expected to pop scope without a " "valid insertion point!"); scope.pop(); } //===----------------------------------------------------------------------===// // SwitchEnumBuilder Implementation //===----------------------------------------------------------------------===// void SwitchEnumBuilder::emit() && { bool isAddressOnly = subjectExprOperand.getType().isAddressOnly(builder.getFunction()) && getSGF().silConv.useLoweredAddresses(); using DeclBlockPair = std::pair<EnumElementDecl *, SILBasicBlock *>; { // TODO: We could store the data in CaseBB form and not have to do this. llvm::SmallVector<DeclBlockPair, 8> caseBlocks; llvm::SmallVector<ProfileCounter, 8> caseBlockCounts; std::transform(caseDataArray.begin(), caseDataArray.end(), std::back_inserter(caseBlocks), [](NormalCaseData &caseData) -> DeclBlockPair { return {caseData.decl, caseData.block}; }); std::transform(caseDataArray.begin(), caseDataArray.end(), std::back_inserter(caseBlockCounts), [](NormalCaseData &caseData) -> ProfileCounter { return caseData.count; }); SILBasicBlock *defaultBlock = defaultBlockData ? defaultBlockData->block : nullptr; ProfileCounter defaultBlockCount = defaultBlockData ? defaultBlockData->count : ProfileCounter(); ArrayRef<ProfileCounter> caseBlockCountsRef = caseBlockCounts; if (isAddressOnly) { builder.createSwitchEnumAddr(loc, subjectExprOperand.getValue(), defaultBlock, caseBlocks, caseBlockCountsRef, defaultBlockCount); } else { if (subjectExprOperand.getType().isAddress()) { // TODO: Refactor this into a maybe load. if (subjectExprOperand.hasCleanup()) { subjectExprOperand = builder.createLoadTake(loc, subjectExprOperand); } else { subjectExprOperand = builder.createLoadCopy(loc, subjectExprOperand); } } builder.createSwitchEnum(loc, subjectExprOperand.forward(getSGF()), defaultBlock, caseBlocks, caseBlockCountsRef, defaultBlockCount); } } // If we are asked to create a default block and it is specified that the // default block should be emitted before normal cases, emit it now. if (defaultBlockData && defaultBlockData->dispatchTime == DefaultDispatchTime::BeforeNormalCases) { SILBasicBlock *defaultBlock = defaultBlockData->block; SwitchCaseBranchDest branchDest = defaultBlockData->branchDest; DefaultCaseHandler handler = defaultBlockData->handler; // Don't allow cleanups to escape the conditional block. SwitchCaseFullExpr presentScope(builder.getSILGenFunction(), CleanupLocation(loc), branchDest); builder.emitBlock(defaultBlock); ManagedValue input = subjectExprOperand; if (!isAddressOnly) { input = builder.createOwnedPhiArgument(subjectExprOperand.getType()); } handler(input, std::move(presentScope)); builder.clearInsertionPoint(); } for (NormalCaseData &caseData : caseDataArray) { EnumElementDecl *decl = caseData.decl; SILBasicBlock *caseBlock = caseData.block; SwitchCaseBranchDest branchDest = caseData.branchDest; NormalCaseHandler handler = caseData.handler; // Don't allow cleanups to escape the conditional block. SwitchCaseFullExpr presentScope(builder.getSILGenFunction(), CleanupLocation(loc), branchDest); builder.emitBlock(caseBlock); ManagedValue input; if (decl->hasAssociatedValues()) { // Pull the payload out if we have one. SILType inputType = subjectExprOperand.getType().getEnumElementType( decl, builder.getModule(), builder.getFunction()); input = subjectExprOperand; if (!isAddressOnly) { input = builder.createOwnedPhiArgument(inputType); } } handler(input, std::move(presentScope)); builder.clearInsertionPoint(); } // If we are asked to create a default block and it is specified that the // default block should be emitted after normal cases, emit it now. if (defaultBlockData && defaultBlockData->dispatchTime == DefaultDispatchTime::AfterNormalCases) { SILBasicBlock *defaultBlock = defaultBlockData->block; auto branchDest = defaultBlockData->branchDest; DefaultCaseHandler handler = defaultBlockData->handler; // Don't allow cleanups to escape the conditional block. SwitchCaseFullExpr presentScope(builder.getSILGenFunction(), CleanupLocation(loc), branchDest); builder.emitBlock(defaultBlock); ManagedValue input = subjectExprOperand; if (!isAddressOnly) { input = builder.createOwnedPhiArgument(subjectExprOperand.getType()); } handler(input, std::move(presentScope)); builder.clearInsertionPoint(); } }
41.530726
80
0.631558
cachemeifyoucan
ede71ec889767958aaeaabc0f5d3e3b97c2b0069
1,498
cpp
C++
samples/SamplesCommon/Parameters.cpp
alarouche/czrpc
cb2d7611d701152ace8e31230f64c0fb12e48276
[ "MIT" ]
30
2017-06-11T10:36:05.000Z
2021-09-22T13:09:40.000Z
samples/SamplesCommon/Parameters.cpp
alarouche/czrpc
cb2d7611d701152ace8e31230f64c0fb12e48276
[ "MIT" ]
1
2018-01-24T09:49:51.000Z
2018-01-24T09:49:51.000Z
samples/SamplesCommon/Parameters.cpp
alarouche/czrpc
cb2d7611d701152ace8e31230f64c0fb12e48276
[ "MIT" ]
6
2018-02-16T17:02:48.000Z
2021-09-22T13:09:44.000Z
/******************************************************************** CrazyGaze (http://www.crazygaze.com) Author : Rui Figueira Email : [email protected] purpose: *********************************************************************/ #include "SamplesCommonPCH.h" #include "Parameters.h" namespace cz { std::string Parameters::ms_empty; Parameters::Parameters() { } void Parameters::set(int argc, char* argv[]) { if (argc<=1) return; for (int i=1; i<argc; i++) { const char *arg = argv[i]; if (*arg == '-') arg++; const char *seperator = strchr(arg, '='); if (seperator==nullptr) { m_args.emplace_back(arg, ""); } else { std::string name(arg, seperator); std::string value(++seperator); m_args.emplace_back(std::move(name), std::move(value)); } } } const Parameters::Param* Parameters::begin() const { if (m_args.size()) return &m_args[0]; else return nullptr; } const Parameters::Param* Parameters::end() const { return begin() + m_args.size(); } bool Parameters::has( const char* name ) const { for(auto &i: m_args) { if (i.name==name) { return true; } } return false; } bool Parameters::has( const std::string& name ) const { return has(name.c_str()); } const std::string& Parameters::get( const char *name ) const { for (auto &i: m_args) { if (i.name==name) return i.value; } return ms_empty; } } // namespace cz
16.831461
71
0.535381
alarouche
edea3c1be60b87c60f412f998c78bc3592f35d15
2,402
cpp
C++
cpp/godot-cpp/src/gen/Skin.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/Skin.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/Skin.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "Skin.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" namespace godot { Skin::___method_bindings Skin::___mb = {}; void Skin::___init_method_bindings() { ___mb.mb_add_bind = godot::api->godot_method_bind_get_method("Skin", "add_bind"); ___mb.mb_clear_binds = godot::api->godot_method_bind_get_method("Skin", "clear_binds"); ___mb.mb_get_bind_bone = godot::api->godot_method_bind_get_method("Skin", "get_bind_bone"); ___mb.mb_get_bind_count = godot::api->godot_method_bind_get_method("Skin", "get_bind_count"); ___mb.mb_get_bind_pose = godot::api->godot_method_bind_get_method("Skin", "get_bind_pose"); ___mb.mb_set_bind_bone = godot::api->godot_method_bind_get_method("Skin", "set_bind_bone"); ___mb.mb_set_bind_count = godot::api->godot_method_bind_get_method("Skin", "set_bind_count"); ___mb.mb_set_bind_pose = godot::api->godot_method_bind_get_method("Skin", "set_bind_pose"); } Skin *Skin::_new() { return (Skin *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"Skin")()); } void Skin::add_bind(const int64_t bone, const Transform pose) { ___godot_icall_void_int_Transform(___mb.mb_add_bind, (const Object *) this, bone, pose); } void Skin::clear_binds() { ___godot_icall_void(___mb.mb_clear_binds, (const Object *) this); } int64_t Skin::get_bind_bone(const int64_t bind_index) const { return ___godot_icall_int_int(___mb.mb_get_bind_bone, (const Object *) this, bind_index); } int64_t Skin::get_bind_count() const { return ___godot_icall_int(___mb.mb_get_bind_count, (const Object *) this); } Transform Skin::get_bind_pose(const int64_t bind_index) const { return ___godot_icall_Transform_int(___mb.mb_get_bind_pose, (const Object *) this, bind_index); } void Skin::set_bind_bone(const int64_t bind_index, const int64_t bone) { ___godot_icall_void_int_int(___mb.mb_set_bind_bone, (const Object *) this, bind_index, bone); } void Skin::set_bind_count(const int64_t bind_count) { ___godot_icall_void_int(___mb.mb_set_bind_count, (const Object *) this, bind_count); } void Skin::set_bind_pose(const int64_t bind_index, const Transform pose) { ___godot_icall_void_int_Transform(___mb.mb_set_bind_pose, (const Object *) this, bind_index, pose); } }
36.393939
189
0.781848
GDNative-Gradle
edeb1b7a00cce0c49960a76b69fe0b8db0f4b374
25,545
cpp
C++
source/Visitors/TerrainBrush.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/Visitors/TerrainBrush.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
source/Visitors/TerrainBrush.cpp
badbrainz/pme
1c8e6f3d154cc59613f5ef3f2f8293f488c64b28
[ "WTFPL" ]
null
null
null
#include "TerrainBrush.h" #include "../Kernel/Gateway.h" #include "../Geometry/Ray3D.h" #include "../Factories/TerrainVisuals.h" #include "../Factories/TerrainPasture.h" #include "../Factories/TerrainLogic.h" #include "../Factories/WorldVisuals.h" #include "../Factories/Meadow.h" #include "../Factories/Water.h" #include "../Managers/ManagersUtils.h" #include "../Controllers/VillageModelController.h" #include "../Controllers/TileController.h" #include "../Databases/TerrainDatabase.h" #include "../Databases/ModelDatabase.h" #include "../Nodes/SpatialIndexNode.h" #include "../Nodes/SpatialIndexCell.h" #include "../Nodes/TransformGroup.h" #include "../Tools/NodeIterator.h" #include "../Tools/RangeIterator.h" #include "../Strategies/BrushBitEStrategy.h" #include "../Strategies/BrushBitDStrategy.h" #include "../Containers/ocsort.h" TerrainBrush::TerrainBrush() { strategies.append(new BrushBitEStrategy()); strategies.append(new BrushBitDStrategy()); reset(); } void TerrainBrush::visit(SpatialIndexBaseNode* node) { pointAVLTree.clear(); if (intersect(&node->getBoundsDescriptor())) { NodeIterator iter(node->getFirstChild()); while (!iter.end()) { iter.current()->accept(this); iter++; } } if (pointAVLTree.isEmpty()) return; if (saveCollPoint) { AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); if (!enabled) return; } switch (type) { case BrushTypes::TILE: editTiles(); break; case BrushTypes::GRASS: editGrass(); break; case BrushTypes::WATER: editWater(); break; case BrushTypes::MODEL: editModel(); break; default: break; } } void TerrainBrush::visit(SpatialIndexNode* node) { if (intersect(&node->getBoundsDescriptor())) { NodeIterator iter(node->getFirstChild()); while (!iter.end()) { iter.current()->accept(this); iter++; } } } void TerrainBrush::visit(SpatialIndexCell* node) { BoundsDescriptor *bounds = &node->getBoundsDescriptor(); TileController* controller; RangeIterator iter; Tuple4f packet; Tuple3f point; float distance; TerrainVisuals* visuals = Gateway::getTerrainVisuals(); TerrainDatabase* tdatabase = Gateway::getTerrainDatabase(); if (node->isVisible()) if (intersect(bounds)) { if (showGuides) { glColor3ub(255, 255, 255); bounds->render(BoundsDescriptor::AABB | BoundsDescriptor::WIRE); } if (enabled || saveCollPoint) { iter.set(visuals->getArea().x, node->getRange()); while (!iter.end()) { controller = tdatabase->getController(iter.current()); packet = intersector.intersectTriangles(ray, controller->getVertices(), visuals->getTileIndices(0), 8); if (1 == packet.w) { point.set(packet.x, packet.y, packet.z); distance = point.getDistance(ray->getOrigin()); if (2.0f < distance) pointAVLTree.insertKeyAndValue(distance, point); } iter++; } } } } void TerrainBrush::editModel() { ModelDatabase *ndatabase, *sdatabase, *vdatabase, *cdatabase; WorldVisuals* wVisuals; //int ctrlindex; GSElementInfo* info; ModelController* controller; AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); switch (layer) { case BrushLayers::CHARACTER: if (constant) { info = Gateway::getActiveCharacterInfo(); if (info->name) { cdatabase = Gateway::getCharacterDatabase(); controller = cdatabase->instantiateModel(info->name); controller->translateModel(cpoint.x, cpoint.y + 0.05f, cpoint.z); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); Gateway::getMapDescriptor().playerPositions.append(Tuple2f(cpoint.x, cpoint.z)); } } break; case BrushLayers::CRITTER: if (constant) { info = Gateway::getActiveCritterInfo(); if (info->name) { cdatabase = Gateway::getCritterDatabase(); controller = cdatabase->instantiateModel(info->name); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); float y = controller->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y; Tuple3f cen = controller->getTransformGroup()->getBoundsDescriptor().getCenterAABB(); controller->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z); wVisuals = Gateway::getWorldVisuals(); WorldObject worldObject; worldObject.flags = 0; worldObject.name = info->name; worldObject.type = WorldObjectTypes::CRITTER; worldObject.orientation = 0.0f; worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z); worldObject.windFactor = 0.0f; wVisuals->addObject(worldObject); } } break; case BrushLayers::NATURE: if (constant) { info = Gateway::getActiveNatureInfo(); if (info->name) { ndatabase = Gateway::getNatureDatabase(); controller = ndatabase->instantiateModel(info->name); controller->translateModel(cpoint.x, cpoint.y + 0.05f, cpoint.z); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); ///cannot subtract y because that would cause a problem with canopy models wVisuals = Gateway::getWorldVisuals(); WorldObject worldObject; worldObject.flags = 0; worldObject.name = info->name; worldObject.type = WorldObjectTypes::NATURE; worldObject.orientation = 0.79f; worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z); worldObject.windFactor = info->windFactor; wVisuals->addObject(worldObject); } } break; case BrushLayers::STRUCTURE: if (constant) { info = Gateway::getActiveStructureInfo(); if (info->name) { sdatabase = Gateway::getStructureDatabase(); controller = sdatabase->instantiateModel(info->name); TransformGroupNode* tgnode = controller->getTGNode(); tgnode->attach(Gateway::getSpatialCell(cpoint)); float y = controller->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y; Tuple3f cen = controller->getTransformGroup()->getBoundsDescriptor().getCenterAABB(); controller->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z); wVisuals = Gateway::getWorldVisuals(); WorldObject worldObject; worldObject.flags = 0; worldObject.name = info->name; worldObject.type = WorldObjectTypes::STRUCTURE; worldObject.orientation = 0.0f; worldObject.position.set(cpoint.x, cpoint.y + 0.05f, cpoint.z); worldObject.windFactor = 0.0f; wVisuals->addObject(worldObject); } } break; case BrushLayers::VILLAGE: if (constant) { info = Gateway::getActiveVillageInfo(); if (info->name) { vdatabase = Gateway::getVillageDatabase(); VillageModelController* villageController = (VillageModelController*) vdatabase->instantiateModel(info->name); villageController->setPopulation(info->population); villageController->setMaxPopulation(info->maxpopulation); float y = villageController->getTransformGroup()->getBoundsDescriptor().getMinEndAABB().y; Tuple3f cen = villageController->getTransformGroup()->getBoundsDescriptor().getCenterAABB(); villageController->translateModel(cpoint.x - cen.x, cpoint.y + 0.05f - y, cpoint.z - cen.z); } } break; default: break; } } void TerrainBrush::editTiles() { if (layer != BrushLayers::TILE) return; TileController *controller; Tuple3f *verts; Tuple4ub *cols; float s, y, d; unsigned int lflag; char col; RangeIterator tileiter; TerrainVisuals* visuals = Gateway::getTerrainVisuals(); TerrainLogic* terrainLogic = Gateway::getTerrainLogic(); TerrainDatabase* tdatabase = Gateway::getTerrainDatabase(); AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); if (mode == BrushModes::FILL) { if (constant) if (txcoordsIndex >= 0) for (unsigned int i = 0; i < tdatabase->getControllerCount(); i++) tdatabase->changeTileTexture(level, txcoordsIndex, i, !tdatabase->getController(i)->isVisible()); return; } ++pointIter; cpoint = pointIter.value(); Tuple2i area(visuals->getArea()); unsigned int xOff = clamp(int(cpoint.x - radius), 0, area.y - 1); unsigned int yOff = clamp(int(cpoint.z - radius), 0, area.x - 1); unsigned int zOff = clamp(int(cpoint.x + radius), 0, area.y - 1); unsigned int wOff = clamp(int(cpoint.z + radius), 0, area.x - 1); tileiter.set(area.x, Tuple4i(yOff, xOff, wOff, zOff)); glPointSize(2.0f); glColor3ub(255, 200, 0); glBegin(GL_POINTS); while (!tileiter.end()) { controller = tdatabase->getController(tileiter.current()); verts = controller->getVertices(); cols = controller->getColors(); switch (mode) { case BrushModes::ROTATE90: if (constant) controller->setFlags(TileFlags::TEXTURE_ROTATE90); break; case BrushModes::ROTATE180: if (constant) controller->setFlags(TileFlags::TEXTURE_ROTATE180); break; case BrushModes::ROTATE270: if (constant) controller->setFlags(TileFlags::TEXTURE_ROTATE270); break; case BrushModes::MIRRORX: if (constant) controller->setFlags(TileFlags::TEXTURE_MIRRORX); break; case BrushModes::MIRRORY: if (constant) controller->setFlags(TileFlags::TEXTURE_MIRRORY); break; //case BrushModes::VISIBLE: // // if (constant) // controller->setFlags(TileFlags::TILE_VISIBLE); // // break; // //case BrushModes::QUAD0DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD0_DIAGONAL); // // break; // //case BrushModes::QUAD1DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD1_DIAGONAL); // // break; // //case BrushModes::QUAD2DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD2_DIAGONAL); // // break; // //case BrushModes::QUAD3DIAGONAL: // // if (constant) // controller->setFlags(TileFlags::QUAD3_DIAGONAL); // // break; // //case BrushModes::DYNAMICMIX: // // if (constant) // controller->setFlags(TileFlags::DYNAMIC_MIX); // // break; // //case BrushModes::NOTESSELATE: // // if (constant) // controller->setFlags(TileFlags::TILE_NOTESSELLATE); // // break; case BrushModes::RAISE: for (unsigned int v = 0; v < 9; v++) { d = verts[v].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; verts[v].y += time * strength * 6 * exp(s); glVertex3f(verts[v].x, verts[v].y + 0.1f, verts[v].z); } } break; case BrushModes::LOWER: for (unsigned int v = 0; v < 9; v++) { d = verts[v].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; verts[v].y += time * -strength * 6 * exp(s); glVertex3f(verts[v].x, verts[v].y + 0.1f, verts[v].z); } } break; case BrushModes::ERASE: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 3 * exp(s); col = (char)(y * 255); cols[c].w -= cols[c].w <= col ? 0 : col; glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::RESTORE: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 3 * exp(s); cols[c].w += (char)((255 - cols[c].w) * y); glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::BURN: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 2 * exp(s); col = (char)(y * 255); cols[c].x -= cols[c].x < col ? 0 : col; cols[c].y -= cols[c].y < col ? 0 : col; cols[c].z -= cols[c].z < col ? 0 : col; glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::HEAL: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { s = -(d * d) / radius; y = time * strength * 2 * exp(s); cols[c].x += (char) round((255 - cols[c].x) * y); cols[c].y += (char) round((255 - cols[c].y) * y); cols[c].z += (char) round((255 - cols[c].z) * y); glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::PAINT: if (verts[4].getDistance(cpoint) <= radius) tdatabase->changeTileTexture(level, txcoordsIndex, tileiter.current()); break; case BrushModes::MARKER: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { y = time * opacity; col = (char)(y * 255); cols[c].x -= cols[c].x <= col ? 0 : col; cols[c].y -= cols[c].y <= col ? 0 : col; cols[c].z -= cols[c].z <= col ? 0 : col; glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::PASTEL: for (unsigned int c = 0; c < 9; c++) { d = verts[c].getDistance(cpoint); if (d <= radius) { cols[c].x = char(255 * opacity); cols[c].y = char(255 * opacity); cols[c].z = char(255 * opacity); glVertex3f(verts[c].x, verts[c].y + 0.1f, verts[c].z); } } break; case BrushModes::ERASETILE: if (verts[4].getDistance(cpoint) <= radius) tdatabase->changeTileTexture(level, -1, tileiter.current()); break; case BrushModes::LOGIC: if (logicflag != TileTypes::GRASSFIELD) if (verts[4].getDistance(cpoint) <= radius) { lflag = terrainLogic->getFlags(tileiter.current()); terrainLogic->setFlags(tileiter.current(), strategy->getType((lflag & MASK_FLAGS), logicflag)); } break; case BrushModes::FLAG: if (verts[4].getDistance(cpoint) <= radius) { lflag = terrainLogic->getFlags(tileiter.current()); terrainLogic->setFlags(tileiter.current(), strategy->getFlags(lflag, logicflag)); } break; case BrushModes::ADVANCED: if (verts[4].getDistance(cpoint) <= radius) { BrushMatrixDescriptor* descriptor = &Gateway::getBrushMatrixDescriptor(); if (!descriptor->tileList.isEmpty()) { int col = tileiter.current() - int(tileiter.current()/area.y) * area.y; int row = int(tileiter.current()/area.y); int mx = col % descriptor->dimensions.x; int my = row % descriptor->dimensions.y; Tile *mtile = &descriptor->tileList(my * descriptor->dimensions.x + mx); tdatabase->changeTileTexture(level, mtile->textureID[0], tileiter.current()); controller->clearFlags(); controller->setFlags(mtile->flags); } } break; case BrushModes::POINTER: break; default: break; } tileiter++; } glEnd(); glPointSize(1.0f); if (mode < BrushModes::PAINT) Gateway::updateSpatialIndex(cpoint, radius); } void TerrainBrush::editGrass() { if (layer != BrushLayers::GRASS && mode != BrushModes::LOGIC && type != BrushTypes::GRASS) return; if (meadowname.isBlank()) return; Tuple3f *verts; RangeIterator tileiter; GrassPatch* patch; Meadow* meadow; int meadowindex; unsigned int lflag; TerrainVisuals* visuals = Gateway::getTerrainVisuals(); TerrainDatabase* tdatabase = Gateway::getTerrainDatabase(); TerrainPasture* terrainPasture = Gateway::getTerrainPasture(); TerrainLogic* terrainLogic = Gateway::getTerrainLogic(); AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); Tuple2i area(visuals->getArea()); unsigned int xOff = clamp(int(cpoint.x - radius), 0, area.y - 1); unsigned int yOff = clamp(int(cpoint.z - radius), 0, area.x - 1); unsigned int zOff = clamp(int(cpoint.x + radius), 0, area.y - 1); unsigned int wOff = clamp(int(cpoint.z + radius), 0, area.x - 1); tileiter.set(area.x, Tuple4i(yOff, xOff, wOff, zOff)); while (!tileiter.end()) { verts = tdatabase->getController(tileiter.current())->getVertices(); if (verts[4].getDistance(cpoint) <= radius) { meadowindex = terrainPasture->getMeadowIndex(meadowname); meadow = terrainPasture->getMeadow(meadowindex); if (!meadow->containsTileIndex(tileiter.current())) { if (patch = terrainPasture->createPatch(meadowindex)) { patch->position.set(tileiter.current() - int(tileiter.current()/area.y) * area.y, int(tileiter.current()/area.y)); patch->range.set(0x00000000,0x00000000); patch->color.set(0xff); } lflag = terrainLogic->getFlags(tileiter.current()); terrainLogic->setFlags(tileiter.current(), (lflag & MASK_FLAGS) | (TileTypes::GRASSFIELD << 27)); //terrainLogic->setFlags(tileiter.current(), strategy->getType((lflag & MASK_FLAGS), logicflag)); meadow->addTileIndex(tileiter.current()); } } tileiter++; } } bool TerrainBrush::intersect(BoundsDescriptor *bounds) { Tuple3f ro; Tuple3f rd; Tuple3f d; Tuple3f a; Tuple3f e; Tuple3f c; ro = ray->getOrigin(); rd = ray->getDestination(); d = (rd - ro) * 0.5f; a.set(fabsf(d.x), fabsf(d.y), fabsf(d.z)); e = bounds->getExtents(); c = ro + d - bounds->getCenterAABB(); if (fabsf(c.x) > e.x + a.x || fabsf(c.y) > e.y + a.y || fabsf(c.z) > e.z + a.z) return false; if (fabsf(d.y * c.z - d.z * c.y) > (e.y * a.z + e.z * a.y) || fabsf(d.z * c.x - d.x * c.z) > (e.z * a.x + e.x * a.z) || fabsf(d.x * c.y - d.y * c.x) > (e.x * a.y + e.y * a.x)) return false; return true; } void TerrainBrush::editWater() { if (layer != BrushLayers::WATER) return; if (!waterModel) return; Tuple3f point; float distance; Tuple4f packet; Array < DistanceObject<unsigned int> > distObjs; DistanceObject <unsigned int> object; AVLTreeTIterator <float, Tuple3f, 4> pointIter(pointAVLTree); ++pointIter; cpoint = pointIter.value(); switch (mode) { case BrushModes::VERTEX: { if (constant) waterModel->addVertex(Tuple3f(cpoint.x, cpoint.y + 0.05f, cpoint.z)); } break; case BrushModes::TRIANGLE: { if (constant) { for (unsigned int i = 0; i < waterModel->getTriangleCount(); i++) { packet = intersector.intersectTriangles(ray, waterModel->getVertices(), &waterModel->getTriangles()[i], 1); if (1 == packet.w) { point.set(packet.x, packet.y, packet.z); distance = point.getDistance(ray->getOrigin()); if (2.0f < distance) { object.set(distance, i); distObjs.append(object); } } } } if (!distObjs.isEmpty()) { OCQuickSort(distObjs, 0, distObjs.length()); waterModel->removeTriangle(distObjs(0).getObject()); } break; } } } void TerrainBrush::setRay(Ray3D* r) { ray = r; } void TerrainBrush::setPaintIndex(int index) { txcoordsIndex = index; } void TerrainBrush::setPaintLayer(int layer) { level = layer; } void TerrainBrush::enable(bool e) { enabled = e; } void TerrainBrush::enableConstant(bool enable) { constant = enable; } void TerrainBrush::setRadius(float r) { radius = r; } void TerrainBrush::update(float tick) { time = tick; } void TerrainBrush::setStrength(float s) { strength = s; } void TerrainBrush::setOpacity(float o) { opacity = o; } void TerrainBrush::setLogic(unsigned int flags) { logicflag = flags; } void TerrainBrush::setMode(int m) { mode = m; } unsigned int TerrainBrush::getMode() { return mode; } void TerrainBrush::setType(int m) { type = m; } unsigned int TerrainBrush::getType() { return type; } void TerrainBrush::setLayer(int m) { layer = m; } int TerrainBrush::getLayer() { return layer; } void TerrainBrush::enableGuides(bool enable) { showGuides = enable; } void TerrainBrush::setMeadowName(const char* name) { meadowname = name; } void TerrainBrush::setNatureTransformGroup(TransformGroup* group) { natureRoot = group; } void TerrainBrush::setCharacterTransformGroup(TransformGroup* group) { characterRoot = group; } void TerrainBrush::setCritterTransformGroup(TransformGroup* group) { critterRoot = group; } void TerrainBrush::setStructureTransformGroup(TransformGroup* group) { structureRoot = group; } void TerrainBrush::setVillageTransformGroup(TransformGroup* group) { villageRoot = group; } Tuple4f TerrainBrush::getCollisionPoint() { if (pointAVLTree.isEmpty()) return Tuple4f(0,0,0,0); return Tuple4f(cpoint.x, cpoint.y, cpoint.z, 1); } void TerrainBrush::saveCollisionPoint(bool save) { saveCollPoint = save; } void TerrainBrush::drawCollisionMark() { } void TerrainBrush::enableLogicFlag(bool enable) { if (enable) strategy = strategies(0); else strategy = strategies(1); } void TerrainBrush::setWaterModel(Water* water) { waterModel = water; } void TerrainBrush::reset() { natureRoot = 0; characterRoot = 0; structureRoot = 0; critterRoot = 0; villageRoot = 0; waterModel = 0; showGuides = false; enabled = false; constant = false; txcoordsIndex = -1; level = 0; meadowname.clear(); radius = 2.0f; strength = 0.0f; time = 0.0f; opacity = 0.0f; saveCollPoint = false; logicflag = TileLogic::FLAG_NONE | (TileTypes::UNUSED << 27); mode = BrushModes::POINTER; type = BrushTypes::NONE; layer = BrushLayers::NONE; strategy = strategies(0); } TerrainBrush::~TerrainBrush() { strategies.clear(); }
26.609375
125
0.542924
badbrainz
eded2e795fa3156c2b5aa1f2c9c45077735e4598
3,139
hpp
C++
IDemo.hpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
1
2019-06-14T08:24:17.000Z
2019-06-14T08:24:17.000Z
IDemo.hpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
null
null
null
IDemo.hpp
Sebajuste/Omeglond3D
28a3910b47490ec837a29e40e132369f957aedc7
[ "MIT" ]
null
null
null
#ifndef _DEF_IDEMO_HPP #define _DEF_IDEMO_HPP #include "src/Omgl3D.hpp" #include <SFML/Window.hpp> class IDemo { public: IDemo() : width_screen(800), height_screen(600), running(true) { } virtual ~IDemo() {} virtual void yourEvent(float elapsedtime, const sf::Event & event) {} void events(float elapsedtime) { sf::Event event; while( window.GetEvent(event) ) { if( event.Type == sf::Event::Closed ) { running = false; } if( event.Type == sf::Event::KeyPressed ) { switch(event.Key.Code) { case sf::Key::Escape: running = false; break; default: break; } } yourEvent(elapsedtime, event); } const sf::Input& Input = window.GetInput(); bool LeftKeyDown = Input.IsKeyDown(sf::Key::Left); bool RightKeyDown = Input.IsKeyDown(sf::Key::Right); bool UpKeyDown = Input.IsKeyDown(sf::Key::Up); bool DownKeyDown = Input.IsKeyDown(sf::Key::Down); bool QKeyDown = Input.IsKeyDown(sf::Key::Q); bool DKeyDown = Input.IsKeyDown(sf::Key::D); bool ZKeyDown = Input.IsKeyDown(sf::Key::Z); bool SKeyDown = Input.IsKeyDown(sf::Key::S); OMGL3D::MATH::Quaternionf rotate, rotate_x, rotate_y, rotate_z; OMGL3D::MATH::Vector3f vector; if( LeftKeyDown ) { rotate_x = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 0, 1, -20*elapsedtime); } if( RightKeyDown ) { rotate_x = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 0, 1, 20*elapsedtime); } if( UpKeyDown ) { rotate_z = OMGL3D::MATH::Quaternionf::CreateQuaternion(1, 0, 0, -20*elapsedtime); } if( DownKeyDown ) { rotate_z = OMGL3D::MATH::Quaternionf::CreateQuaternion(1, 0, 0, 20*elapsedtime); } if( QKeyDown ) { rotate_y = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 1, 0, -20*elapsedtime); } if( DKeyDown ) { rotate_y = OMGL3D::MATH::Quaternionf::CreateQuaternion(0, 1, 0, 20*elapsedtime); } if( ZKeyDown ) { vector.z = -10*elapsedtime; } if( SKeyDown ) { vector.z = 10*elapsedtime; } rotate = rotate_x * rotate_y * rotate_z; //position = rotate.getMatrix4(); position *= rotate.GetMatrix4(); position *= vector; } virtual void init()=0; virtual void run()=0; void start() { init(); sf::Clock clock; while( running ) { elapsedtime = clock.GetElapsedTime(); clock.Reset(); events(elapsedtime); run(); } } protected: unsigned int width_screen, height_screen; bool running; float elapsedtime; sf::Window window; OMGL3D::MATH::Matrix4f position; }; #endif
22.582734
93
0.521822
Sebajuste
eded3f907772be78a364c272f687c920d80a74d5
3,765
cpp
C++
src/TVShader.cpp
jcmoyer/HALT
8f31eb1943b43ca0d2ab4065a2c624b67a80124f
[ "Unlicense", "MIT" ]
null
null
null
src/TVShader.cpp
jcmoyer/HALT
8f31eb1943b43ca0d2ab4065a2c624b67a80124f
[ "Unlicense", "MIT" ]
1
2015-06-29T21:53:55.000Z
2015-06-29T21:53:55.000Z
src/TVShader.cpp
jcmoyer/HALT
8f31eb1943b43ca0d2ab4065a2c624b67a80124f
[ "Unlicense", "MIT" ]
null
null
null
// ============================================================================ // Copyright (c) 2011-2012 J.C. Moyer // // 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 "TVShader.h" #include "TerminalRenderer.h" #include "TProgram.h" #include <GL/glew.h> namespace halt { const char* TVGLSLShaderSource = "#version 120 \n" "uniform mat4 tvs_Projection; \n" " \n" "attribute vec2 tvs_TexCoord; \n" "attribute vec4 tvs_Vertex; \n" "attribute vec4 tvs_Color; \n" " \n" "varying vec2 tfs_TexCoord; \n" "varying vec4 tfs_Color; \n" " \n" "void main() { \n" " gl_Position = tvs_Projection * tvs_Vertex; \n" " tfs_TexCoord = tvs_TexCoord; \n" " tfs_Color = tvs_Color; \n" "} \n"; const char* TVS_PROJECTION_MAT = "tvs_Projection"; const char* VERTEX_ATTRIBUTE_NAME = "tvs_Vertex"; const char* TEXCOORD_ATTRIBUTE_NAME = "tvs_TexCoord"; const char* COLOR_ATTRIBUTE_NAME = "tvs_Color"; TVShader::TVShader(TProgram* owner) { handle = glCreateShader(GL_VERTEX_SHADER); glShaderSource(handle, 1, &TVGLSLShaderSource, 0); glCompileShader(handle); } TVShader::~TVShader() { if (handle) glDeleteShader(handle); } void TVShader::Enable(bool state, unsigned int vertex_attrib, unsigned int tex_coord_atrrib, unsigned int color_attrib) { if (state) { glEnableVertexAttribArray(vertex_attrib); glVertexAttribPointer(vertex_attrib, 2, GL_UNSIGNED_SHORT, 0, sizeof(TerminalVertex), (void*)0); glEnableVertexAttribArray(tex_coord_atrrib); glVertexAttribPointer(tex_coord_atrrib, 2, GL_FLOAT, 0, sizeof(TerminalVertex), (void*)4); glEnableVertexAttribArray(color_attrib); glVertexAttribPointer(color_attrib, 4, GL_UNSIGNED_BYTE, 1, sizeof(TerminalVertex), (void*)12); } else { glDisableVertexAttribArray(vertex_attrib); glDisableVertexAttribArray(tex_coord_atrrib); glDisableVertexAttribArray(color_attrib); } } }
48.896104
122
0.562019
jcmoyer
edef4a097eb4ce91d4567df08e1e1433603dd67d
32,877
cpp
C++
T3000/T3ModulesOutputDlg.cpp
daven-que/T3000_Building_Automation_System
cc56967e9bf849ebc5ec47950b74e8dc765f720c
[ "MIT" ]
null
null
null
T3000/T3ModulesOutputDlg.cpp
daven-que/T3000_Building_Automation_System
cc56967e9bf849ebc5ec47950b74e8dc765f720c
[ "MIT" ]
null
null
null
T3000/T3ModulesOutputDlg.cpp
daven-que/T3000_Building_Automation_System
cc56967e9bf849ebc5ec47950b74e8dc765f720c
[ "MIT" ]
null
null
null
// T3ModulesOutputDlg.cpp : implementation file // #include "stdafx.h" #include "T3000.h" #include "T3ModulesOutputDlg.h" #include "afxdialogex.h" #include "global_function.h" // CT3ModulesOutputDlg dialog DWORD WINAPI _ReadMultiRegisters_T3_Output(LPVOID pParam) { CT3ModulesOutputDlg* pFrame=(CT3ModulesOutputDlg*)(pParam); CString g_strT3000LogString; int heatbeat = 0; while(pFrame->IsWindowVisible ()) { if (!is_connect()) { Sleep(1000); continue; } if (pFrame->m_isstop) { // heatbeat ++; Sleep(1000); if (heatbeat >10) { pFrame->m_isstop = FALSE; heatbeat =0; } continue; } for(int i=0; i<4; i++) { int multy_ret = 0; if (pFrame->m_isstop) { break; } multy_ret = Read_Multi(g_tstat_id,&product_register_value[i*100],i*100,100); Sleep(100); if(multy_ret<0) break; } PostMessage(g_hwnd_now,WM_REFRESH_BAC_INPUT_LIST,0,0); } return 0; return 0; } IMPLEMENT_DYNAMIC(CT3ModulesOutputDlg, CFormView) CT3ModulesOutputDlg::CT3ModulesOutputDlg() : CFormView(CT3ModulesOutputDlg::IDD) { hFirstThread = NULL; m_isstop = FALSE; } CT3ModulesOutputDlg::~CT3ModulesOutputDlg() { if(hFirstThread != NULL) TerminateThread(hFirstThread, 0); } void CT3ModulesOutputDlg::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_T3OUTPUTS, m_outputlist); } #ifdef _DEBUG void CT3ModulesOutputDlg::AssertValid() const { CFormView::AssertValid(); } #ifndef _WIN32_WCE void CT3ModulesOutputDlg::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif #endif //_DEBUG BEGIN_MESSAGE_MAP(CT3ModulesOutputDlg, CFormView) ON_MESSAGE(WM_REFRESH_BAC_INPUT_LIST,Fresh_Input_List) ON_MESSAGE(WM_LIST_ITEM_CHANGED,Change_Input_Item) ON_NOTIFY(NM_CLICK, IDC_LIST_T3OUTPUTS, &CT3ModulesOutputDlg::OnNMClickList_output) ON_NOTIFY(NM_DBLCLK, IDC_LIST_T3OUTPUTS, &CT3ModulesOutputDlg::OnNMDblclkListT3outputs) END_MESSAGE_MAP() // CT3ModulesOutputDlg message handlers void CT3ModulesOutputDlg::Fresh() { CString strTemp; g_hwnd_now = this->m_hWnd; m_sn = m_sn=product_register_value[0]+product_register_value[1]*256 +product_register_value[2]*256*256+product_register_value[3]*256*256*256; m_outputlist.ShowWindow(SW_HIDE); m_outputlist.DeleteAllItems(); while(m_outputlist.DeleteColumn(0)); if (product_register_value[7] == PM_T34AO) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(1, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(2, _T("Value"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); for(int i=1; i<9; i++) { strTemp.Format(_T("Digit Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); //strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } for(int i=9; i<13; i++) { strTemp.Format(_T("Analog Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); // strTemp.Format(_T("%d"),product_register_value[108+(i-8)-1]); if (product_register_value[108+(i-8)-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } for(int i = 1; i<13; i++) { m_outputlist.SetItemText(i-1,1,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,2,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,2,L"On"); } else { if (i<9) { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } else { strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,2,strTemp); } } } else if (product_register_value[7] == PM_T3IOA) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[8]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } for(int i=1; i<9; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); // strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,1,strTemp); m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T38AI8AO6DO) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString); bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } for(int i=1; i<15; i++) { if (i<9) { strTemp= Get_Table_Name(m_sn,_T("Analog_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { // if (product_register_value[100+i-1] == 0) // { // strTemp = _T("Off"); // } // else // { // strTemp = _T("On"); // } strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,1,strTemp); } else { strTemp= Get_Table_Name(m_sn,_T("Digital_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } m_outputlist.SetItemText(i-1,1,strTemp); } m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); } } else if (product_register_value[7] == PM_T38I13O) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(1, _T("Output Value"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(2, _T("Light Switch"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(3, _T("Auto/Manual"), 90, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(4, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); for(int i=1; i<14; i++) { strTemp = Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i-1,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[13]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue2(product_register_value[117]); for (int i=8; i<13; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } CString CstresultDO; for(int i = 1; i<=13; i++) { // CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { CstresultDO = _T("Off"); } else { CstresultDO = _T("On"); } m_outputlist.SetItemText(i-1,1,CstresultDO); if (product_register_value[216+i-1]>0) { CstresultDO=Get_Table_Name(m_sn,_T("Input"),product_register_value[216+i-1]); } else { CstresultDO=_T("UNUSED"); } m_outputlist.SetItemText(i-1,2,CstresultDO); if (((product_register_value[215]>>(i-1))&0x01)==1) { CstresultDO=_T("Manual"); } else { CstresultDO=_T("Auto"); } m_outputlist.SetItemText(i-1,3,CstresultDO); m_outputlist.SetItemText(i-1,4,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T36CT) { m_outputlist.ModifyStyle(0,LVS_SINGLESEL|LVS_REPORT|LVS_SHOWSELALWAYS); m_outputlist.SetExtendedStyle(m_outputlist.GetExtendedStyle() |LVS_EX_GRIDLINES&(~LVS_EX_FULLROWSELECT)); m_outputlist.InsertColumn(0, _T("Label"), 180, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByDigit); m_outputlist.InsertColumn(2, _T("Switch Status"), 100, ListCtrlEx::Normal, LVCFMT_CENTER, ListCtrlEx::SortByString); m_outputlist.InsertColumn(1, _T("Value"), 90, ListCtrlEx::EditBox, LVCFMT_CENTER, ListCtrlEx::SortByString); for(int i=1; i<6; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); } CString CstresultDO; int b0,b1,b; for(int i = 1; i<=5; i++) { CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); m_outputlist.SetItemText(i-1,2,CstresultDO); b0=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+1); b1=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+2); b=b1*2+b0; if (i==5) { b0=Get_Bit_FromRegister(product_register_value[124],1); b1=Get_Bit_FromRegister(product_register_value[124],2); b=b1*2+b0; } if (b==0) { CstresultDO=_T("OFF"); } else if (b==1) { CstresultDO=_T("ON"); } else if (b==2) { CstresultDO=_T("AUTO"); } else { CstresultDO=_T(""); } m_outputlist.SetItemText(i-1,1,CstresultDO); } } m_outputlist.ShowWindow(SW_SHOW); if(hFirstThread != NULL) TerminateThread(hFirstThread, 0); hFirstThread=NULL; if (!hFirstThread) { hFirstThread = CreateThread(NULL,NULL,_ReadMultiRegisters_T3_Output,this,NULL,0); } } LRESULT CT3ModulesOutputDlg::Fresh_Input_List(WPARAM wParam,LPARAM lParam) { m_sn=product_register_value[0]+product_register_value[1]*256+product_register_value[2]*256*256+product_register_value[3]*256*256*256; CString strTemp; int fresh_type = (int)wParam; int fresh_row =(int) lParam; if (fresh_type == 0) { m_outputlist.DeleteAllItems(); if (product_register_value[7] == PM_T34AO) { for(int i=1; i<9; i++) { strTemp.Format(_T("Digit Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); // strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } for(int i=9; i<13; i++) { strTemp.Format(_T("Analog Output%d"),i); m_outputlist.InsertItem(i-1,strTemp); strTemp.Format(_T("%d"),product_register_value[108+(i-8)-1]); if (product_register_value[108+(i-8)-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,2,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } for(int i = 1; i<13; i++) { m_outputlist.SetItemText(i-1,1,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,2,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,2,L"On"); } else { if (i<9) { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } else { strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,2,strTemp); } } } else if (product_register_value[7] == PM_T3IOA) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[8]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } for(int i=1; i<9; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); // strTemp.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,1,strTemp); m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T38I13O) { for(int i=1; i<14; i++) { strTemp = Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i-1,strTemp); } bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[13]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue2(product_register_value[117]); for (int i=8; i<13; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } CString CstresultDO; for(int i = 1; i<=13; i++) { //CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } m_outputlist.SetItemText(i-1,1,strTemp); if (product_register_value[216+i-1]>0) { CstresultDO=Get_Table_Name(m_sn,_T("Input"),product_register_value[216+i-1]); } else { CstresultDO=_T("UNUSED"); } m_outputlist.SetItemText(i-1,2,CstresultDO); if (((product_register_value[215]>>(i-1))&0x01)==1) { CstresultDO=_T("Manual"); } else { CstresultDO=_T("Auto"); } m_outputlist.SetItemText(i-1,3,CstresultDO); m_outputlist.SetItemText(i-1,4,STRING_SWITCH_STATUS[SwitchValue[i-1]]); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } } } else if (product_register_value[7] == PM_T36CT) { for(int i=1; i<6; i++) { strTemp= Get_Table_Name(m_sn,_T("Output"),i); m_outputlist.InsertItem(i,strTemp); } CString CstresultDO; int b0,b1,b; for(int i = 1; i<=5; i++) { CstresultDO.Format(_T("%d"),product_register_value[100+i-1]); m_outputlist.SetItemText(i-1,2,CstresultDO); b0=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+1); b1=Get_Bit_FromRegister(product_register_value[124],2*(i-1)+2); b=b1*2+b0; if (i==5) { b0=Get_Bit_FromRegister(product_register_value[124],1); b1=Get_Bit_FromRegister(product_register_value[124],2); b=b1*2+b0; } if (b==0) { CstresultDO=_T("OFF"); } else if (b==1) { CstresultDO=_T("ON"); } else if (b==2) { CstresultDO=_T("AUTO"); } else { CstresultDO=_T(""); } m_outputlist.SetItemText(i-1,1,CstresultDO); } } else if (product_register_value[7] == PM_T38AI8AO6DO) { bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } for(int i=1; i<15; i++) { if (i<9) { strTemp= Get_Table_Name(m_sn,_T("Analog_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { // if (product_register_value[100+i-1] == 0) // { // strTemp = _T("Off"); // } // else // { // strTemp = _T("On"); // } strTemp.Format(_T("%d"),product_register_value[100+i-1]); } m_outputlist.SetItemText(i-1,1,strTemp); } else { strTemp= Get_Table_Name(m_sn,_T("Digital_Output"),i); m_outputlist.InsertItem(i,strTemp); if (SwitchValue[i-1] == 0) { m_outputlist.SetItemText(i-1,1,L"Off"); } else if (SwitchValue[i-1] == 1) { m_outputlist.SetItemText(i-1,1,L"On"); } else { if (product_register_value[100+i-1] == 0) { strTemp = _T("Off"); } else { strTemp = _T("On"); } } m_outputlist.SetItemText(i-1,1,strTemp); } m_outputlist.SetItemText(i-1,2,STRING_SWITCH_STATUS[SwitchValue[i-1]]); } } } return 0; } LRESULT CT3ModulesOutputDlg::Change_Input_Item(WPARAM wParam,LPARAM lParam) { int lRow = (int)wParam; int lCol = (int)lParam; CString strText = m_outputlist.GetItemText (lRow,lCol); if (product_register_value[7] == PM_T34AO) { if (lCol == 2) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } } } else if (product_register_value[7] == PM_T3IOA) { } else if (product_register_value[7] == PM_T38I13O) { } else if (product_register_value[7] == PM_T36CT) { } else if (product_register_value[7] == PM_T38AI8AO6DO) { if (lCol == 1) { bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } if (SwitchValue[lRow] ==2) { int OutputValue = _wtoi (strText); if (OutputValue!=product_register_value[100+lRow]) { if (lRow<8) { int ret = write_one (g_tstat_id,100+lRow,OutputValue,1); if (ret>0) { product_register_value[100+lRow] = OutputValue; } } } PostMessage (WM_REFRESH_BAC_INPUT_LIST,0,0); } else { m_outputlist.Set_Edit (false); return 0; } } } return 0; } /* @1:Different Product responce to the different functionality @2: */ void CT3ModulesOutputDlg::OnNMClickList_output(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); CString temp_cstring; long lRow,lCol; m_outputlist.Set_Edit(true); DWORD dwPos=GetMessagePos();//Get which line is click by user.Set the check box, when user enter Insert it will jump to program dialog CPoint point( GET_X_LPARAM(dwPos), GET_Y_LPARAM(dwPos)); m_outputlist.ScreenToClient(&point); LVHITTESTINFO lvinfo; lvinfo.pt=point; lvinfo.flags=LVHT_ABOVE; int nItem=m_outputlist.SubItemHitTest(&lvinfo); BOOL Is_Range = FALSE; int Range_Address = -1; int Value_Address = -1; int Value_Length = 0; lRow = lvinfo.iItem; lCol = lvinfo.iSubItem; m_isstop = TRUE; if(lRow>m_outputlist.GetItemCount()) //如果点击区超过最大行号,则点击是无效的 { return; } if(lRow<0) { return; } if (product_register_value[7] == PM_T34AO) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[12]; for (int i=0; i<4; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue1(product_register_value[117]); for (int i=4; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*(i-4)]+BitSwitchValue1[2*(i-4)+1]*2; } bitset<16> BitSwitchValue2(product_register_value[118]); for (int i=8; i<12; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } if (lCol == 2) { // m_isstop =TRUE; m_outputlist.Set_Edit (false); if (SwitchValue[lRow] == 2) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } else if (product_register_value[7] == PM_T3IOA) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[8]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } if (lCol == 1) { if (SwitchValue[lRow] == 2) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } else if (product_register_value[7] == PM_T38AI8AO6DO) { bitset<16> BitSwitchValue1(product_register_value[114]); bitset<16> BitSwitchValue2(product_register_value[115]); int SwitchValue[16]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue1[2*i]+BitSwitchValue1[2*i+1]*2; SwitchValue[8+i]=BitSwitchValue2[2*i]+BitSwitchValue2[2*i+1]*2; } if (lCol == 1) { if (SwitchValue[lRow] == 2) { if (lRow>7) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } } else if (product_register_value[7] == PM_T38I13O) { bitset<16> BitSwitchValue(product_register_value[116]); int SwitchValue[13]; for (int i=0; i<8; i++) { SwitchValue[i]=BitSwitchValue[2*i]+BitSwitchValue[2*i+1]*2; } bitset<16> BitSwitchValue2(product_register_value[117]); for (int i=8; i<13; i++) { SwitchValue[i]=BitSwitchValue2[2*(i-8)]+BitSwitchValue2[2*(i-8)+1]*2; } if (lCol == 1) { if (SwitchValue[lRow] == 2) { if (product_register_value[100+lRow] == 0) { int ret = write_one (g_tstat_id,100+lRow,1,1); if (ret > 0) { product_register_value[100+lRow] = 1; m_outputlist.SetItemText (lRow,lCol,L"On"); } } else { int ret = write_one (g_tstat_id,100+lRow,0,1); if (ret > 0) { product_register_value[100+lRow] = 0; m_outputlist.SetItemText (lRow,lCol,L"Off"); } } } } } else if (product_register_value[7] == PM_T36CT) { } } void CT3ModulesOutputDlg::OnNMDblclkListT3outputs(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); *pResult = 0; } BOOL CT3ModulesOutputDlg::PreTranslateMessage(MSG* pMsg) { if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN) { CRect list_rect,win_rect; m_outputlist.GetWindowRect(list_rect); ScreenToClient(&list_rect); ::GetWindowRect(this->m_hWnd,win_rect); m_outputlist.Set_My_WindowRect(win_rect); m_outputlist.Set_My_ListRect(list_rect); m_outputlist.Get_clicked_mouse_position(); return TRUE; } return CFormView::PreTranslateMessage(pMsg); }
29.068966
138
0.52082
daven-que
edf0d3adec736d669ec7476f4a15d48edd902b8d
693
hpp
C++
lib/libcpp/FadalightMesh/FadalightMesh/patchinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
lib/libcpp/FadalightMesh/FadalightMesh/patchinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
1
2019-01-31T10:59:11.000Z
2019-01-31T10:59:11.000Z
lib/libcpp/FadalightMesh/FadalightMesh/patchinfo.hpp
beckerrh/simfemsrc
d857eb6f6f8627412d4f9d89a871834c756537db
[ "MIT" ]
null
null
null
#ifndef __FadalightMesh_PatchInfo_h #define __FadalightMesh_PatchInfo_h #include "Alat/vector.hpp" #include "Alat/armadillo.hpp" /*--------------------------------------------------------------------------*/ namespace FadalightMesh { class PatchInfo { public: ~PatchInfo(); PatchInfo(); PatchInfo( const PatchInfo& patchinfo); PatchInfo& operator=( const PatchInfo& patchinfo); std::string getClassName() const; PatchInfo* clone() const; alat::Vector<alat::armaivec> cells, edgesinner, edgesouter, nodes; arma::field<arma::mat> sidecoeffs; arma::field<arma::imat> sideindices; }; } /*--------------------------------------------------------------------------*/ #endif
23.896552
78
0.572872
beckerrh
edf30d98197266a8a41a4d0ff63bcc4a00f5a898
30,358
hpp
C++
Primitives/General/Mat4x4.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
2
2021-06-09T00:38:46.000Z
2021-09-04T21:55:33.000Z
Primitives/General/Mat4x4.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
null
null
null
Primitives/General/Mat4x4.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
1
2021-08-30T00:46:12.000Z
2021-08-30T00:46:12.000Z
// // Mat4x4.h // DataStructures // // Created by James Landess on 11/11/16. // Copyright (c) 2016 James Landess. All rights reserved. // #ifndef DataStructures_Mat4x4_h #define DataStructures_Mat4x4_h #include "StaticArray.hpp" #include "Vec4.hpp" #include "Mat2x4.hpp" #include "Mat3x4.hpp" #include "Mat4x3.hpp" #include "TypeTraits/StaticallySized.h" namespace LD { namespace Detail { template<typename T> class tMat4x4 { private: tVec4<T> Rows[4]; public: inline tMat4x4(); inline tMat4x4(const typename TypeAid<T, 16>::CoreType & a); inline tMat4x4(const typename TypeAid<T, 16>::CoreType & a0, const typename TypeAid<T, 16>::CoreType & b0, const typename TypeAid<T, 16>::CoreType & c0,const typename TypeAid<T, 16>::CoreType & d0, const typename TypeAid<T, 16>::CoreType & a1, const typename TypeAid<T, 16>::CoreType & b1, const typename TypeAid<T, 16>::CoreType & c1,const typename TypeAid<T, 16>::CoreType & d1, const typename TypeAid<T, 16>::CoreType & a2, const typename TypeAid<T, 16>::CoreType & b2, const typename TypeAid<T, 16>::CoreType & c2,const typename TypeAid<T, 16>::CoreType & d2, const typename TypeAid<T, 16>::CoreType & a3, const typename TypeAid<T, 16>::CoreType & b3, const typename TypeAid<T, 16>::CoreType & c3,const typename TypeAid<T, 16>::CoreType & d3); inline tMat4x4(const tVec4<T> &a, const tVec4<T> & b, const tVec4<T> & c, const tVec4<T> & d); inline tMat4x4(const tMat2x2<T> & a); inline tMat4x4(const tMat3x3<T> & a); inline tVec4<T> & operator [] (const PDP::UInteger & index); inline const tVec4<T> & operator [] (const PDP::UInteger & index) const; inline tMat4x4 & operator = (const typename TypeAid<T, 16>::CoreType & a); inline tMat4x4 & operator = (const tMat2x2<T> & object); inline tMat4x4 & operator = (const tMat3x3<T> & object); }; template<typename T> tMat4x4<T>::tMat4x4() { this->Rows[0] = this->Rows[1] = this->Rows[2] = this->Rows[3] = 0; } template<typename T> tMat4x4<T>::tMat4x4(const typename TypeAid<T, 16>::CoreType & a) { this->Rows[0] = this->Rows[1] = this->Rows[2] = this->Rows[3] = a; } template<typename T> tMat4x4<T>::tMat4x4(const typename TypeAid<T, 16>::CoreType & a0, const typename TypeAid<T, 16>::CoreType & b0, const typename TypeAid<T, 16>::CoreType & c0,const typename TypeAid<T, 16>::CoreType & d0, const typename TypeAid<T, 16>::CoreType & a1, const typename TypeAid<T, 16>::CoreType & b1, const typename TypeAid<T, 16>::CoreType & c1,const typename TypeAid<T, 16>::CoreType & d1, const typename TypeAid<T, 16>::CoreType & a2, const typename TypeAid<T, 16>::CoreType & b2, const typename TypeAid<T, 16>::CoreType & c2,const typename TypeAid<T, 16>::CoreType & d2, const typename TypeAid<T, 16>::CoreType & a3, const typename TypeAid<T, 16>::CoreType & b3, const typename TypeAid<T, 16>::CoreType & c3,const typename TypeAid<T, 16>::CoreType & d3) { this->Rows[0] = tVec4<T>(a0,b0,c0,d0); this->Rows[1] = tVec4<T>(a1,b1,c1,d1); this->Rows[2] = tVec4<T>(a2,b2,c2,d2); this->Rows[3] = tVec4<T>(a3,b3,c3,d3); } template<typename T> tMat4x4<T>::tMat4x4(const tVec4<T> &a, const tVec4<T> & b, const tVec4<T> & c, const tVec4<T> & d) { this->Rows[0] = a; this->Rows[1] = b; this->Rows[2] = c; this->Rows[3] = d; } template<typename T> tVec4<T> & tMat4x4<T>::operator[](const PDP::UInteger &index) { return this->Rows[index]; } template<typename T> const tVec4<T> & tMat4x4<T>::operator[](const PDP::UInteger &index) const { return this->Rows[index]; } template<typename T> tMat4x4<T> & tMat4x4<T>::operator=(const typename TypeAid<T, 16>::CoreType &a) { this->Rows[0] = tVec4<T>(a,0,0,0); this->Rows[1] = tVec4<T>(0,a,0,0); this->Rows[2] = tVec4<T>(0,0,a,0); this->Rows[3] = tVec4<T>(0,0,0,a); return (*this); } template <typename U, typename T> inline tMat4x4<T>& operator+= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] += s; a[1] += s; a[2] += s; a[3] += s; return a; } template <typename U, typename T> inline tMat4x4<T>& operator+= (tMat4x4<U> & a, const tMat4x4<T> & b ) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; a[3] += b[3]; return a; } template <typename U, typename T> inline tMat4x4<T> & operator-= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] -= s; a[1] -= s; a[2] -= s; a[3] -= s; return a; } template <typename U, typename T> inline tMat4x4<T> & operator-= (tMat4x4<U> & a, const tMat4x4<T> & m) { a[0] -= m[0]; a[1] -= m[1]; a[2] -= m[2]; a[3] -= m[3]; return a; } template <typename U, typename T> inline tMat4x4<T> & operator*= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] *= s; a[1] *= s; a[2] *= s; a[3] *= s; return a; } template <typename U, typename T> inline tMat4x4<T> & operator*= (tMat4x4<U> & a, const tMat4x4<T> & m) { return (a = a * m); } template <typename U, typename T> inline tMat4x4<T> & operator /= (tMat4x4<T> & a,const typename TypeAid<U, 16>::CoreType &s) { a[0] /= s; a[1] /= s; a[2] /= s; a[3] /= s; return a; } template <typename T> struct compute_inversetMat4x4 { inline static tMat4x4<T> call( const tMat4x4<T> & m) { const T & Coef00 = m[2][2] * m[3][3] - m[3][2] * m[2][3]; const T & Coef02 = m[1][2] * m[3][3] - m[3][2] * m[1][3]; const T & Coef03 = m[1][2] * m[2][3] - m[2][2] * m[1][3]; const T & Coef04 = m[2][1] * m[3][3] - m[3][1] * m[2][3]; const T & Coef06 = m[1][1] * m[3][3] - m[3][1] * m[1][3]; const T & Coef07 = m[1][1] * m[2][3] - m[2][1] * m[1][3]; const T & Coef08 = m[2][1] * m[3][2] - m[3][1] * m[2][2]; const T & Coef10 = m[1][1] * m[3][2] - m[3][1] * m[1][2]; const T & Coef11 = m[1][1] * m[2][2] - m[2][1] * m[1][2]; const T & Coef12 = m[2][0] * m[3][3] - m[3][0] * m[2][3]; const T & Coef14 = m[1][0] * m[3][3] - m[3][0] * m[1][3]; const T & Coef15 = m[1][0] * m[2][3] - m[2][0] * m[1][3]; const T & Coef16 = m[2][0] * m[3][2] - m[3][0] * m[2][2]; const T & Coef18 = m[1][0] * m[3][2] - m[3][0] * m[1][2]; const T & Coef19 = m[1][0] * m[2][2] - m[2][0] * m[1][2]; const T & Coef20 = m[2][0] * m[3][1] - m[3][0] * m[2][1]; const T & Coef22 = m[1][0] * m[3][1] - m[3][0] * m[1][1]; const T & Coef23 = m[1][0] * m[2][1] - m[2][0] * m[1][1]; const tVec4<T> Fac0(Coef00, Coef00, Coef02, Coef03); const tVec4<T> Fac1(Coef04, Coef04, Coef06, Coef07); const tVec4<T> Fac2(Coef08, Coef08, Coef10, Coef11); const tVec4<T> Fac3(Coef12, Coef12, Coef14, Coef15); const tVec4<T> Fac4(Coef16, Coef16, Coef18, Coef19); const tVec4<T> Fac5(Coef20, Coef20, Coef22, Coef23); const tVec4<T> Vec0(m[1][0], m[0][0], m[0][0], m[0][0]); const tVec4<T> Vec1(m[1][1], m[0][1], m[0][1], m[0][1]); const tVec4<T> Vec2(m[1][2], m[0][2], m[0][2], m[0][2]); const tVec4<T> Vec3(m[1][3], m[0][3], m[0][3], m[0][3]); const tVec4<T> Inv0(Vec1 * Fac0 - Vec2 * Fac1 + Vec3 * Fac2); const tVec4<T> Inv1(Vec0 * Fac0 - Vec2 * Fac3 + Vec3 * Fac4); const tVec4<T> Inv2(Vec0 * Fac1 - Vec1 * Fac3 + Vec3 * Fac5); const tVec4<T> Inv3(Vec0 * Fac2 - Vec1 * Fac4 + Vec2 * Fac5); const tVec4<T> SignA(+1, -1, +1, -1); const tVec4<T> SignB(-1, +1, -1, +1); const tMat4x4<T> Inverse(Inv0 * SignA, Inv1 * SignB, Inv2 * SignA, Inv3 * SignB); const tVec4<T> Row0(Inverse[0][0], Inverse[1][0], Inverse[2][0], Inverse[3][0]); const tVec4<T> Dot0(m[0] * Row0); const T Dot1 = (Dot0.x + Dot0.y) + (Dot0.z + Dot0.w); const T OneOverDeterminant = static_cast<T>(1) / Dot1; return Inverse * OneOverDeterminant; } }; template <typename U, typename T> inline tMat4x4<T> & operator/= (tMat4x4<U> & a, const tMat4x4<T> & m) { return (a = a* compute_inversetMat4x4<T>::call(m)); } template <typename T> inline tMat4x4<T> & operator++ (tMat4x4<T> & m) { m[0]; m[1]; m[2]; m[3]; return m; } template <typename T> inline tMat4x4<T> & operator-- (tMat4x4<T> & m) { m[0]; m[1]; m[2]; m[3]; return m; } template <typename T> inline tMat4x4<T> & operator++(tMat4x4<T> & m,int) { ++m; return m; } template <typename T> inline tMat4x4<T> & operator--(tMat4x4<T> & m, int) { --m; return m; } // Binary operators template <typename T, typename U> inline tMat4x4<T> operator+ ( tMat4x4<T> const & m, const typename TypeAid<U, 16>::CoreType &s ) { return tMat4x4<T>( m[0] + s, m[1] + s, m[2] + s, m[3] + s); } template <typename T, typename U> inline tMat4x4<T> operator+ ( const typename TypeAid<T, 16>::CoreType &s, tMat4x4<U> const & m ) { return tMat4x4<T>( m[0] + s, m[1] + s, m[2] + s, m[3] + s); } template <typename T, typename U> inline tMat4x4<T> operator+ ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { return tMat4x4<T>( m1[0] + m2[0], m1[1] + m2[1], m1[2] + m2[2], m1[3] + m2[3]); } template <typename T, typename U> inline tMat4x4<T> operator- ( tMat4x4<T> const & m, const typename TypeAid<U, 16>::CoreType &s ) { return tMat4x4<T>( m[0] - s, m[1] - s, m[2] - s, m[3] - s); } template <typename T, typename U> inline tMat4x4<T> operator- ( const typename TypeAid<T, 16>::CoreType &s, tMat4x4<U> const & m ) { return tMat4x4<T>( s - m[0], s - m[1], s - m[2], s - m[3]); } template <typename T> inline tMat4x4<T> operator- ( tMat4x4<T> const &m1, tMat4x4<T> const &m2 ) { return tMat4x4<T>( m1[0] - m2[0], m1[1] - m2[1], m1[2] - m2[2], m1[3] - m2[3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tMat4x4<T> const & m, const typename TypeAid<U, 16>::CoreType &s ) { return tMat4x4<T>( m[0] * s, m[1] * s, m[2] * s, m[3] * s); } template <typename T, typename U> inline tMat4x4<T> operator* ( const typename TypeAid<U, 16>::CoreType &s, tMat4x4<T> const & m ) { return tMat4x4<T>( m[0] * s, m[1] * s, m[2] * s, m[3] * s); } template <typename T, typename U> inline tVec4<T> operator* ( tMat4x4<T> const & m, tVec4<U> const & v ) { tVec4<T> const Mov0(v[0]); tVec4<T> const Mov1(v[1]); tVec4<T> const Mul0 = m[0] * Mov0; tVec4<T> const Mul1 = m[1] * Mov1; tVec4<T> const Add0 = Mul0 + Mul1; tVec4<T> const Mov2(v[2]); tVec4<T> const Mov3(v[3]); tVec4<T> const Mul2 = m[2] * Mov2; tVec4<T> const Mul3 = m[3] * Mov3; tVec4<T> const Add1 = Mul2 + Mul3; tVec4<T> const Add2 = Add0 + Add1; return Add2; } template <typename T, typename U> inline tVec4<T> operator* ( tVec4<T> const & v, tMat4x4<T> const & m ) { return tMat4x4<T>( m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2] + m[0][3] * v[3], m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2] + m[1][3] * v[3], m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2] + m[2][3] * v[3], m[3][0] * v[0] + m[3][1] * v[1] + m[3][2] * v[2] + m[3][3] * v[3]); } template <typename T, typename U> inline tMat2x4<T> operator* ( tMat4x4<T> const & m1, tMat2x4<U> const & m2 ) { return tMat2x4<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3]); } template <typename T, typename U> inline tMat4x4<T> operator*(tMat4x4<T> const & m1, tMat4x4<U> const & m2) { tMat4x4<T> t; // write to temp for (PDP::UShort i=0; i < 4; i++) { for (PDP::UShort j=0; j < 4; j++) { t[i][j] = m1[i][0]*m2[0][j] + m1[i][1]*m2[1][j] + m1[i][2]*m2[2][j] + m1[i][3]*m2[3][j]; } } return t; } template <typename T, typename U> inline tMat3x4<T> operator* ( tMat4x4<T> const & m1, tMat3x4<U> const & m2 ) { return tMat3x4<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][3] * m2[0][0] + m1[1][3] * m2[0][1] + m1[2][3] * m2[0][2] + m1[3][3] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], m1[0][3] * m2[1][0] + m1[1][3] * m2[1][1] + m1[2][3] * m2[1][2] + m1[3][3] * m2[1][3], m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3], m1[0][3] * m2[2][0] + m1[1][3] * m2[2][1] + m1[2][3] * m2[2][2] + m1[3][3] * m2[2][3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tVec4<T> const & m1, tMat4x4<U> const & m2 ) { tMat4x4<T> const SrcA0 = m1[0]; tVec4<T> const SrcA1 = m1[1]; tVec4<T> const SrcA2 = m1[2]; tVec4<T> const SrcA3 = m1[3]; tVec4<T> const SrcB0 = m2[0]; tVec4<T> const SrcB1 = m2[1]; tVec4<T> const SrcB2 = m2[2]; tVec4<T> const SrcB3 = m2[3]; tVec4<T> Result(0); Result[0] = SrcA0 * SrcB0[0] + SrcA1 * SrcB0[1] + SrcA2 * SrcB0[2] + SrcA3 * SrcB0[3]; Result[1] = SrcA0 * SrcB1[0] + SrcA1 * SrcB1[1] + SrcA2 * SrcB1[2] + SrcA3 * SrcB1[3]; Result[2] = SrcA0 * SrcB2[0] + SrcA1 * SrcB2[1] + SrcA2 * SrcB2[2] + SrcA3 * SrcB2[3]; Result[3] = SrcA0 * SrcB3[0] + SrcA1 * SrcB3[1] + SrcA2 * SrcB3[2] + SrcA3 * SrcB3[3]; return Result; } template <typename T, typename U> inline tMat4x4<T> operator/ ( tMat4x4<T> const & m, typename TypeAid<U, 16>::CoreType const & s ) { return tMat4x4<T>( m[0] / s, m[1] / s, m[2] / s, m[3] / s); } template <typename T, typename U> inline tMat4x4<T> operator/ ( typename TypeAid<T, 16>::CoreType const & s, tMat4x4<U> const & m ) { return tMat4x4<T>( s / m[0], s / m[1], s / m[2], s / m[3]); } template <typename T, typename U> inline tVec4<T> operator/ ( tMat4x4<T> const & m, tVec4<U> const & v ) { return compute_inversetMat4x4<T>::call(m)*v; } template <typename T, typename U> inline tVec4<T> operator/ ( tVec4<T> const & v, tMat4x4<U> const & m ) { return v * compute_inversetMat4x4<U>::call(m); } template <typename T, typename U> inline tMat4x4<T> operator/ ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { tMat4x4<T> m1_copy(m1); return m1_copy /= m2; } // Unary constant operators template <typename T> inline tMat4x4<T> const operator- ( tMat4x4<T> const & m ) { return tMat4x4<T>( -m[0], -m[1], -m[2], -m[3]); } template <typename T> inline tMat4x4<T> const operator++ ( tMat4x4<T> const & m, int ) { return tMat4x4<T>( m[0] + static_cast<T>(1), m[1] + static_cast<T>(1), m[2] + static_cast<T>(1), m[3] + static_cast<T>(1)); } template <typename T> inline tMat4x4<T> const operator-- ( tMat4x4<T> const & m, int ) { return tMat4x4<T>( m[0] - static_cast<T>(1), m[1] - static_cast<T>(1), m[2] - static_cast<T>(1), m[3] - static_cast<T>(1)); } ////////////////////////////////////// // Boolean operators template <typename T, typename U> inline bool operator== ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { return (m1[0] == m2[0]) && (m1[1] == m2[1]) && (m1[2] == m2[2]) && (m1[3] == m2[3]); } template <typename T, typename U> inline bool operator!= ( tMat4x4<T> const & m1, tMat4x4<U> const & m2 ) { return (m1[0] != m2[0]) || (m1[1] != m2[1]) || (m1[2] != m2[2]) || (m1[3] != m2[3]); } template <typename T, typename U> inline tMat4x3<T> operator* ( tMat4x3<T> const & m1, tMat4x4<U> const & m2 ) { return tMat4x3<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][2] * m2[0][0] + m1[1][2] * m2[0][1] + m1[2][2] * m2[0][2] + m1[3][2] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][2] * m2[1][0] + m1[1][2] * m2[1][1] + m1[2][2] * m2[1][2] + m1[3][2] * m2[1][3], m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], m1[0][2] * m2[2][0] + m1[1][2] * m2[2][1] + m1[2][2] * m2[2][2] + m1[3][2] * m2[2][3], m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3], m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3], m1[0][2] * m2[3][0] + m1[1][2] * m2[3][1] + m1[2][2] * m2[3][2] + m1[3][2] * m2[3][3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tMat3x4<T> const & m1, tMat4x3<U> const & m2 ) { const T & SrcA00 = m1[0][0]; const T & SrcA01 = m1[0][1]; const T & SrcA02 = m1[0][2]; const T & SrcA03 = m1[0][3]; const T & SrcA10 = m1[1][0]; const T & SrcA11 = m1[1][1]; const T & SrcA12 = m1[1][2]; const T & SrcA13 = m1[1][3]; const T & SrcA20 = m1[2][0]; const T & SrcA21 = m1[2][1]; const T & SrcA22 = m1[2][2]; const T & SrcA23 = m1[2][3]; const T & SrcB00 = m2[0][0]; const T & SrcB01 = m2[0][1]; const T & SrcB02 = m2[0][2]; const T & SrcB10 = m2[1][0]; const T & SrcB11 = m2[1][1]; const T & SrcB12 = m2[1][2]; const T & SrcB20 = m2[2][0]; const T & SrcB21 = m2[2][1]; const T & SrcB22 = m2[2][2]; const T & SrcB30 = m2[3][0]; const T & SrcB31 = m2[3][1]; const T & SrcB32 = m2[3][2]; tMat4x4<T> Result(T(0)); Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01 + SrcA20 * SrcB02; Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01 + SrcA21 * SrcB02; Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01 + SrcA22 * SrcB02; Result[0][3] = SrcA03 * SrcB00 + SrcA13 * SrcB01 + SrcA23 * SrcB02; Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11 + SrcA20 * SrcB12; Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11 + SrcA21 * SrcB12; Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11 + SrcA22 * SrcB12; Result[1][3] = SrcA03 * SrcB10 + SrcA13 * SrcB11 + SrcA23 * SrcB12; Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21 + SrcA20 * SrcB22; Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21 + SrcA21 * SrcB22; Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21 + SrcA22 * SrcB22; Result[2][3] = SrcA03 * SrcB20 + SrcA13 * SrcB21 + SrcA23 * SrcB22; Result[3][0] = SrcA00 * SrcB30 + SrcA10 * SrcB31 + SrcA20 * SrcB32; Result[3][1] = SrcA01 * SrcB30 + SrcA11 * SrcB31 + SrcA21 * SrcB32; Result[3][2] = SrcA02 * SrcB30 + SrcA12 * SrcB31 + SrcA22 * SrcB32; Result[3][3] = SrcA03 * SrcB30 + SrcA13 * SrcB31 + SrcA23 * SrcB32; return Result; } template <typename T, typename U> inline tMat4x2<T> operator* ( tMat4x2<T> const & m1, tMat4x4<U> const & m2 ) { return tMat4x2<T>( m1[0][0] * m2[0][0] + m1[1][0] * m2[0][1] + m1[2][0] * m2[0][2] + m1[3][0] * m2[0][3], m1[0][1] * m2[0][0] + m1[1][1] * m2[0][1] + m1[2][1] * m2[0][2] + m1[3][1] * m2[0][3], m1[0][0] * m2[1][0] + m1[1][0] * m2[1][1] + m1[2][0] * m2[1][2] + m1[3][0] * m2[1][3], m1[0][1] * m2[1][0] + m1[1][1] * m2[1][1] + m1[2][1] * m2[1][2] + m1[3][1] * m2[1][3], m1[0][0] * m2[2][0] + m1[1][0] * m2[2][1] + m1[2][0] * m2[2][2] + m1[3][0] * m2[2][3], m1[0][1] * m2[2][0] + m1[1][1] * m2[2][1] + m1[2][1] * m2[2][2] + m1[3][1] * m2[2][3], m1[0][0] * m2[3][0] + m1[1][0] * m2[3][1] + m1[2][0] * m2[3][2] + m1[3][0] * m2[3][3], m1[0][1] * m2[3][0] + m1[1][1] * m2[3][1] + m1[2][1] * m2[3][2] + m1[3][1] * m2[3][3]); } template <typename T, typename U> inline tMat4x4<T> operator* ( tMat2x4<T> const & m1, tMat4x2<U> const & m2 ) { const T & SrcA00 = m1[0][0]; const T & SrcA01 = m1[0][1]; const T & SrcA02 = m1[0][2]; const T & SrcA03 = m1[0][3]; const T & SrcA10 = m1[1][0]; const T & SrcA11 = m1[1][1]; const T & SrcA12 = m1[1][2]; const T & SrcA13 = m1[1][3]; const T & SrcB00 = m2[0][0]; const T & SrcB01 = m2[0][1]; const T & SrcB10 = m2[1][0]; const T & SrcB11 = m2[1][1]; const T & SrcB20 = m2[2][0]; const T & SrcB21 = m2[2][1]; const T & SrcB30 = m2[3][0]; const T & SrcB31 = m2[3][1]; tMat4x4<T> Result(T(0)); Result[0][0] = SrcA00 * SrcB00 + SrcA10 * SrcB01; Result[0][1] = SrcA01 * SrcB00 + SrcA11 * SrcB01; Result[0][2] = SrcA02 * SrcB00 + SrcA12 * SrcB01; Result[0][3] = SrcA03 * SrcB00 + SrcA13 * SrcB01; Result[1][0] = SrcA00 * SrcB10 + SrcA10 * SrcB11; Result[1][1] = SrcA01 * SrcB10 + SrcA11 * SrcB11; Result[1][2] = SrcA02 * SrcB10 + SrcA12 * SrcB11; Result[1][3] = SrcA03 * SrcB10 + SrcA13 * SrcB11; Result[2][0] = SrcA00 * SrcB20 + SrcA10 * SrcB21; Result[2][1] = SrcA01 * SrcB20 + SrcA11 * SrcB21; Result[2][2] = SrcA02 * SrcB20 + SrcA12 * SrcB21; Result[2][3] = SrcA03 * SrcB20 + SrcA13 * SrcB21; Result[3][0] = SrcA00 * SrcB30 + SrcA10 * SrcB31; Result[3][1] = SrcA01 * SrcB30 + SrcA11 * SrcB31; Result[3][2] = SrcA02 * SrcB30 + SrcA12 * SrcB31; Result[3][3] = SrcA03 * SrcB30 + SrcA13 * SrcB31; return Result; } } typedef Detail::tMat4x4<PDP::UInteger> UMat4x4; typedef Detail::tMat4x4<PDP::Integer> IMat4x4; typedef Detail::tMat4x4<float> Mat4x4; typedef Detail::tMat4x4<double> DMat4x4; typedef Detail::tMat4x4<unsigned short> USMat4x4; typedef Detail::tMat4x4<short> SMat4x4; //typedef Detail::tMat4x4<PDP::Half> HMat4x4; } namespace LD { namespace Detail { template<typename T> struct StaticallySized<LD::Detail::tMat4x4<T>>: public LD::Detail::IntegralConstant<bool,true> { }; } } #endif
36.531889
210
0.40164
jlandess
edf4d6c14d2cf3c573aca49985a79226597e3f85
5,614
hpp
C++
test/parser_default_parameters_extra_args_in_between.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
test/parser_default_parameters_extra_args_in_between.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
test/parser_default_parameters_extra_args_in_between.hpp
cynodelic/metaflags
171f09800910a1c20ce8732441e27f33d8d2ce4f
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #ifndef CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP #define CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP CYNODELIC_TESTER_TEST_CASE(parser_default_parameters_extra_args_in_between); CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,all_long_flags_called) { using prs = mfl::parser< mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>, mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>, mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>> >; argv_maker test_argv( "test", "--first", "1", "extra_args", "431","33", "--second", "1","2", "__XYZ__", "--third", "1","2","3" ); prs::parse(static_cast<int>(test_argv.size()),test_argv.data()); CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1); CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),13); CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),13); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2)),3); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0)),1); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1)),2); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2)),3); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first"))); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--second"))); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--third"))); } CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,single_long_flag_called) { using prs = mfl::parser< mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>, mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>, mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>> >; argv_maker test_argv( "test", "aaaaaaaaaa", "12345", "--first", "12" ); prs::parse(static_cast<int>(test_argv.size()),test_argv.data()); CYNODELIC_TESTER_MESSAGE << "prs::finished_at() = " << prs::finished_at(); CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1); CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),4); CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),4); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0,0)),12); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0,0)),12); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2,0)),0); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first"))); CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--second"))); CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--third"))); } CYNODELIC_TESTER_SECTION(parser_default_parameters_extra_args_in_between,two_long_flags_called) { using prs = mfl::parser< mfl::flag<STRING_("first,f"),STRING_("..."),mfl::i32_arg<>>, mfl::flag<STRING_("second,s"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>>, mfl::flag<STRING_("third,t"),STRING_("..."),mfl::i32_arg<>,mfl::i32_arg<>,mfl::i32_arg<>> >; argv_maker test_argv( "test", "--first", "963", "AAA", "--extra_arg", "--second", "34","56" ); prs::parse(static_cast<int>(test_argv.size()),test_argv.data()); CYNODELIC_TESTER_MESSAGE << "prs::finished_at() = " << prs::finished_at(); CYNODELIC_TESTER_CHECK_EQUALS(prs::starts_at(),1); CYNODELIC_TESTER_CHECK_EQUALS(prs::last_parsed_argument_position(),7); CYNODELIC_TESTER_CHECK_EQUALS(prs::finished_at(),7); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--first",0,0)),963); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",0,0)),34); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--second",1,0)),56); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"--third",2,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-f",0,0)),963); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",0,0)),34); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-s",1,0)),56); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",0,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",1,0)),0); CYNODELIC_TESTER_CHECK_EQUALS((GET_ARG(prs,"-t",2,0)),0); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--first"))); CYNODELIC_TESTER_CHECK_TRUE((WAS_CALLED(prs,"--second"))); CYNODELIC_TESTER_CHECK_FALSE((WAS_CALLED(prs,"--third"))); } #endif // CYNODELIC_METAFLAGS_TEST_PARSER_DEFAULT_PARAMETERS_EXTRA_ARGS_IN_BETWEEN_HPP
38.452055
97
0.731386
cynodelic
edf4e86f8a89845491b36e5786f8d7bf6cb4ceac
2,242
cpp
C++
PDFWriter/Trace.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
1,039
2015-01-18T20:03:11.000Z
2022-03-24T02:46:05.000Z
PDFWriter/Trace.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
414
2015-01-22T15:08:45.000Z
2022-02-07T13:51:48.000Z
PDFWriter/Trace.cpp
thmclellan/PDF-Writer
9d31d12ce12e586b4f7f748e17029a10ccc2c176
[ "Apache-2.0" ]
209
2015-03-30T23:04:26.000Z
2022-03-28T18:58:47.000Z
/* Source File : Trace.cpp Copyright 2011 Gal Kahana PDFWriter 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 "Trace.h" #include "Log.h" #include "SafeBufferMacrosDefs.h" #include <stdio.h> #include <stdarg.h> Trace& Trace::DefaultTrace(){ static Trace default_trace; return default_trace; } Trace::Trace(void) { mLog = NULL; mLogFilePath = "Log.txt"; mShouldLog = false; } Trace::~Trace(void) { delete mLog; } void Trace::SetLogSettings(const std::string& inLogFilePath,bool inShouldLog,bool inPlaceUTF8Bom) { mShouldLog = inShouldLog; mPlaceUTF8Bom = inPlaceUTF8Bom; mLogFilePath = inLogFilePath; mLogStream = NULL; if(mLog != NULL) { delete mLog; mLog = NULL; //if(mShouldLog) // mLog = new Log(mLogFilePath,inPlaceUTF8Bom); } } void Trace::SetLogSettings(IByteWriter* inLogStream,bool inShouldLog) { mShouldLog = inShouldLog; mLogStream = inLogStream; mPlaceUTF8Bom = false; if(mLog != NULL) { delete mLog; mLog = NULL; if(mShouldLog) mLog = new Log(mLogStream); } } void Trace::TraceToLog(const char* inFormat,...) { if(mShouldLog) { if(NULL == mLog) { if(mLogStream) mLog = new Log(mLogStream); else mLog = new Log(mLogFilePath,mPlaceUTF8Bom); } va_list argptr; va_start(argptr, inFormat); SAFE_VSPRINTF(mBuffer, MAX_TRACE_SIZE,inFormat,argptr); va_end(argptr); mLog->LogEntry(std::string(mBuffer)); } } void Trace::TraceToLog(const char* inFormat,va_list inList) { if(mShouldLog) { if(NULL == mLog) { if(mLogStream) mLog = new Log(mLogStream); else mLog = new Log(mLogFilePath,mPlaceUTF8Bom); } SAFE_VSPRINTF(mBuffer, MAX_TRACE_SIZE,inFormat,inList); mLog->LogEntry(std::string(mBuffer)); } }
19.327586
97
0.706512
thmclellan
edf5ac4512886af5808226f06babb0e66e541335
2,158
cpp
C++
aws-cpp-sdk-mgn/source/model/IdentificationHints.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-mgn/source/model/IdentificationHints.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-mgn/source/model/IdentificationHints.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/mgn/model/IdentificationHints.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace mgn { namespace Model { IdentificationHints::IdentificationHints() : m_awsInstanceIDHasBeenSet(false), m_fqdnHasBeenSet(false), m_hostnameHasBeenSet(false), m_vmPathHasBeenSet(false), m_vmWareUuidHasBeenSet(false) { } IdentificationHints::IdentificationHints(JsonView jsonValue) : m_awsInstanceIDHasBeenSet(false), m_fqdnHasBeenSet(false), m_hostnameHasBeenSet(false), m_vmPathHasBeenSet(false), m_vmWareUuidHasBeenSet(false) { *this = jsonValue; } IdentificationHints& IdentificationHints::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("awsInstanceID")) { m_awsInstanceID = jsonValue.GetString("awsInstanceID"); m_awsInstanceIDHasBeenSet = true; } if(jsonValue.ValueExists("fqdn")) { m_fqdn = jsonValue.GetString("fqdn"); m_fqdnHasBeenSet = true; } if(jsonValue.ValueExists("hostname")) { m_hostname = jsonValue.GetString("hostname"); m_hostnameHasBeenSet = true; } if(jsonValue.ValueExists("vmPath")) { m_vmPath = jsonValue.GetString("vmPath"); m_vmPathHasBeenSet = true; } if(jsonValue.ValueExists("vmWareUuid")) { m_vmWareUuid = jsonValue.GetString("vmWareUuid"); m_vmWareUuidHasBeenSet = true; } return *this; } JsonValue IdentificationHints::Jsonize() const { JsonValue payload; if(m_awsInstanceIDHasBeenSet) { payload.WithString("awsInstanceID", m_awsInstanceID); } if(m_fqdnHasBeenSet) { payload.WithString("fqdn", m_fqdn); } if(m_hostnameHasBeenSet) { payload.WithString("hostname", m_hostname); } if(m_vmPathHasBeenSet) { payload.WithString("vmPath", m_vmPath); } if(m_vmWareUuidHasBeenSet) { payload.WithString("vmWareUuid", m_vmWareUuid); } return payload; } } // namespace Model } // namespace mgn } // namespace Aws
17.983333
72
0.712697
perfectrecall
edfca4da0ac988ec35bb064d320585eb1bd51517
2,041
hpp
C++
sdk/include/vill_runtime.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/vill_runtime.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
sdk/include/vill_runtime.hpp
qianxj/XExplorer
00e326da03ffcaa21115a2345275452607c6bab5
[ "MIT" ]
null
null
null
#ifndef WPP_VILL_RUNTIME_H #define WPP_VILL_RUNTIME_H #include <vector> #include "wlexer.hpp" #include "werr.hpp" #include "errors.hpp" using namespace wpp; using namespace wpp::how; namespace mill{ struct vill_type { typedef unsigned char int_u8; typedef unsigned short int_u16; typedef unsigned int int_u32; typedef unsigned __int64 int_u64; typedef char int_i8; typedef short int_i16; typedef int int_i32; typedef __int64 int_i64; typedef float float32; typedef double float64; typedef long double float80; typedef char* astring; typedef wchar_t* string; typedef unsigned char ubyte; typedef char byte; typedef char achar; typedef wchar_t wchar; typedef void* obj_ptr; typedef bool boolean; }; struct vill_register { union { vill_type::int_u8 val_u8; vill_type::int_u16 val_u16; vill_type::int_u32 val_u32; vill_type::int_u64 val_u64; vill_type::int_i8 val_i8; vill_type::int_i16 val_i16; vill_type::int_i32 val_i32; vill_type::int_i64 val_i64; vill_type::float32 val_f32; vill_type::float64 val_f64; vill_type::float80 val_f80; vill_type::boolean val_bool; vill_type::obj_ptr val_ptr; vill_type::string val_string; vill_type::astring val_astring; }; }; struct vill_flag_register { unsigned int C : 1; //carry unsigned int Z : 1; //zero unsigned int S : 1; //sign unsigned int O : 1; //overflow }; class vill_runtime { public: static const int void_ptr_size = 4; public: std::vector<vill_register>* ptr_registeres; vill_flag_register flag_register; int* ptr_stackes; int* stack_bp; int* stack_sp; public: void set_err_ptr(wErr* err_ptr); wErr* get_err_ptr(); void error(error::err nError, const wchar_t* str, wtoken& tk); private: wErr* err_ptr_; public: //std::map<std::wstring /*dll*/,std::map<std::wstring /*alias*/, int>> * ptr_extern_method_; vill_runtime(); ~vill_runtime(); public: void reset(); //int step_next(); //int step_continue(); }; } //namespace mill #endif //WPP_VILL_RUNTIME
20.826531
93
0.721215
qianxj
61035e572c4d4f3462a25672f11baa47330bc2cf
28,079
cpp
C++
Checkpoint.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
Checkpoint.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
Checkpoint.cpp
lighthouse-os/system_vold
a6410826bfb872d3b2a52cff063b271fef133e54
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "Checkpoint" #include "Checkpoint.h" #include "VoldUtil.h" #include "VolumeManager.h" #include <fstream> #include <list> #include <memory> #include <string> #include <thread> #include <vector> #include <android-base/file.h> #include <android-base/logging.h> #include <android-base/parseint.h> #include <android-base/properties.h> #include <android-base/unique_fd.h> #include <android/hardware/boot/1.0/IBootControl.h> #include <cutils/android_reboot.h> #include <fcntl.h> #include <fs_mgr.h> #include <linux/fs.h> #include <mntent.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/statvfs.h> #include <unistd.h> using android::base::GetBoolProperty; using android::base::GetUintProperty; using android::base::SetProperty; using android::binder::Status; using android::fs_mgr::Fstab; using android::fs_mgr::ReadDefaultFstab; using android::fs_mgr::ReadFstabFromFile; using android::hardware::hidl_string; using android::hardware::boot::V1_0::BoolResult; using android::hardware::boot::V1_0::CommandResult; using android::hardware::boot::V1_0::IBootControl; using android::hardware::boot::V1_0::Slot; namespace android { namespace vold { namespace { const std::string kMetadataCPFile = "/metadata/vold/checkpoint"; binder::Status error(const std::string& msg) { PLOG(ERROR) << msg; return binder::Status::fromServiceSpecificError(errno, String8(msg.c_str())); } binder::Status error(int error, const std::string& msg) { LOG(ERROR) << msg; return binder::Status::fromServiceSpecificError(error, String8(msg.c_str())); } bool setBowState(std::string const& block_device, std::string const& state) { std::string bow_device = fs_mgr_find_bow_device(block_device); if (bow_device.empty()) return false; if (!android::base::WriteStringToFile(state, bow_device + "/bow/state")) { PLOG(ERROR) << "Failed to write to file " << bow_device + "/bow/state"; return false; } return true; } } // namespace Status cp_supportsCheckpoint(bool& result) { result = false; for (const auto& entry : fstab_default) { if (entry.fs_mgr_flags.checkpoint_blk || entry.fs_mgr_flags.checkpoint_fs) { result = true; return Status::ok(); } } return Status::ok(); } Status cp_supportsBlockCheckpoint(bool& result) { result = false; for (const auto& entry : fstab_default) { if (entry.fs_mgr_flags.checkpoint_blk) { result = true; return Status::ok(); } } return Status::ok(); } Status cp_supportsFileCheckpoint(bool& result) { result = false; for (const auto& entry : fstab_default) { if (entry.fs_mgr_flags.checkpoint_fs) { result = true; return Status::ok(); } } return Status::ok(); } Status cp_startCheckpoint(int retry) { bool result; if (!cp_supportsCheckpoint(result).isOk() || !result) return error(ENOTSUP, "Checkpoints not supported"); if (retry < -1) return error(EINVAL, "Retry count must be more than -1"); std::string content = std::to_string(retry + 1); if (retry == -1) { sp<IBootControl> module = IBootControl::getService(); if (module) { std::string suffix; auto cb = [&suffix](hidl_string s) { suffix = s; }; if (module->getSuffix(module->getCurrentSlot(), cb).isOk()) content += " " + suffix; } } if (!android::base::WriteStringToFile(content, kMetadataCPFile)) return error("Failed to write checkpoint file"); return Status::ok(); } namespace { volatile bool isCheckpointing = false; volatile bool needsCheckpointWasCalled = false; // Protects isCheckpointing, needsCheckpointWasCalled and code that makes decisions based on status // of isCheckpointing std::mutex isCheckpointingLock; } Status cp_commitChanges() { std::lock_guard<std::mutex> lock(isCheckpointingLock); if (!isCheckpointing) { return Status::ok(); } if (android::base::GetProperty("persist.vold.dont_commit_checkpoint", "0") == "1") { LOG(WARNING) << "NOT COMMITTING CHECKPOINT BECAUSE persist.vold.dont_commit_checkpoint IS 1"; return Status::ok(); } sp<IBootControl> module = IBootControl::getService(); if (module) { CommandResult cr; module->markBootSuccessful([&cr](CommandResult result) { cr = result; }); if (!cr.success) return error(EINVAL, "Error marking booted successfully: " + std::string(cr.errMsg)); LOG(INFO) << "Marked slot as booted successfully."; // Clears the warm reset flag for next reboot. if (!SetProperty("ota.warm_reset", "0")) { LOG(WARNING) << "Failed to reset the warm reset flag"; } } // Must take action for list of mounted checkpointed things here // To do this, we walk the list of mounted file systems. // But we also need to get the matching fstab entries to see // the original flags std::string err_str; Fstab mounts; if (!ReadFstabFromFile("/proc/mounts", &mounts)) { return error(EINVAL, "Failed to get /proc/mounts"); } // Walk mounted file systems for (const auto& mount_rec : mounts) { const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point); if (!fstab_rec) continue; if (fstab_rec->fs_mgr_flags.checkpoint_fs) { if (fstab_rec->fs_type == "f2fs") { std::string options = mount_rec.fs_options + ",checkpoint=enable"; if (mount(mount_rec.blk_device.c_str(), mount_rec.mount_point.c_str(), "none", MS_REMOUNT | fstab_rec->flags, options.c_str())) { return error(EINVAL, "Failed to remount"); } } } else if (fstab_rec->fs_mgr_flags.checkpoint_blk) { if (!setBowState(mount_rec.blk_device, "2")) return error(EINVAL, "Failed to set bow state"); } } SetProperty("vold.checkpoint_committed", "1"); LOG(INFO) << "Checkpoint has been committed."; isCheckpointing = false; if (!android::base::RemoveFileIfExists(kMetadataCPFile, &err_str)) return error(err_str.c_str()); return Status::ok(); } namespace { void abort_metadata_file() { std::string oldContent, newContent; int retry = 0; struct stat st; int result = stat(kMetadataCPFile.c_str(), &st); // If the file doesn't exist, we aren't managing a checkpoint retry counter if (result != 0) return; if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) { PLOG(ERROR) << "Failed to read checkpoint file"; return; } std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" ")); if (!android::base::ParseInt(retryContent, &retry)) { PLOG(ERROR) << "Could not parse retry count"; return; } if (retry > 0) { newContent = "0"; if (!android::base::WriteStringToFile(newContent, kMetadataCPFile)) PLOG(ERROR) << "Could not write checkpoint file"; } } } // namespace void cp_abortChanges(const std::string& message, bool retry) { if (!cp_needsCheckpoint()) return; if (!retry) abort_metadata_file(); android_reboot(ANDROID_RB_RESTART2, 0, message.c_str()); } bool cp_needsRollback() { std::string content; bool ret; ret = android::base::ReadFileToString(kMetadataCPFile, &content); if (ret) { if (content == "0") return true; if (content.substr(0, 3) == "-1 ") { std::string oldSuffix = content.substr(3); sp<IBootControl> module = IBootControl::getService(); std::string newSuffix; if (module) { auto cb = [&newSuffix](hidl_string s) { newSuffix = s; }; module->getSuffix(module->getCurrentSlot(), cb); if (oldSuffix == newSuffix) return true; } } } return false; } bool cp_needsCheckpoint() { std::lock_guard<std::mutex> lock(isCheckpointingLock); // Make sure we only return true during boot. See b/138952436 for discussion if (needsCheckpointWasCalled) return isCheckpointing; needsCheckpointWasCalled = true; bool ret; std::string content; sp<IBootControl> module = IBootControl::getService(); if (isCheckpointing) return isCheckpointing; if (module && module->isSlotMarkedSuccessful(module->getCurrentSlot()) == BoolResult::FALSE) { isCheckpointing = true; return true; } ret = android::base::ReadFileToString(kMetadataCPFile, &content); if (ret) { ret = content != "0"; isCheckpointing = ret; return ret; } return false; } bool cp_isCheckpointing() { return isCheckpointing; } namespace { const std::string kSleepTimeProp = "ro.sys.cp_msleeptime"; const uint32_t msleeptime_default = 1000; // 1 s const uint32_t max_msleeptime = 3600000; // 1 h const std::string kMinFreeBytesProp = "ro.sys.cp_min_free_bytes"; const uint64_t min_free_bytes_default = 100 * (1 << 20); // 100 MiB const std::string kCommitOnFullProp = "ro.sys.cp_commit_on_full"; const bool commit_on_full_default = true; static void cp_healthDaemon(std::string mnt_pnt, std::string blk_device, bool is_fs_cp) { struct statvfs data; uint32_t msleeptime = GetUintProperty(kSleepTimeProp, msleeptime_default, max_msleeptime); uint64_t min_free_bytes = GetUintProperty(kMinFreeBytesProp, min_free_bytes_default, (uint64_t)-1); bool commit_on_full = GetBoolProperty(kCommitOnFullProp, commit_on_full_default); struct timespec req; req.tv_sec = msleeptime / 1000; msleeptime %= 1000; req.tv_nsec = msleeptime * 1000000; while (isCheckpointing) { uint64_t free_bytes = 0; if (is_fs_cp) { statvfs(mnt_pnt.c_str(), &data); free_bytes = ((uint64_t) data.f_bavail) * data.f_frsize; } else { std::string bow_device = fs_mgr_find_bow_device(blk_device); if (!bow_device.empty()) { std::string content; if (android::base::ReadFileToString(bow_device + "/bow/free", &content)) { free_bytes = std::strtoull(content.c_str(), NULL, 10); } } } if (free_bytes < min_free_bytes) { if (commit_on_full) { LOG(INFO) << "Low space for checkpointing. Commiting changes"; cp_commitChanges(); break; } else { LOG(INFO) << "Low space for checkpointing. Rebooting"; cp_abortChanges("checkpoint,low_space", false); break; } } nanosleep(&req, NULL); } } } // namespace Status cp_prepareCheckpoint() { // Log to notify CTS - see b/137924328 for context LOG(INFO) << "cp_prepareCheckpoint called"; std::lock_guard<std::mutex> lock(isCheckpointingLock); if (!isCheckpointing) { return Status::ok(); } Fstab mounts; if (!ReadFstabFromFile("/proc/mounts", &mounts)) { return error(EINVAL, "Failed to get /proc/mounts"); } for (const auto& mount_rec : mounts) { const auto fstab_rec = GetEntryForMountPoint(&fstab_default, mount_rec.mount_point); if (!fstab_rec) continue; if (fstab_rec->fs_mgr_flags.checkpoint_blk) { android::base::unique_fd fd( TEMP_FAILURE_RETRY(open(mount_rec.mount_point.c_str(), O_RDONLY | O_CLOEXEC))); if (fd == -1) { PLOG(ERROR) << "Failed to open mount point" << mount_rec.mount_point; continue; } struct fstrim_range range = {}; range.len = ULLONG_MAX; nsecs_t start = systemTime(SYSTEM_TIME_BOOTTIME); if (ioctl(fd, FITRIM, &range)) { PLOG(ERROR) << "Failed to trim " << mount_rec.mount_point; continue; } nsecs_t time = systemTime(SYSTEM_TIME_BOOTTIME) - start; LOG(INFO) << "Trimmed " << range.len << " bytes on " << mount_rec.mount_point << " in " << nanoseconds_to_milliseconds(time) << "ms for checkpoint"; setBowState(mount_rec.blk_device, "1"); } if (fstab_rec->fs_mgr_flags.checkpoint_blk || fstab_rec->fs_mgr_flags.checkpoint_fs) { std::thread(cp_healthDaemon, std::string(mount_rec.mount_point), std::string(mount_rec.blk_device), fstab_rec->fs_mgr_flags.checkpoint_fs == 1) .detach(); } } return Status::ok(); } namespace { const int kSectorSize = 512; typedef uint64_t sector_t; struct log_entry { sector_t source; // in sectors of size kSectorSize sector_t dest; // in sectors of size kSectorSize uint32_t size; // in bytes uint32_t checksum; } __attribute__((packed)); struct log_sector_v1_0 { uint32_t magic; uint16_t header_version; uint16_t header_size; uint32_t block_size; uint32_t count; uint32_t sequence; uint64_t sector0; } __attribute__((packed)); // MAGIC is BOW in ascii const int kMagic = 0x00574f42; // Partially restored MAGIC is WOB in ascii const int kPartialRestoreMagic = 0x00424f57; void crc32(const void* data, size_t n_bytes, uint32_t* crc) { static uint32_t table[0x100] = { 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D}; for (size_t i = 0; i < n_bytes; ++i) { *crc ^= ((uint8_t*)data)[i]; *crc = table[(uint8_t)*crc] ^ *crc >> 8; } } // A map of relocations. // The map must be initialized so that relocations[0] = 0 // During restore, we replay the log records in reverse, copying from dest to // source // To validate, we must be able to read the 'dest' sectors as though they had // been copied but without actually copying. This map represents how the sectors // would have been moved. To read a sector s, find the index <= s and read // relocations[index] + s - index typedef std::map<sector_t, sector_t> Relocations; void relocate(Relocations& relocations, sector_t dest, sector_t source, int count) { // Find first one we're equal to or greater than auto s = --relocations.upper_bound(source); // Take slice Relocations slice; slice[dest] = source - s->first + s->second; ++s; // Add rest of elements for (; s != relocations.end() && s->first < source + count; ++s) slice[dest - source + s->first] = s->second; // Split range at end of dest auto dest_end = --relocations.upper_bound(dest + count); relocations[dest + count] = dest + count - dest_end->first + dest_end->second; // Remove all elements in [dest, dest + count) relocations.erase(relocations.lower_bound(dest), relocations.lower_bound(dest + count)); // Add new elements relocations.insert(slice.begin(), slice.end()); } // A map of sectors that have been written to. // The final entry must always be False. // When we restart the restore after an interruption, we must take care that // when we copy from dest to source, that the block we copy to was not // previously copied from. // i e. A->B C->A; If we replay this sequence, we end up copying C->B // We must save our partial result whenever we finish a page, or when we copy // to a location that was copied from earlier (our source is an earlier dest) typedef std::map<sector_t, bool> Used_Sectors; bool checkCollision(Used_Sectors& used_sectors, sector_t start, sector_t end) { auto second_overlap = used_sectors.upper_bound(start); auto first_overlap = --second_overlap; if (first_overlap->second) { return true; } else if (second_overlap != used_sectors.end() && second_overlap->first < end) { return true; } return false; } void markUsed(Used_Sectors& used_sectors, sector_t start, sector_t end) { auto start_pos = used_sectors.insert_or_assign(start, true).first; auto end_pos = used_sectors.insert_or_assign(end, false).first; if (start_pos == used_sectors.begin() || !std::prev(start_pos)->second) { start_pos++; } if (std::next(end_pos) != used_sectors.end() && !std::next(end_pos)->second) { end_pos++; } if (start_pos->first < end_pos->first) { used_sectors.erase(start_pos, end_pos); } } // Restores the given log_entry's data from dest -> source // If that entry is a log sector, set the magic to kPartialRestoreMagic and flush. void restoreSector(int device_fd, Used_Sectors& used_sectors, std::vector<char>& ls_buffer, log_entry* le, std::vector<char>& buffer) { log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]); uint32_t index = le - ((log_entry*)&ls_buffer[ls.header_size]); int count = (le->size - 1) / kSectorSize + 1; if (checkCollision(used_sectors, le->source, le->source + count)) { fsync(device_fd); lseek64(device_fd, 0, SEEK_SET); ls.count = index + 1; ls.magic = kPartialRestoreMagic; write(device_fd, &ls_buffer[0], ls.block_size); fsync(device_fd); used_sectors.clear(); used_sectors[0] = false; } markUsed(used_sectors, le->dest, le->dest + count); if (index == 0 && ls.sequence != 0) { log_sector_v1_0* next = reinterpret_cast<log_sector_v1_0*>(&buffer[0]); if (next->magic == kMagic) { next->magic = kPartialRestoreMagic; } } lseek64(device_fd, le->source * kSectorSize, SEEK_SET); write(device_fd, &buffer[0], le->size); if (index == 0) { fsync(device_fd); } } // Read from the device // If we are validating, the read occurs as though the relocations had happened std::vector<char> relocatedRead(int device_fd, Relocations const& relocations, bool validating, sector_t sector, uint32_t size, uint32_t block_size) { if (!validating) { std::vector<char> buffer(size); lseek64(device_fd, sector * kSectorSize, SEEK_SET); read(device_fd, &buffer[0], size); return buffer; } std::vector<char> buffer(size); for (uint32_t i = 0; i < size; i += block_size, sector += block_size / kSectorSize) { auto relocation = --relocations.upper_bound(sector); lseek64(device_fd, (sector + relocation->second - relocation->first) * kSectorSize, SEEK_SET); read(device_fd, &buffer[i], block_size); } return buffer; } } // namespace Status cp_restoreCheckpoint(const std::string& blockDevice, int restore_limit) { bool validating = true; std::string action = "Validating"; int restore_count = 0; for (;;) { Relocations relocations; relocations[0] = 0; Status status = Status::ok(); LOG(INFO) << action << " checkpoint on " << blockDevice; base::unique_fd device_fd(open(blockDevice.c_str(), O_RDWR | O_CLOEXEC)); if (device_fd < 0) return error("Cannot open " + blockDevice); log_sector_v1_0 original_ls; read(device_fd, reinterpret_cast<char*>(&original_ls), sizeof(original_ls)); if (original_ls.magic == kPartialRestoreMagic) { validating = false; action = "Restoring"; } else if (original_ls.magic != kMagic) { return error(EINVAL, "No magic"); } LOG(INFO) << action << " " << original_ls.sequence << " log sectors"; for (int sequence = original_ls.sequence; sequence >= 0 && status.isOk(); sequence--) { auto ls_buffer = relocatedRead(device_fd, relocations, validating, 0, original_ls.block_size, original_ls.block_size); log_sector_v1_0& ls = *reinterpret_cast<log_sector_v1_0*>(&ls_buffer[0]); Used_Sectors used_sectors; used_sectors[0] = false; if (ls.magic != kMagic && (ls.magic != kPartialRestoreMagic || validating)) { status = error(EINVAL, "No magic"); break; } if (ls.block_size != original_ls.block_size) { status = error(EINVAL, "Block size mismatch"); break; } if ((int)ls.sequence != sequence) { status = error(EINVAL, "Expecting log sector " + std::to_string(sequence) + " but got " + std::to_string(ls.sequence)); break; } LOG(INFO) << action << " from log sector " << ls.sequence; for (log_entry* le = reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]) + ls.count - 1; le >= reinterpret_cast<log_entry*>(&ls_buffer[ls.header_size]); --le) { // This is very noisy - limit to DEBUG only LOG(VERBOSE) << action << " " << le->size << " bytes from sector " << le->dest << " to " << le->source << " with checksum " << std::hex << le->checksum; auto buffer = relocatedRead(device_fd, relocations, validating, le->dest, le->size, ls.block_size); uint32_t checksum = le->source / (ls.block_size / kSectorSize); for (size_t i = 0; i < le->size; i += ls.block_size) { crc32(&buffer[i], ls.block_size, &checksum); } if (le->checksum && checksum != le->checksum) { status = error(EINVAL, "Checksums don't match"); break; } if (validating) { relocate(relocations, le->source, le->dest, (le->size - 1) / kSectorSize + 1); } else { restoreSector(device_fd, used_sectors, ls_buffer, le, buffer); restore_count++; if (restore_limit && restore_count >= restore_limit) { status = error(EAGAIN, "Hit the test limit"); break; } } } } if (!status.isOk()) { if (!validating) { LOG(ERROR) << "Checkpoint restore failed even though checkpoint validation passed"; return status; } LOG(WARNING) << "Checkpoint validation failed - attempting to roll forward"; auto buffer = relocatedRead(device_fd, relocations, false, original_ls.sector0, original_ls.block_size, original_ls.block_size); lseek64(device_fd, 0, SEEK_SET); write(device_fd, &buffer[0], original_ls.block_size); return Status::ok(); } if (!validating) break; validating = false; action = "Restoring"; } return Status::ok(); } Status cp_markBootAttempt() { std::string oldContent, newContent; int retry = 0; struct stat st; int result = stat(kMetadataCPFile.c_str(), &st); // If the file doesn't exist, we aren't managing a checkpoint retry counter if (result != 0) return Status::ok(); if (!android::base::ReadFileToString(kMetadataCPFile, &oldContent)) return error("Failed to read checkpoint file"); std::string retryContent = oldContent.substr(0, oldContent.find_first_of(" ")); if (!android::base::ParseInt(retryContent, &retry)) return error(EINVAL, "Could not parse retry count"); if (retry > 0) { retry--; newContent = std::to_string(retry); if (!android::base::WriteStringToFile(newContent, kMetadataCPFile)) return error("Could not write checkpoint file"); } return Status::ok(); } void cp_resetCheckpoint() { std::lock_guard<std::mutex> lock(isCheckpointingLock); needsCheckpointWasCalled = false; } } // namespace vold } // namespace android
37.488652
99
0.635671
lighthouse-os
610411775e48998fe94d2266f16faa552b075df6
220
cpp
C++
NonOpt/tests/testPoint.cpp
frankecurtis/NonOpt
f81ff1c818dcde382cf6045a671bf8bc1d3a3467
[ "MIT" ]
4
2021-06-27T18:13:59.000Z
2022-01-25T00:36:56.000Z
NonOpt/tests/testPoint.cpp
frankecurtis/NonOpt
f81ff1c818dcde382cf6045a671bf8bc1d3a3467
[ "MIT" ]
null
null
null
NonOpt/tests/testPoint.cpp
frankecurtis/NonOpt
f81ff1c818dcde382cf6045a671bf8bc1d3a3467
[ "MIT" ]
1
2021-06-27T18:14:02.000Z
2021-06-27T18:14:02.000Z
// Copyright (C) 2022 Frank E. Curtis // // This code is published under the MIT License. // // Author(s) : Frank E. Curtis #include "testPoint.hpp" // Main function int main() { return testPointImplementation(1); }
15.714286
48
0.681818
frankecurtis
61049f69be37617afa2968b10a34abecbfb62b3a
1,500
cpp
C++
FantasyBrawl_Project/Motor2D/UI_Clock.cpp
project2-tmp/Base_Code
72cd8b375a912c2760e62f273c74de7c0c6d939e
[ "MIT" ]
6
2019-04-14T18:17:35.000Z
2021-07-29T02:22:24.000Z
FantasyBrawl_Project/Motor2D/UI_Clock.cpp
project2-tmp/Base_Code
72cd8b375a912c2760e62f273c74de7c0c6d939e
[ "MIT" ]
7
2019-03-21T22:00:20.000Z
2019-06-12T00:37:31.000Z
FantasyBrawl_Project/Motor2D/UI_Clock.cpp
CheckTheDog/Fantasy-Brawl
72cd8b375a912c2760e62f273c74de7c0c6d939e
[ "MIT" ]
2
2019-11-18T09:13:31.000Z
2021-02-03T21:02:52.000Z
#include "UI_Clock.h" #include "j1App.h" #include "j1Render.h" #include "j1Gui.h" #include "Brofiler\Brofiler.h" void Clock::setStartValue(int new_start_value) { start_value = new_start_value; } void Clock::setAlarm(int alarm) { alarms.push_back(alarm); } void Clock::restartChrono() { switch (this->type) { case TIMER: time = start_value; break; case STOPWATCH: time = 0; break; } } void Clock::BlitElement() { BROFILER_CATEGORY("Clock Blit", Profiler::Color::PowderBlue); time_elapsed = counter.ReadSec(); switch (type) { case STOPWATCH: if (time != time_elapsed) { time = time_elapsed; if (callback != nullptr) //If has callback send event { for (int i = 0; i < alarms.size(); i++) { if (time == (int)alarms[i]) callback->OnUIEvent(this, STOPWATCH_ALARM); } } std::string secs = std::to_string(time); //p2SString secs("%04d", time); if (last_secs != secs) text->setText(secs); section = text->section; last_secs = std::to_string(time); } break; case TIMER: if (start_value - time_elapsed != time && time != 0) { time = start_value - time_elapsed; if (time == 0 && callback != nullptr) //If has callback send event callback->OnUIEvent(this, TIMER_ZERO); //p2SString secs("%d", time); std::string secs = std::to_string(time); if (last_secs != secs) text->setText(secs); section = text->section; last_secs = std::to_string(time); } break; } text->BlitElement(); }
18.072289
69
0.637333
project2-tmp
610b46c5733d2a5a9c820a4c7717ed352c7bb78f
899
cpp
C++
Box3D/src/TextureBuffer.cpp
Campeanu/Box3D
2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec
[ "MIT" ]
1
2020-07-20T15:55:43.000Z
2020-07-20T15:55:43.000Z
Box3D/src/TextureBuffer.cpp
Campeanu/Box3D
2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec
[ "MIT" ]
null
null
null
Box3D/src/TextureBuffer.cpp
Campeanu/Box3D
2b1bb5b7b3bd66cbe6a32d910ce56ba41023dcec
[ "MIT" ]
null
null
null
#include <Box3D/Renderer/TextureBuffer.hpp> namespace box3d { TextureBuffer::TextureBuffer() { glGenTextures(1, &this->m_rendererID); glBindTexture(GL_TEXTURE_2D, this->m_rendererID); } TextureBuffer::~TextureBuffer() { } void TextureBuffer::createTexImage2D(box3d::Application& app) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, app.GetWindow().GetWidth(), app.GetWindow().GetHeight(), 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); } void TextureBuffer::setTextureAtributes() { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void TextureBuffer::bind() const { glBindTexture(GL_TEXTURE_2D, this->m_rendererID); } void TextureBuffer::unbind() const { glBindTexture(GL_TEXTURE_2D, 0); } }
23.051282
139
0.668521
Campeanu
610f458c09000c569e26b8984cdb126628f11bb9
4,459
hpp
C++
src/3rd party/boost/boost/python/object/inheritance.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/boost/boost/python/object/inheritance.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/boost/boost/python/object/inheritance.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Copyright David Abrahams 2002. Permission to copy, use, // modify, sell and distribute this software is granted provided this // copyright notice appears in all copies. This software is provided // "as is" without express or implied warranty, and with no claim as // to its suitability for any purpose. #ifndef INHERITANCE_DWA200216_HPP # define INHERITANCE_DWA200216_HPP # include <boost/python/type_id.hpp> # include <boost/shared_ptr.hpp> # include <boost/mpl/if.hpp> # include <boost/type_traits/object_traits.hpp> # include <boost/type_traits/is_polymorphic.hpp> # include <boost/detail/workaround.hpp> namespace boost { namespace python { namespace objects { typedef type_info class_id; using python::type_id; // Types used to get address and id of most derived type typedef std::pair<void*,class_id> dynamic_id_t; typedef dynamic_id_t (*dynamic_id_function)(void*); BOOST_PYTHON_DECL void register_dynamic_id_aux( class_id static_id, dynamic_id_function get_dynamic_id); BOOST_PYTHON_DECL void add_cast( class_id src_t, class_id dst_t, void* (*cast)(void*), bool polymorphic); BOOST_PYTHON_DECL void* find_static_type(void* p, class_id src, class_id dst); BOOST_PYTHON_DECL void* find_dynamic_type(void* p, class_id src, class_id dst); // // a generator with an execute() function which, given a source type // and a pointer to an object of that type, returns its most-derived // /reachable/ type identifier and object pointer. // // first, the case where T has virtual functions template <class T> struct polymorphic_id_generator { static dynamic_id_t execute(void* p_) { T* p = static_cast<T*>(p_); return std::make_pair(dynamic_cast<void*>(p), class_id(typeid(*p))); } }; // now, the non-polymorphic case. template <class T> struct non_polymorphic_id_generator { static dynamic_id_t execute(void* p_) { return std::make_pair(p_, python::type_id<T>()); } }; // Now the generalized selector template <class T> struct dynamic_id_generator { typedef typename mpl::if_c< is_polymorphic<T>::value , polymorphic_id_generator<T> , non_polymorphic_id_generator<T> >::type type; }; // Register the dynamic id function for T with the type-conversion // system. template <class T> void register_dynamic_id(T* = 0) { typedef typename dynamic_id_generator<T>::type generator; register_dynamic_id_aux( python::type_id<T>(), &generator::execute); } // // a generator with an execute() function which, given a void* // pointing to an object of type Source will attempt to convert it to // an object of type Target. // template <class Source, class Target> struct dynamic_cast_generator { static void* execute(void* source) { return dynamic_cast<Target*>( static_cast<Source*>(source)); } }; template <class Source, class Target> struct implicit_cast_generator { static void* execute(void* source) { Target* result = static_cast<Source*>(source); return result; } }; template <class Source, class Target> struct cast_generator { // It's OK to return false, since we can always cast up with // dynamic_cast<> if neccessary. # if BOOST_WORKAROUND(__MWERKS__, <= 0x2407) BOOST_STATIC_CONSTANT(bool, is_upcast = false); # else BOOST_STATIC_CONSTANT( bool, is_upcast = ( is_base_and_derived<Target,Source>::value )); # endif typedef typename mpl::if_c< is_upcast # if BOOST_WORKAROUND(__MWERKS__, <= 0x2407) // grab a few more implicit_cast cases for CodeWarrior || !is_polymorphic<Source>::value || !is_polymorphic<Target>::value # endif , implicit_cast_generator<Source,Target> , dynamic_cast_generator<Source,Target> >::type type; }; template <class Source, class Target> inline void register_conversion( // We need this parameter because CWPro7 can't determine // which is the base reliably. bool is_downcast = !cast_generator<Source,Target>::is_upcast // These parameters shouldn't be used, they're an MSVC bug workaround , Source* = 0, Target* = 0) { typedef typename cast_generator<Source,Target>::type generator; add_cast(python::type_id<Source>() , python::type_id<Target>() , &generator::execute , is_downcast); } }}} // namespace boost::python::object #endif // INHERITANCE_DWA200216_HPP
28.767742
79
0.705539
OLR-xray
611314e88ba3e5f3b90ccc91ccf45e4fadfa70d0
9,694
cpp
C++
src/MainBackTracking.cpp
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
1
2020-10-25T07:14:48.000Z
2020-10-25T07:14:48.000Z
src/MainBackTracking.cpp
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
null
null
null
src/MainBackTracking.cpp
DarioDaF/ASS_TOP
0438a3deb9ca3b906c4cd7a923c598a7786fe4ec
[ "CC-BY-4.0" ]
2
2020-10-02T12:24:38.000Z
2020-10-25T07:00:24.000Z
#include <fstream> #include <sstream> #include <filesystem> #include <string> #include <algorithm> #include <vector> #include "backTracking/TOP_Backtracking.hpp" #include "greedy/GreedyPaths.hpp" using namespace std; namespace fs = std::filesystem; /** * Struct that represent Chao's results */ struct chaoResults { string file; double chaoOptimum; }; /** * MainBackTracking.cpp is a main that takes all the instances and solve them with the backtracking algorithm. Bacause * of the long time that takes the backtracking, it is possible to set a maxTime limit that it takes to resolve * each instance (default value 3 minutes). The main perform a metaheuristic backtracking because it use the greedy * algorithm (with its parameter maxDeviation) plus some other solutions built to solve the TOP problem. * the solution are compared with Chao's ones to evaluate the performance and the resoluts of the backtracking algorithm. * All the outputs are saved in different files to sum up the information and the outputs from which it is obtained * the best optimum. * * Input file: * paramTimeBt.txt : file in which are contained tthe max time permitted to execute the backtracking algorithm * on each instance, expressed in second. * Mandatory info: time for each instance. If not provided, default at 3 minutes. * The file is located in "parametes_in" directory. * * chaoResults.txt : file in which are contained Chao's results, used to compare greedy scores whith Chao's ones. * The file is located in "parametes_in" directory. * * "instances" files : files that contain the instances to solve. * The files are located in "instances" directory. * * Output files: * SolBacktracking.csv : file in which it is saved for each instance the algorithm results and the comparison whith chao's one. * The file is located in "solutions" directory. * * "outputs/backtracking/[#]" files : for all the instances, it is saved a file which contain the input and the output in standard * form. Some useful information as the path, the hop and the score obtained are provided. * The file are located in "outputs/backtracking/[#]" directory. * * "outputs/routeHops/backtarcking/[#]" files : for all the instances it is saved the solution obtained if hops form to read and use * it in the resolution of other algortims (i.e. Local Search). * The files are located in "outputs/routeHops/backtracking/[#]" directory. * * Usage: * ./MainBackT.exe [version of algorithm] * - version : * 1 : if with default parameters * 2 : if with parameters readed by Greedy output files * * @param argc number of items in the command line * @param argv items in the command line * @return resolve all the instances and print outputs and parameters in files */ int main(int argc, char* argv[]) { double maxTime = 3.0 * 60.0; // Default Time limit: 3 minutes int errors = 0, cnt_istances = 0; bool timeDefault = false; vector<chaoResults> chaoRes; string line; if (argc < 1) { cerr << argc << " ERROR: insert Backtracking algorithm's version [#1 or #2]" << endl; return 1; } //Open the file conteining the max time for execute the program for each instance ifstream paramTime("./paramIn/paramTimeBt.txt"); if (!paramTime) { cerr << " ERROR: Unable to open MaxTime file" << endl; timeDefault = true; } if(!timeDefault) { while(getline(paramTime, line)) { std::istringstream iss(line); //Split the input string std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); if (results[0] == "timeMax") { maxTime = stod(results[1]); } else { continue; } } paramTime.close(); } cout << "LOG: timeMax limit set to " << maxTime << "s" << endl; //Open and read the file of Chao's results ifstream optStream("./paramIn/chaoResults.txt"); if (!optStream) { throw runtime_error(" ERROR: Unable to open Chao's file"); } // Read all the lines into chao's file while(getline(optStream, line)) { std::istringstream iss(line); //Split the input string std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); chaoRes.push_back({.file = results[0], .chaoOptimum = stod(results[1])}); //Populate the vector of chao's results } optStream.close(); //Open and write the file of results for each instance fs::create_directories("solutions"); string titleFile = "solutions/SolBacktracking#"; titleFile.push_back(*argv[1]); ofstream solutionsStream(titleFile + ".csv"); if(!solutionsStream) { throw runtime_error(" ERROR: Unable to open Solution file"); } if(*argv[1] == '2') { solutionsStream << "# TimeMax limit set to " << maxTime << "s [Custom parameters] " << endl; } else { solutionsStream << "# TimeMax limit set to " << maxTime << "s [Default parameters] " << endl; } for (const auto &file : fs::directory_iterator("./instances")) { //For each instance TOP_Input in; string line; // Default weight parameters double wProfit = 1.1; double wTime = 0.7; double maxDeviation = 1.5; // Max deviation admitted to the path double wNonCost = 0.0; if (file.path().extension() != ".txt") continue; cerr << "Processing: " << file.path().filename() << endl; { ifstream is(file.path()); if (!is) { ++errors; cerr << " ERROR: Unable to open Instance file" << endl; continue; } is >> in; in.name = file.path().filename().replace_extension("").string(); } if(*argv[1] == '2') { // Second version without greedy parameters, otherwise with default parameters //Open the file conteining the params // If found param, set it, otherwise use default value ifstream paramStream(GetGreedyBestParamsPath(in.name)); if (!paramStream) { throw runtime_error("ERROR: Cannot find Greedy parameter file: run Greedy algorithm or use default parameters"); } while(getline(paramStream, line)) { std::istringstream iss(line); //Split the input string std::vector<string> results(std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>()); if (results[0] == "Profit") { // Skip first line continue; } if (results[2] == "null") { // Default parameters break; } if(results[1] == "wProfit:") { wProfit = stod(results[2]); } else if(results[1] == "wTime:") { wTime = stod(results[2]); } else if(results[1] == "maxDeviation:") { maxDeviation = stod(results[2]); } else if(results[1] == "wNonCost:") { wNonCost = stod(results[2]); } } paramStream.close(); } cerr << "LOG: param <" << wProfit << "; " << wTime << "; " << maxDeviation << "; " << wNonCost << ">" << endl; TOP_Walker tw(in, wProfit, wTime, maxDeviation, wNonCost, 0); TOP_Checker ck; Backtrack(tw, ck, maxTime); { // Print the output string titleDir = "outputs/backtracking/#"; titleDir.push_back(*argv[1]); fs::create_directories(titleDir); std::ofstream os(titleDir / file.path().filename().replace_extension(".out")); if (!os) { ++errors; std::cerr << " ERROR: Unable to open output file" << std::endl; continue; } if (ck.GetBestCost() == 0) { os << in; os << "h 0"; } else { os << in << ck.GetBest(); } } { string titleDir = "outputs/routeHops/backtracking/#"; titleDir.push_back(*argv[1]); fs::create_directories(titleDir); std::ofstream os(titleDir / file.path().filename().replace_extension(".out")); if (!os) { ++errors; std::cerr << " ERROR: Unable to open output file" << std::endl; continue; } if (ck.GetBestCost() == 0) { os << in; os << "h 0"; } else { os << ck.GetBest(); } } // Print a ".csv" file with all the scores if(chaoRes[cnt_istances].file == file.path().filename()) { // Compare with Chao if(chaoRes[cnt_istances].chaoOptimum == -ck.GetBestCost()) { solutionsStream << file.path().filename() << "," << chaoRes[cnt_istances].chaoOptimum << "," << -ck.GetBestCost() << "," << 1.0 << endl; ++cnt_istances; continue; } solutionsStream << file.path().filename() << "," << chaoRes[cnt_istances].chaoOptimum << "," << -ck.GetBestCost() << "," << -ck.GetBestCost() / chaoRes[cnt_istances].chaoOptimum << endl; ++cnt_istances; } else { // New map found solutionsStream << file.path().filename() << "," << -ck.GetBestCost() << "," << "(new map)" << endl; } } solutionsStream.close(); return 0; }
37.573643
136
0.583454
DarioDaF
61141b5b467eae9d8a3d1dac9687fe78e6c2a95b
3,214
cpp
C++
isaac_variant_caller/src/lib/blt_util/istream_line_splitter.cpp
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
21
2015-01-09T01:11:28.000Z
2019-09-04T03:48:21.000Z
isaac_variant_caller/src/lib/blt_util/istream_line_splitter.cpp
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
4
2015-07-23T09:38:39.000Z
2018-02-01T05:37:26.000Z
isaac_variant_caller/src/lib/blt_util/istream_line_splitter.cpp
sequencing/isaac_variant_caller
ed24e20b097ee04629f61014d3b81a6ea902c66b
[ "BSL-1.0" ]
13
2015-01-29T16:41:26.000Z
2021-06-25T02:42:32.000Z
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Copyright (c) 2009-2013 Illumina, Inc. // // This software is provided under the terms and conditions of the // Illumina Open Source Software License 1. // // You should have received a copy of the Illumina Open Source // Software License 1 along with this program. If not, see // <https://github.com/sequencing/licenses/> // /// \file /// /// an efficient (and slightly unsafe) class for basic tab-delimited files, etc... /// /// \author Chris Saunders /// #include "blt_util/blt_exception.hh" #include "blt_util/istream_line_splitter.hh" #include <cassert> #include <cstring> #include <iostream> #include <sstream> void istream_line_splitter:: write_line(std::ostream& os) const { for (unsigned i(0); i<_n_word; ++i) { if (i) os << _sep; os << word[i]; } os << "\n"; } void istream_line_splitter:: dump(std::ostream& os) const { os << "\tline_no: " << _line_no << "\n"; os << "\tline: "; write_line(os); } void istream_line_splitter:: increase_buffer_size() { assert(_buf_size>1); const unsigned old_buf_size(_buf_size); const char* old_buf(_buf); _buf_size *= 2; _buf=new char[_buf_size]; memcpy(_buf,old_buf,(old_buf_size-1)*sizeof(char)); delete [] old_buf; } static bool check_istream(std::istream& is, unsigned& line_no) { if (is) { line_no++; // regular successful line read: return true; } if (is.eof()) return false; else if (is.fail()) { if (is.bad()) { std::ostringstream oss; oss << "ERROR: unexpected failure while attempting to read line " << (line_no+1) << "\n"; throw blt_exception(oss.str().c_str()); } is.clear(); } // incomplete line read in this case, have to increase buffer size: return true; } bool istream_line_splitter:: parse_line() { _n_word=0; _is.getline(_buf,_buf_size); const unsigned previous_line_no(_line_no); if (! check_istream(_is,_line_no)) return false; // normal eof unsigned buflen(strlen(_buf)); while (((buflen+1) == _buf_size) && (previous_line_no==_line_no)) { increase_buffer_size(); _is.getline(_buf+buflen,_buf_size-buflen); if (! check_istream(_is,_line_no)) { std::ostringstream oss; oss << "ERROR: Unexpected read failure in parse_line() at line_no: " << _line_no << "\n"; throw blt_exception(oss.str().c_str()); } buflen=(strlen(_buf)); } if ((buflen+1) >_buf_size) { std::ostringstream oss; oss << "ERROR: Unexpected read failure in parse_line() at line_no: " << _line_no << "\n"; throw blt_exception(oss.str().c_str()); } if (NULL == _buf) return false; assert(buflen); // do a low-level separator parse: { char* p(_buf); word[0]=p; unsigned i(1); while (i<_max_word) { if ((*p == '\n') || (*p == '\0')) break; if (*p == _sep) { *p = '\0'; word[i++] = p+1; } ++p; } _n_word=i; } return true; }
22.633803
101
0.574673
sequencing
61156337b8c0e2c4f61baf2c1ed44e0641c7cc21
7,791
hpp
C++
src/Engine/Renderer/RenderTechnique/RenderTechnique.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
src/Engine/Renderer/RenderTechnique/RenderTechnique.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
src/Engine/Renderer/RenderTechnique/RenderTechnique.hpp
nmellado/Radium-Engine
6e42e4be8d14bcd496371a5f58d483f7d03f9cf4
[ "Apache-2.0" ]
null
null
null
#ifndef RADIUMENGINE_RENDERTECHNIQUE_HPP #define RADIUMENGINE_RENDERTECHNIQUE_HPP #include <Engine/RaEngine.hpp> #include <Engine/Renderer/RenderTechnique/ShaderConfiguration.hpp> #include <memory> #include <map> #include <functional> namespace Ra { namespace Engine { class ShaderProgram; class Material; } } namespace Ra { namespace Engine { // TODO (Mathias) : Adapt RenderTechnique for multi-material purpose // TODO transform the folowing ideas and insight into a real doc ... // --> Interface that must be implemented by a RenderTechnique // --> depthAmbiant Pass // This pass must compute the Z of each Fragment and, optionally, the ambiant term // (see DepthAmbiantPass shader of Forward Renderer) // --> opaqueLighting Pass // This pass must compute the lighting of the opaque aspect of the material // (see BlinnPhong shader of Forward Renderer) // --> transparentLighting Pass // This pass must compute the lighting of the transparent aspect of the material // (see LitOIT shader of Forward Renderer) // // --> modify RenderObject so that it is able to activate the required technique for rendering // This is done but not yet finalized ... main rendering (internal render) is fixed, secondary renderings (ui, // debug, ...) still have the possibilities to bypass the notion of Technique" // // A RenderTechnique correspond to a set shader configuration allowing to manage a Material while rendering. // The set of configurations must contains what is required to render objects in the following ways : // 1- depth and ambiant-environment lighting : // Required for the depth pre-pass of several renderers. // Must initialise the color. Initialization at 0 or to the base color of the fragments resulting from // ambiant-Environment lighting // * Default/Reference : DepthAmbiantPass shaders // 2- Opaque lighting : THIS ONE IS MANDATORY, EACH MATERIAL MUST AT LEAST BE RENDERABLE AS OPAQUE OBJECT // Main configuration, computes the resluting color according to a lighting configuration. // The lighting configuration might contains one or severa sources of different types. // * Default/Reference : BlinnPhong shaders // 3- Transparent lighting : // Same as opaque lighting but for transparent objects // * Default/Reference LitOIT shaders // 4- WhatElse ???? // /* Exemple of use from Forward Renderer * * depthAmbiant pass * Build a RenderParameters object defining the ambiant lighting configuration (envmap or irradiancemap or * constant factor of base color. * for each RenderObject * call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_DEPTH_AMBIANT); * * opaqueLighting pass : * For each light sources set (from 1 to N light sources) * Build a RenderParameters object defining the lighting configuration. * For each RenderObject * call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_LIGHT_OPAQUE); * * transparentLighting pass * For each light sources set (from 1 to N light sources) * Build a RenderParameters object defining the lighting configuration. * For each RenderObject * call ro->render(ambiantLigthingPtarams, renderData(stange name for matrices + time), TECHNIQUE_LIGHT_TRANSPARENT); * * Each technique must be configured with its own shaders. * * TODO : Default rendertechnique must be renderer dependant ... */ class RA_ENGINE_API RenderTechnique { public: enum PassName { Z_PREPASS = 1 << 0, LIGHTING_OPAQUE = 1 << 1, LIGHTING_TRANSPARENT = 1 << 2, NO_PASS = 0 }; RenderTechnique(); RenderTechnique(const RenderTechnique &); ~RenderTechnique(); void setConfiguration(const ShaderConfiguration &newConfig, PassName pass = LIGHTING_OPAQUE); // TODO : do we need all the config or only the basic part ? ShaderConfiguration getConfiguration(PassName pass = LIGHTING_OPAQUE) const; const ShaderProgram *getShader(PassName pass = LIGHTING_OPAQUE) const; void setMaterial(const std::shared_ptr<Material> &material); const std::shared_ptr<Material> &getMaterial() const; void resetMaterial(Material *mat); void updateGL(); bool shaderIsDirty(PassName pass = LIGHTING_OPAQUE) const; // creates a Radium default rendertechnique : // Z_PREPASS = DepthDepthAmbientPass // LIGHTING_OPAQUE = BlinnPhong // LIGHTING_TRANSPARENT = LitOIT static Ra::Engine::RenderTechnique createDefaultRenderTechnique(); private: using ConfigurationSet = std::map<PassName, ShaderConfiguration>; using ShaderSet = std::map<PassName, const ShaderProgram *>; ConfigurationSet shaderConfig; ShaderSet shaders; std::shared_ptr<Material> material = nullptr; // Change this if there is more than 8 configurations unsigned char dirtyBits = (Z_PREPASS | LIGHTING_OPAQUE | LIGHTING_TRANSPARENT); unsigned char setPasses = NO_PASS; }; /////////////////////////////////////////////// //// Radium defined technique /// /////////////////////////////////////////////// namespace EngineRenderTechniques { // A default technique function is a function that will fill the given RenderTEchnique with the default // configurations associated with a material using DefaultTechniqueBuilder = std::function<void(RenderTechnique &, bool)>; /** register a new default builder for a technique * @return true if builder added, false else (e.g, a builder with the same name exists) */ RA_ENGINE_API bool registerDefaultTechnique(const std::string &name, DefaultTechniqueBuilder builder); /** remove a default builder * @return true if builder removed, false else (e.g, a builder with the same name does't exists) */ RA_ENGINE_API bool removeDefaultTechnique(const std::string &name); /** * @param name name of the technique to construct * @return a pair containing the search result and, if true, the functor to call to build the technique. */ RA_ENGINE_API std::pair<bool, DefaultTechniqueBuilder> getDefaultTechnique(const std::string &name); } } // namespace Engine } // namespace Ra #endif // RADIUMENGINE_RENDERTECHNIQUE_HPP
48.391304
139
0.583237
nmellado
61181e255dba50705ff9e8c1f1abbb38f943af9f
3,091
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcBoundaryCurve.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcBoundaryCurve.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/lib/IfcBoundaryCurve.cpp
promethe42/ifcplusplus
1c8b51b1f870f0107538dbea5eaa2755c81f5dca
[ "MIT" ]
null
null
null
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include <sstream> #include <limits> #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4/include/IfcBoundaryCurve.h" #include "ifcpp/IFC4/include/IfcCompositeCurveSegment.h" #include "ifcpp/IFC4/include/IfcLogical.h" #include "ifcpp/IFC4/include/IfcPresentationLayerAssignment.h" #include "ifcpp/IFC4/include/IfcStyledItem.h" // ENTITY IfcBoundaryCurve IfcBoundaryCurve::IfcBoundaryCurve() {} IfcBoundaryCurve::IfcBoundaryCurve( int id ) { m_entity_id = id; } IfcBoundaryCurve::~IfcBoundaryCurve() {} shared_ptr<BuildingObject> IfcBoundaryCurve::getDeepCopy( BuildingCopyOptions& options ) { shared_ptr<IfcBoundaryCurve> copy_self( new IfcBoundaryCurve() ); for( size_t ii=0; ii<m_Segments.size(); ++ii ) { auto item_ii = m_Segments[ii]; if( item_ii ) { copy_self->m_Segments.push_back( dynamic_pointer_cast<IfcCompositeCurveSegment>(item_ii->getDeepCopy(options) ) ); } } if( m_SelfIntersect ) { copy_self->m_SelfIntersect = dynamic_pointer_cast<IfcLogical>( m_SelfIntersect->getDeepCopy(options) ); } return copy_self; } void IfcBoundaryCurve::getStepLine( std::stringstream& stream ) const { stream << "#" << m_entity_id << "= IFCBOUNDARYCURVE" << "("; writeEntityList( stream, m_Segments ); stream << ","; if( m_SelfIntersect ) { m_SelfIntersect->getStepParameter( stream ); } else { stream << "$"; } stream << ");"; } void IfcBoundaryCurve::getStepParameter( std::stringstream& stream, bool ) const { stream << "#" << m_entity_id; } const std::wstring IfcBoundaryCurve::toString() const { return L"IfcBoundaryCurve"; } void IfcBoundaryCurve::readStepArguments( const std::vector<std::wstring>& args, const std::map<int,shared_ptr<BuildingEntity> >& map ) { const size_t num_args = args.size(); if( num_args != 2 ){ std::stringstream err; err << "Wrong parameter count for entity IfcBoundaryCurve, expecting 2, having " << num_args << ". Entity ID: " << m_entity_id << std::endl; throw BuildingException( err.str().c_str() ); } readEntityReferenceList( args[0], m_Segments, map ); m_SelfIntersect = IfcLogical::createObjectFromSTEP( args[1], map ); } void IfcBoundaryCurve::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IfcCompositeCurveOnSurface::getAttributes( vec_attributes ); } void IfcBoundaryCurve::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IfcCompositeCurveOnSurface::getAttributesInverse( vec_attributes_inverse ); } void IfcBoundaryCurve::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcCompositeCurveOnSurface::setInverseCounterparts( ptr_self_entity ); } void IfcBoundaryCurve::unlinkFromInverseCounterparts() { IfcCompositeCurveOnSurface::unlinkFromInverseCounterparts(); }
46.134328
234
0.748302
promethe42
611bac00a3264f6058c1cfbcd0fac6fd9a2e3fd0
3,191
cc
C++
app_ipc_scheduler/shm_sem.cc
xyyeh/Cpp_tutorials
cb5c750a61013d252e1a7e53100690315bfa931b
[ "Unlicense" ]
1
2019-12-04T06:03:10.000Z
2019-12-04T06:03:10.000Z
app_ipc_scheduler/shm_sem.cc
xyyeh/cpp_tutorials
cb5c750a61013d252e1a7e53100690315bfa931b
[ "Unlicense" ]
null
null
null
app_ipc_scheduler/shm_sem.cc
xyyeh/cpp_tutorials
cb5c750a61013d252e1a7e53100690315bfa931b
[ "Unlicense" ]
null
null
null
#include "shm_sem.h" #include <errno.h> #include <sys/mman.h> #include <sys/types.h> #include <unistd.h> #include <cstdio> #include <cstdlib> #include <iostream> const std::string ShmSemaphore::sLockSemaphoreName = "/semaphoreInit"; ShmSemaphore::ShmSemaphore(const std::string& sName) : name_(sName), ptr_(nullptr), shm_id_(-1), sem_id_(nullptr), size_(0) { /** * Semaphore open */ sem_id_ = sem_open(sLockSemaphoreName.c_str(), O_CREAT, S_IRUSR | S_IWUSR, 1); } bool ShmSemaphore::Create(size_t nSize, int mode /*= READ_WRITE*/) { size_ = nSize; shm_id_ = shm_open(name_.c_str(), O_CREAT | mode, 0666); if (shm_id_ < 0) { switch (errno) { case EACCES: throw ShmException("Permission Exception "); break; case EEXIST: throw ShmException( "Shared memory object specified by name already exists."); break; case EINVAL: throw ShmException("Invalid shared memory name passed."); break; case EMFILE: throw ShmException( "The process already has the maximum number of files open."); break; case ENAMETOOLONG: throw ShmException("The length of name exceeds PATH_MAX."); break; case ENFILE: throw ShmException( "The limit on the total number of files open on the system has " "been reached"); break; default: throw ShmException( "Invalid exception occurred in shared memory creation"); break; } } /* adjusting mapped file size (make room for the whole segment to map) -- * ftruncate() */ ftruncate(shm_id_, size_); return true; } bool ShmSemaphore::Attach(int mode /*= A_READ | A_WRITE*/) { /* requesting the shared segment -- mmap() */ ptr_ = mmap(NULL, size_, mode, MAP_SHARED, shm_id_, 0); if (ptr_ == nullptr) { throw ShmException("Exception in attaching the shared memory region"); } return true; } bool ShmSemaphore::Detach() { munmap(ptr_, size_); } bool ShmSemaphore::Lock() { sem_wait(sem_id_); } bool ShmSemaphore::Trylock() { return (sem_trywait(sem_id_) == 0); } bool ShmSemaphore::Unlock() { return (sem_post(sem_id_) == 0); } bool ShmSemaphore::UnlockSingle() { int sem_val; if (sem_getvalue(sem_id_, &sem_val) == 0) { if (sem_val == 0) { return (sem_post(sem_id_) == 0); } else { return false; } } return false; } ShmSemaphore::~ShmSemaphore() { Clear(); } void ShmSemaphore::Clear() { if (shm_id_ != -1) { if (shm_unlink(name_.c_str()) < 0) { perror("shm_unlink"); } } /** * Semaphore unlink: Remove a named semaphore from the system. */ if (sem_id_ != NULL) { /** * Semaphore Close: Close a named semaphore */ if (sem_close(sem_id_) < 0) { perror("sem_close"); } /** * Semaphore unlink: Remove a named semaphore from the system. */ if (sem_unlink(sLockSemaphoreName.c_str()) < 0) { perror("sem_unlink"); } } } ShmException::ShmException(const std::string& message, bool bSysMsg /*= false*/) throw() {} ShmException::~ShmException() throw() {}
26.371901
80
0.614854
xyyeh
6120212e344a69fbb446a123d1d724c58b9aae7b
4,487
cpp
C++
src/3rdparty/opennurbs/opennurbs_sum.cpp
ouxianghui/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
12
2021-03-26T03:23:30.000Z
2021-12-31T10:05:44.000Z
src/3rdparty/opennurbs/opennurbs_sum.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
null
null
null
src/3rdparty/opennurbs/opennurbs_sum.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
9
2021-06-23T08:26:40.000Z
2022-01-20T07:18:10.000Z
/* $NoKeywords: $ */ /* // // Copyright (c) 1993-2007 Robert McNeel & Associates. All rights reserved. // Rhinoceros is a registered trademark of Robert McNeel & Assoicates. // // THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. // ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF // MERCHANTABILITY ARE HEREBY DISCLAIMED. // // For complete openNURBS copyright information see <http://www.opennurbs.org>. // //////////////////////////////////////////////////////////////// */ #include "opennurbs.h" ON_Sum::ON_Sum() { Begin(0.0); } int ON_Sum::SummandCount() const { return m_pos_count + m_neg_count + m_zero_count; } void ON_Sum::Begin( double starting_value ) { m_sum_err = 0.0; m_pos_sum = 0.0; m_neg_sum = 0.0; m_pos_sum1_count = 0; m_pos_sum2_count = 0; m_pos_sum3_count = 0; m_neg_sum1_count = 0; m_neg_sum2_count = 0; m_neg_sum3_count = 0; m_pos_count = 0; m_neg_count = 0; m_zero_count = 0; if ( starting_value > 0.0 ) { m_pos_sum = starting_value; } else if ( starting_value < 0.0 ) { m_neg_sum = starting_value; } } double ON_Sum::SortAndSum( int count, double* a ) { // note that the arrays passed to ON_Sum::SortAndSum() are all // homogeneous in sign double s = 0.0; if ( count > 0 ) { if ( count >= 2 ) { ON_SortDoubleArray( ON::quick_sort, a, count ); //double a0 = fabs(a[0]); //double a1 = fabs(a[count-1]); m_sum_err += ON_EPSILON*( fabs(a[count-1]) + count*fabs(a[0]) ); } if ( a[count] < 0.0 ) { a += count-1; while (count--) s += *a--; } else { while (count--) s += *a++; } } return s; } void ON_Sum::Plus( double x ) { if (x > 0.0) { m_pos_count++; m_pos_sum1[m_pos_sum1_count++] = x; if ( m_pos_sum1_count == sum1_max_count ) { m_pos_sum2[m_pos_sum2_count++] = SortAndSum( m_pos_sum1_count, m_pos_sum1 ); m_pos_sum1_count = 0; if ( m_pos_sum2_count == sum2_max_count ) { m_pos_sum3[m_pos_sum3_count++] = SortAndSum( m_pos_sum2_count, m_pos_sum2 ); m_pos_sum2_count = 0; if ( m_pos_sum3_count == sum3_max_count ) { x = SortAndSum( m_pos_sum3_count, m_pos_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_pos_sum) ); m_pos_sum += x; m_pos_sum3_count = 0; } } } } else if ( x < 0.0 ) { m_neg_count++; m_neg_sum1[m_neg_sum1_count++] = x; if ( m_neg_sum1_count == sum1_max_count ) { m_neg_sum2[m_neg_sum2_count++] = SortAndSum( m_neg_sum1_count, m_neg_sum1 ); m_neg_sum1_count = 0; if ( m_neg_sum2_count == sum2_max_count ) { m_neg_sum3[m_neg_sum3_count++] = SortAndSum( m_neg_sum2_count, m_neg_sum2 ); m_neg_sum2_count = 0; if ( m_neg_sum3_count == sum3_max_count ) { x = SortAndSum( m_neg_sum3_count, m_neg_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_neg_sum) ); m_neg_sum += x; m_neg_sum3_count = 0; } } } } else m_zero_count++; } void ON_Sum::operator=(double x) { Begin(x); } void ON_Sum::operator+=(double x) { Plus(x); } void ON_Sum::operator-=(double x) { Plus(-x); } double ON_Sum::Total( double* error_estimate ) { double x; if ( m_pos_sum1_count > 0 ) { m_pos_sum2[m_pos_sum2_count++] = SortAndSum( m_pos_sum1_count, m_pos_sum1 ); m_pos_sum1_count = 0; } if ( m_pos_sum2_count > 0 ) { m_pos_sum3[m_pos_sum3_count++] = SortAndSum( m_pos_sum2_count, m_pos_sum2 ); m_pos_sum2_count = 0; } if ( m_pos_sum3_count > 0 ) { x = SortAndSum( m_pos_sum3_count, m_pos_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_pos_sum) ); m_pos_sum += x; m_pos_sum3_count = 0; } if ( m_neg_sum1_count > 0 ) { m_neg_sum2[m_neg_sum2_count++] = SortAndSum( m_neg_sum1_count, m_neg_sum1 ); m_neg_sum1_count = 0; } if ( m_neg_sum2_count > 0 ) { m_neg_sum3[m_neg_sum3_count++] = SortAndSum( m_neg_sum2_count, m_neg_sum2 ); m_neg_sum2_count = 0; } if ( m_neg_sum3_count > 0 ) { x = SortAndSum( m_neg_sum3_count, m_neg_sum3 ); m_sum_err += ON_EPSILON*( fabs(x) + fabs(m_neg_sum) ); m_neg_sum += x; m_neg_sum3_count = 0; } if ( error_estimate ) { *error_estimate = m_sum_err + ON_EPSILON*(fabs(m_pos_sum) + fabs(m_neg_sum)); } return m_pos_sum + m_neg_sum; }
22.77665
84
0.605973
ouxianghui