blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
5204c322f4636fddef30d1845d78d63d95970538
ea5bcc2d6464a35ccb7f93f4a5e2737141f0200f
/build-QtPetinator-Desktop_Qt_5_12_6_MSVC2017_32bit-Debug/debug/moc_winning.cpp
fdcb892a457e63ea659c6f2c2e6a1cb325bf923a
[]
no_license
krbroman/Petinator
d9f8858c5700d44064cfb3a6e8284693ae67e983
d43c21a4fca9ef2acc9b15136191541d31477a1f
refs/heads/master
2020-09-06T17:14:44.036691
2019-12-14T10:26:54
2019-12-14T10:26:54
220,488,469
2
0
null
2019-11-30T08:25:56
2019-11-08T14:54:57
C++
UTF-8
C++
false
false
3,591
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'winning.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.6) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../QtPetinator/winning.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'winning.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.12.6. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Winning_t { QByteArrayData data[4]; char stringdata0[63]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Winning_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Winning_t qt_meta_stringdata_Winning = { { QT_MOC_LITERAL(0, 0, 7), // "Winning" QT_MOC_LITERAL(1, 8, 26), // "on_pushButton_Exit_clicked" QT_MOC_LITERAL(2, 35, 0), // "" QT_MOC_LITERAL(3, 36, 26) // "on_pushButton_Play_clicked" }, "Winning\0on_pushButton_Exit_clicked\0\0" "on_pushButton_Play_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Winning[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 24, 2, 0x08 /* Private */, 3, 0, 25, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, 0 // eod }; void Winning::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<Winning *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_pushButton_Exit_clicked(); break; case 1: _t->on_pushButton_Play_clicked(); break; default: ; } } Q_UNUSED(_a); } QT_INIT_METAOBJECT const QMetaObject Winning::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_Winning.data, qt_meta_data_Winning, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *Winning::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Winning::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Winning.stringdata0)) return static_cast<void*>(this); return QDialog::qt_metacast(_clname); } int Winning::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "supermcguitarcraft@gmail.com" ]
supermcguitarcraft@gmail.com
ff77c3afb3baafcfcb09d06a5cef2e21f26de9aa
d2f8dcefc229806f8d5588866da21a80d11c382f
/BOJ/1012/main.cpp
e6df56f80f52e8747efdaf0fe183a5bb334973fd
[]
no_license
timel2ss/Problem-Solving
dda01c3412f84bf478aa28f31bfe097138855571
d86aa7b69ea6ed3328e1009ec018997fc0405e70
refs/heads/master
2023-08-04T05:05:40.831334
2021-09-17T06:44:43
2021-09-17T06:44:43
284,057,518
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
cpp
#include <iostream> using namespace std; int map[60][60]; int visit[60][60]; int M, N, K; int direction[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; int cnt = 0; void dfs(int x, int y) { visit[y][x] = 1; for(int i = 0; i < 4; i++) { int dx = x + direction[i][1]; int dy = y + direction[i][0]; if(0 <= dx && dx < M && 0 <= dy && dy < N && map[dy][dx] == 1 && visit[dy][dx] == 0) { dfs(dx, dy); } } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T; cin >> T; for(int i = 0; i < T; i++ ) { cin >> M >> N >> K; for(int j = 0; j < K; j++) { int X, Y; cin >> X >> Y; map[Y][X] = 1; } for(int a = 0; a < N; a++) { for(int b = 0; b < M; b++) { if(map[a][b] == 1 && visit[a][b] == 0) { dfs(b, a); cnt++; } } } cout << cnt << "\n"; for(int k = 0; k < N; k++) { for(int l = 0; l < M; l++) { map[k][l] = 0; visit[k][l] = 0; } } cnt = 0; } return 0; }
[ "dyddn0823@hanyang.ac.kr" ]
dyddn0823@hanyang.ac.kr
9ec6954fd2b11e4879168aaa9796b4c04b5a111c
50231b5cd1fe157b75e8445aed86bf7cfb03c458
/src/utility/utility.hpp
0e0f0f6c78bc729534341fdb460395823325c1c3
[ "MIT" ]
permissive
blockspacer/std_ext
159b14731df1b98a31383dfd2513e147b5280d5b
d023719c2aa3947ff6bddb2c2294607d79e68099
refs/heads/master
2021-03-28T15:17:45.239777
2017-07-23T09:25:26
2017-07-23T09:25:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,872
hpp
#pragma once #include <type_traits> #include <functional> #include <utility> #include <cstddef> #include <tuple> namespace stdext { namespace details { /** \internal */ template< typename R, typename... A, std::size_t... I > constexpr auto func(std::integer_sequence<std::size_t, I...>) { static_assert((sizeof...(I)<=sizeof...(A)), "!"); return std::function<R(std::tuple_element_t<I, std::tuple<A...>>...)>{}; } } /** \brief Define a function type with limited arguments. * * Given a number of parameters \c N and a function type \c F, \c function_proxy * has a public member alias \c type equal to a function \c G that has the same * return type of \c F and \c N arguments having the same types of the first * \c N arguments of \c F. */ template<std::size_t, typename> struct function_proxy; /** \brief Define a function type with limited arguments. * * \sa function_proxy */ template<std::size_t N, typename R, typename... A> struct function_proxy<N, R(A...)> { using type = decltype(details::func<R, A...>(std::make_index_sequence<N>{})); static constexpr std::size_t Size = N; }; /** \brief Helper type template */ template<std::size_t N, typename F> using function_proxy_t = typename function_proxy<N, F>::type; /** \brief Helper type template */ template<typename T, typename U> struct types { using basic = T; using decorated = U; }; namespace details { /** \internal */ static constexpr std::size_t max_depth = 42; /** \internal */ template<std::size_t N> struct choice: choice<N-1> {}; /** \internal */ template<> struct choice<0> {}; /** \internal */ template<typename T, typename U> constexpr auto inherit_from(choice<0>) { return types<T, U>{}; } /** \internal */ template<typename T, typename U, typename = std::enable_if_t<std::is_pointer<T>::value>> constexpr auto inherit_from(choice<1>) { auto t = inherit_from<std::remove_pointer_t<T>, U>(choice<max_depth>{}); using B = typename decltype(t)::basic; using D = typename decltype(t)::decorated; return types<B, std::add_pointer_t<D>>{}; } /** \internal */ template<typename T, typename U, typename = std::enable_if_t<std::is_lvalue_reference<T>::value>> constexpr auto inherit_from(choice<2>) { auto t = inherit_from<std::remove_reference_t<T>, U>(choice<max_depth>{}); using B = typename decltype(t)::basic; using D = typename decltype(t)::decorated; return types<B, std::add_lvalue_reference_t<D>>{}; } /** \internal */ template<typename T, typename U, typename = std::enable_if_t<std::is_rvalue_reference<T>::value>> constexpr auto inherit_from(choice<3>) { auto t = inherit_from<std::remove_reference_t<T>, U>(choice<max_depth>{}); using B = typename decltype(t)::basic; using D = typename decltype(t)::decorated; return types<B, std::add_rvalue_reference_t<D>>{}; } /** \internal */ template<typename T, typename U, typename = std::enable_if_t<std::is_array<T>::value>> constexpr auto inherit_from(choice<4>) { auto t = inherit_from<std::remove_extent_t<T>, U>(choice<max_depth>{}); using B = typename decltype(t)::basic; using D = typename decltype(t)::decorated; return types<B, std::conditional_t<(0==std::extent<T>::value), D[], D[std::extent<T>::value]>>{}; } /** \internal */ template<typename T, typename U, typename = std::enable_if_t<std::is_const<T>::value>> constexpr auto inherit_from(choice<5>) { auto t = inherit_from<std::remove_const_t<T>, U>(choice<max_depth>{}); using B = typename decltype(t)::basic; using D = typename decltype(t)::decorated; return types<B, std::add_const_t<D>>{}; } /** \internal */ template<typename T, typename U, typename = std::enable_if_t<std::is_volatile<T>::value>> constexpr auto inherit_from(choice<6>) { auto t = inherit_from<std::remove_volatile_t<T>, U>(choice<max_depth>{}); using B = typename decltype(t)::basic; using D = typename decltype(t)::decorated; return types<B, std::add_volatile_t<D>>{}; } } /** \brief Inherit all the inheritable from one type. * * In this case, an example is worth a thousand words: * `inherit_from_t<const int ** const &&, char>` will return * `types<int, const char ** const &&>`.<br/> * That's all, pretty much. */ template<typename T, typename U = char> constexpr auto inherit_from() { return inherit_from<T, U>(details::choice<details::max_depth>{}); } /** \brief Helper type template */ template<typename T, typename U = char> using inherit_from_t = decltype(inherit_from<T, U>()); /** \brief Helper type template */ template<typename T, typename U = char> using inherit_from_basic_t = typename decltype(inherit_from<T, U>())::basic; /** \brief Helper type template */ template<typename T, typename U = char> using inherit_from_decorated_t = typename decltype(inherit_from<T, U>())::decorated; }
[ "michele.caini@gmail.com" ]
michele.caini@gmail.com
128ca34cc7639c8224a60d04f4838b5d780da12b
27b1be9ece5642f4c2d5b3930745508c2069888a
/src/tstools/tspOutputExecutor.cpp
3d560c41c0b98c560971a62fa6d982d88fc887e4
[ "BSD-2-Clause" ]
permissive
vacing/tsduck
26dbe9e0a39e6c15e0364d59433eec9466fef18b
ac01b88a8052419bfce9715886d597419fc5fef6
refs/heads/master
2020-11-30T00:57:35.128901
2019-12-20T22:34:25
2019-12-20T22:34:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,105
cpp
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2019, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // //---------------------------------------------------------------------------- // // Transport stream processor: Execution context of an output plugin // //---------------------------------------------------------------------------- #include "tspOutputExecutor.h" TSDUCK_SOURCE; //---------------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------------- ts::tsp::OutputExecutor::OutputExecutor(Options* options, const PluginOptions* pl_options, const ThreadAttributes& attributes, Mutex& global_mutex) : PluginExecutor(options, pl_options, attributes, global_mutex), _output(dynamic_cast<OutputPlugin*>(PluginThread::plugin())) { } //---------------------------------------------------------------------------- // Output plugin thread //---------------------------------------------------------------------------- void ts::tsp::OutputExecutor::main() { debug(u"output thread started"); PacketCounter output_packets = 0; bool aborted = false; do { // Wait for packets to output size_t pkt_first = 0; size_t pkt_cnt = 0; bool input_end = false; bool timeout = false; waitWork(pkt_first, pkt_cnt, _tsp_bitrate, input_end, aborted, timeout); // We ignore the returned "aborted" which comes from the "next" // processor in the chain, here the input thread. For the // output thread, aborted means was interrupted by user. aborted = _tsp_aborting; // Process restart requests. if (!processPendingRestart()) { timeout = true; } // In case of abort on timeout, notify previous and next plugin, then exit. if (timeout) { // Do not transmit bitrate or input end to next (since next is input processor). passPackets(0, 0, false, true); aborted = true; break; } // Exit thread if no more packet to process if ((pkt_cnt == 0 && input_end) || aborted) { break; } // Check if "joint termination" agreed on a last packet to output const PacketCounter jt_limit = totalPacketsBeforeJointTermination(); if (totalPacketsInThread() + pkt_cnt > jt_limit) { pkt_cnt = totalPacketsInThread() > jt_limit ? 0 : size_t (jt_limit - totalPacketsInThread()); aborted = true; } // Output the packets. Output may be segmented if dropped packets // (ie. starting with a zero byte) are in the middle of the buffer. TSPacket* pkt = _buffer->base() + pkt_first; TSPacketMetadata* data = _metadata->base() + pkt_first; size_t pkt_remain = pkt_cnt; while (pkt_remain > 0) { // Skip dropped packets size_t drop_cnt; for (drop_cnt = 0; drop_cnt < pkt_remain && pkt[drop_cnt].b[0] == 0; drop_cnt++) {} pkt += drop_cnt; data += drop_cnt; pkt_remain -= drop_cnt; addNonPluginPackets(drop_cnt); // Find last non-dropped packet size_t out_cnt = 0; while (out_cnt < pkt_remain && pkt[out_cnt].b[0] != 0) { out_cnt++; } // Output a contiguous range of non-dropped packets. if (out_cnt > 0) { if (_suspended) { // Don't output packet when the plugin is suspended. addNonPluginPackets(out_cnt); } else if (_output->send(pkt, data, out_cnt)) { // Packet successfully sent. addPluginPackets(out_cnt); output_packets += out_cnt; } else { // Send error. aborted = true; break; } pkt += out_cnt; data += out_cnt; pkt_remain -= out_cnt; } } // Pass free buffers to input processor. // Do not transmit bitrate or input end to next (since next is input processor). aborted = !passPackets(pkt_cnt, 0, false, aborted); } while (!aborted); // Close the output processor _output->stop(); debug(u"output thread %s after %'d packets (%'d output)", {aborted ? u"aborted" : u"terminated", totalPacketsInThread(), output_packets}); }
[ "thierry@lelegard.fr" ]
thierry@lelegard.fr
afd95077967ab37c8584cebf7da2d12f5f331f3d
622720ad50d5bcff717ec69317a450484f9a4c36
/Firmware/kl_lib/kl_i2c.cpp
169b3c806f16839363116902c76c7385a21e0add
[]
no_license
Kreyl/chibi-armlet
7fc881c92bc0788220fa51f5266b17ba7fc63071
a96a9a0572cc534b1a9ba0076914d08ab53627b7
refs/heads/master
2023-08-17T00:06:00.341425
2019-12-12T20:23:46
2019-12-12T20:23:46
33,041,077
0
5
null
null
null
null
UTF-8
C++
false
false
30,880
cpp
#include "uart.h" #include "kl_i2c.h" #if defined STM32L1XX || defined STM32F2XX || defined STM32F4XX #define I2C_DMATX_MODE(Chnl) \ STM32_DMA_CR_CHSEL(Chnl) | \ DMA_PRIORITY_LOW | \ STM32_DMA_CR_MSIZE_BYTE | \ STM32_DMA_CR_PSIZE_BYTE | \ STM32_DMA_CR_MINC | /* Memory pointer increase */ \ STM32_DMA_CR_DIR_M2P /* Direction is memory to peripheral */ \ | STM32_DMA_CR_TCIE #define I2C_DMARX_MODE(Chnl) \ STM32_DMA_CR_CHSEL(Chnl) | \ DMA_PRIORITY_LOW | \ STM32_DMA_CR_MSIZE_BYTE | \ STM32_DMA_CR_PSIZE_BYTE | \ STM32_DMA_CR_MINC | /* Memory pointer increase */ \ STM32_DMA_CR_DIR_P2M /* Direction is peripheral to memory */ \ | STM32_DMA_CR_TCIE #if defined STM32F2XX #define I2C1_DMA_CHNL 1 #define I2C2_DMA_CHNL 7 #define I2C3_DMA_CHNL 3 #endif #if I2C1_ENABLED static const i2cParams_t I2C1Params = { I2C1, I2C1_GPIO, I2C1_SCL, I2C1_SDA, I2C1_BAUDRATE, I2C1_DMA_TX, I2C1_DMA_RX, I2C_DMATX_MODE(I2C1_DMA_CHNL), I2C_DMARX_MODE(I2C1_DMA_CHNL) }; i2c_t i2c1 {&I2C1Params}; #endif #if I2C2_ENABLED static const i2cParams_t I2C2Params = { I2C2, I2C2_GPIO, I2C2_SCL, I2C2_SDA, I2C2_BAUDRATE, I2C2_DMA_TX, I2C2_DMA_RX, (I2C_DMATX_MODE(I2C2_DMA_CHNL)), (I2C_DMARX_MODE(I2C2_DMA_CHNL)) }; i2c_t i2c2 {&I2C2Params}; #endif extern "C" void i2cDmaIrqHandler(void *p, uint32_t flags) { chSysLockFromISR(); i2c_t *pi2c = (i2c_t*)p; chThdResumeI(&pi2c->ThdRef, (msg_t)0); chSysUnlockFromISR(); } void i2c_t::Init() { Standby(); Resume(); #if I2C_USE_SEMAPHORE chBSemObjectInit(&BSemaphore, NOT_TAKEN); #endif I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter // ==== DMA ==== PDmaTx = dmaStreamAlloc(PParams->DmaTxID, IRQ_PRIO_MEDIUM, i2cDmaIrqHandler, this); PDmaRx = dmaStreamAlloc(PParams->DmaRxID, IRQ_PRIO_MEDIUM, i2cDmaIrqHandler, this); dmaStreamSetPeripheral(PDmaTx, &pi2c->DR); dmaStreamSetPeripheral(PDmaRx, &pi2c->DR); } void i2c_t::Standby() { if(PParams->pi2c == I2C1) { rccResetI2C1(); rccDisableI2C1(); } #ifdef I2C2 else if(PParams->pi2c == I2C2) { rccResetI2C2(); rccDisableI2C2(); } #endif #if defined I2C3 else if (PParams->pi2c == I2C3) { rccResetI2C3(); rccDisableI2C3(); } #endif // Disable GPIOs PinSetupAnalog(PParams->PGpio, PParams->SclPin); PinSetupAnalog(PParams->PGpio, PParams->SdaPin); } void i2c_t::Resume() { Error = false; // ==== GPIOs ==== AlterFunc_t PinAF; #if defined STM32L1XX || defined STM32F2XX || defined STM32F4XX PinAF = AF4; // for all I2Cs everywhere #else #error "I2C AF not defined" #endif PinSetupAlterFunc(PParams->PGpio, PParams->SclPin, omOpenDrain, pudNone, PinAF); PinSetupAlterFunc(PParams->PGpio, PParams->SdaPin, omOpenDrain, pudNone, PinAF); // ==== Clock and reset ==== if(PParams->pi2c == I2C1) { rccEnableI2C1(FALSE); rccResetI2C1(); } #ifdef I2C2 else if (PParams->pi2c == I2C2) { rccEnableI2C2(FALSE); rccResetI2C2(); } #endif #ifdef I2C3 else if (PParams->pi2c == I2C3) { rccEnableI2C3(FALSE); rccResetI2C3(); } #endif // Minimum clock is 2 MHz uint32_t ClkMhz = Clk.APB1FreqHz / 1000000; uint16_t tmpreg = PParams->pi2c->CR2; tmpreg &= (uint16_t)~I2C_CR2_FREQ; if(ClkMhz < 2) ClkMhz = 2; if(ClkMhz > 32) ClkMhz = 32; tmpreg |= ClkMhz; PParams->pi2c->CR2 = tmpreg; PParams->pi2c->CR1 &= (uint16_t)~I2C_CR1_PE; // Disable i2c to setup TRise & CCR PParams->pi2c->TRISE = (uint16_t)(((ClkMhz * 300) / 1000) + 1); // 16/9 tmpreg = (uint16_t)(Clk.APB1FreqHz / (PParams->BitrateHz * 25)); if(tmpreg == 0) tmpreg = 1; // minimum allowed value tmpreg |= I2C_CCR_FS | I2C_CCR_DUTY; PParams->pi2c->CCR = tmpreg; PParams->pi2c->CR1 |= I2C_CR1_PE; // Enable i2c back // ==== DMA ==== PParams->pi2c->CR2 |= I2C_CR2_DMAEN; } void i2c_t::IReset() { Standby(); Resume(); } uint8_t i2c_t::WriteRead(uint8_t Addr, uint8_t *WPtr, uint8_t WLength, uint8_t *RPtr, uint8_t RLength) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return retvBusy; #endif uint8_t Rslt = retvOk; if(IBusyWait() != retvOk) { Rslt = retvBusy; goto WriteReadEnd; } // Clear flags PParams->pi2c->SR1 = 0; while(RxIsNotEmpty()) (void)PParams->pi2c->DR; // Read DR until it empty ClearAddrFlag(); // Start transmission SendStart(); if(WaitEv5() != retvOk) { Rslt = retvFail; goto WriteReadEnd; } SendAddrWithWrite(Addr); if(WaitEv6() != retvOk) { SendStop(); Rslt = retvFail; goto WriteReadEnd; } ClearAddrFlag(); // Start TX DMA if needed if(WLength != 0) { if(WaitEv8() != retvOk) { Rslt = retvFail; goto WriteReadEnd; } dmaStreamSetMemory0(PDmaTx, WPtr); dmaStreamSetMode (PDmaTx, PParams->DmaModeTx); dmaStreamSetTransactionSize(PDmaTx, WLength); chSysLock(); dmaStreamEnable(PDmaTx); chThdSuspendS(&ThdRef); // Wait IRQ chSysUnlock(); dmaStreamDisable(PDmaTx); } // Read if needed if(RLength != 0) { if(WaitEv8() != retvOk) { Rslt = retvFail; goto WriteReadEnd; } // Send repeated start SendStart(); if(WaitEv5() != retvOk) { Rslt = retvFail; goto WriteReadEnd; } SendAddrWithRead(Addr); if(WaitEv6() != retvOk) { SendStop(); Rslt = retvFail; goto WriteReadEnd; } // If single byte is to be received, disable ACK before clearing ADDR flag if(RLength == 1) AckDisable(); else AckEnable(); ClearAddrFlag(); dmaStreamSetMemory0(PDmaRx, RPtr); dmaStreamSetMode (PDmaRx, PParams->DmaModeRx); dmaStreamSetTransactionSize(PDmaRx, RLength); SignalLastDmaTransfer(); // Inform DMA that this is last transfer => do not ACK last byte chSysLock(); dmaStreamEnable(PDmaRx); chThdSuspendS(&ThdRef); // Wait IRQ chSysUnlock(); dmaStreamDisable(PDmaRx); } // if != 0 else WaitBTF(); // if nothing to read, just stop SendStop(); WriteReadEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } uint8_t i2c_t::WriteWrite(uint8_t Addr, uint8_t *WPtr1, uint8_t WLength1, uint8_t *WPtr2, uint8_t WLength2) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return retvBusy; #endif uint8_t Rslt = retvOk; if(IBusyWait() != retvOk) { Rslt = retvBusy; goto WriteWriteEnd; } // Clear flags PParams->pi2c->SR1 = 0; while(RxIsNotEmpty()) (void)PParams->pi2c->DR; // Read DR until it empty ClearAddrFlag(); // Start transmission SendStart(); if(WaitEv5() != retvOk) { Rslt = retvFail; goto WriteWriteEnd; } SendAddrWithWrite(Addr); if(WaitEv6() != retvOk) { SendStop(); Rslt = retvFail; goto WriteWriteEnd; } ClearAddrFlag(); // Start TX DMA if needed if(WLength1 != 0) { if(WaitEv8() != retvOk) { Rslt = retvFail; goto WriteWriteEnd; } dmaStreamSetMemory0(PDmaTx, WPtr1); dmaStreamSetMode (PDmaTx, PParams->DmaModeTx); dmaStreamSetTransactionSize(PDmaTx, WLength1); chSysLock(); dmaStreamEnable(PDmaTx); chThdSuspendS(&ThdRef); // Wait IRQ chSysUnlock(); dmaStreamDisable(PDmaTx); } if(WLength2 != 0) { if(WaitEv8() != retvOk) { Rslt = retvFail; goto WriteWriteEnd; } dmaStreamSetMemory0(PDmaTx, WPtr2); dmaStreamSetMode (PDmaTx, PParams->DmaModeTx); dmaStreamSetTransactionSize(PDmaTx, WLength2); chSysLock(); dmaStreamEnable(PDmaTx); chThdSuspendS(&ThdRef); // Wait IRQ chSysUnlock(); dmaStreamDisable(PDmaTx); } WaitBTF(); SendStop(); WriteWriteEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } uint8_t i2c_t::CheckAddress(uint32_t Addr) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return retvFail; #endif uint8_t Rslt = retvFail; if(IBusyWait() != retvOk) { Rslt = retvBusy; Printf("i2cC Busy\r"); goto ChckEnd; } IReset(); // Reset I2C // Clear flags PParams->pi2c->SR1 = 0; while(RxIsNotEmpty()) (void)PParams->pi2c->DR; // Read DR until it empty ClearAddrFlag(); // Start transmission SendStart(); if(WaitEv5() == retvOk) { SendAddrWithWrite(Addr); if(WaitEv6() == retvOk) Rslt = retvOk; else Rslt = retvNotFound; } SendStop(); ChckEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } uint8_t i2c_t::Write(uint8_t Addr, uint8_t *WPtr1, uint8_t WLength1) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return retvBusy; #endif uint8_t Rslt = retvOk; if(IBusyWait() != retvOk) { Rslt = retvBusy; goto WriteEnd; } // Clear flags PParams->pi2c->SR1 = 0; while(RxIsNotEmpty()) (void)PParams->pi2c->DR; // Read DR until it empty ClearAddrFlag(); // Start transmission SendStart(); if(WaitEv5() != retvOk) { Rslt = retvFail; goto WriteEnd; } SendAddrWithWrite(Addr); if(WaitEv6() != retvOk) { SendStop(); Rslt = retvFail; goto WriteEnd; } ClearAddrFlag(); // Start TX DMA if needed if(WLength1 != 0) { if(WaitEv8() != retvOk) { Rslt = retvFail; goto WriteEnd; } dmaStreamSetMemory0(PDmaTx, WPtr1); dmaStreamSetMode (PDmaTx, PParams->DmaModeTx); dmaStreamSetTransactionSize(PDmaTx, WLength1); chSysLock(); dmaStreamEnable(PDmaTx); chThdSuspendS(&ThdRef); // Wait IRQ chSysUnlock(); dmaStreamDisable(PDmaTx); } WaitBTF(); SendStop(); WriteEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } void i2c_t::ScanBus() { Printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f"); uint8_t AddrHi, Addr; for(AddrHi = 0; AddrHi < 0x80; AddrHi += 0x10) { Printf("\r%02X: ", AddrHi); for(uint8_t n=0; n<0x10; n++) { Addr = AddrHi + n; if(Addr <= 0x01 or Addr > 0x77) Printf(" "); else { // Try to get response from addr if(IBusyWait() != retvOk) { Printf("i2cBusyWait\r"); return; } // Clear flags PParams->pi2c->SR1 = 0; while(RxIsNotEmpty()) (void)PParams->pi2c->DR; // Read DR until it empty ClearAddrFlag(); // Start transmission SendStart(); if(WaitEv5() != retvOk) continue; SendAddrWithWrite(Addr); if(WaitEv6() == retvOk) Printf("%02X ", Addr); else Printf("__ "); SendStop(); } } // for n } // for AddrHi PrintfEOL(); } // ==== Flag operations ==== #define RETRY_CNT_LONG 450 #define RETRY_CNT_SHORT 450 // Busy flag uint8_t i2c_t::IBusyWait() { uint8_t RetryCnt = 4; while(RetryCnt--) { if(!(PParams->pi2c->SR2 & I2C_SR2_BUSY)) return retvOk; chThdSleepMilliseconds(1); } Error = true; return retvTimeout; } // BUSY, MSL & SB flags uint8_t i2c_t::WaitEv5() { uint32_t RetryCnt = RETRY_CNT_LONG; while(RetryCnt--) { uint16_t Flag1 = PParams->pi2c->SR1; uint16_t Flag2 = PParams->pi2c->SR2; if((Flag1 & I2C_SR1_SB) and (Flag2 & (I2C_SR2_MSL | I2C_SR2_BUSY))) return retvOk; } Error = true; return retvFail; } uint8_t i2c_t::WaitEv6() { uint32_t RetryCnt = RETRY_CNT_SHORT; uint16_t Flag1; do { Flag1 = PParams->pi2c->SR1; if((RetryCnt-- == 0) or (Flag1 & I2C_SR1_AF)) return retvFail; // Fail if timeout or NACK } while(!(Flag1 & I2C_SR1_ADDR)); // ADDR set when Address is sent and ACK received return retvOk; } uint8_t i2c_t::WaitEv8() { uint32_t RetryCnt = RETRY_CNT_SHORT; while(RetryCnt--) if(PParams->pi2c->SR1 & I2C_SR1_TXE) return retvOk; Error = true; return retvTimeout; } uint8_t i2c_t::WaitRx() { uint32_t RetryCnt = RETRY_CNT_LONG; while(RetryCnt--) if(PParams->pi2c->SR1 & I2C_SR1_RXNE) return retvOk; return retvTimeout; } uint8_t i2c_t::WaitStop() { uint32_t RetryCnt = RETRY_CNT_LONG; while(RetryCnt--) if(PParams->pi2c->CR1 & I2C_CR1_STOP) return retvOk; return retvTimeout; } uint8_t i2c_t::WaitBTF() { uint32_t RetryCnt = RETRY_CNT_LONG; while(RetryCnt--) if(PParams->pi2c->SR1 & I2C_SR1_BTF) return retvOk; return retvTimeout; } #endif // MCU type #if defined STM32L4XX || defined STM32F030 #define I2C_DMATX_MODE(Chnl) \ STM32_DMA_CR_CHSEL(Chnl) | \ DMA_PRIORITY_LOW | \ STM32_DMA_CR_MSIZE_BYTE | \ STM32_DMA_CR_PSIZE_BYTE | \ STM32_DMA_CR_MINC | /* Memory pointer increase */ \ STM32_DMA_CR_DIR_M2P /* Direction is memory to peripheral */ #define I2C_DMARX_MODE(Chnl) \ STM32_DMA_CR_CHSEL(Chnl) | \ DMA_PRIORITY_LOW | \ STM32_DMA_CR_MSIZE_BYTE | \ STM32_DMA_CR_PSIZE_BYTE | \ STM32_DMA_CR_MINC | /* Memory pointer increase */ \ STM32_DMA_CR_DIR_P2M /* Direction is peripheral to memory */ #if 1 // ==== Inner defines ==== #define I2C_INT_MASK ((uint32_t)(I2C_ISR_TCR | I2C_ISR_TC | I2C_ISR_STOPF | I2C_ISR_NACKF | I2C_ISR_ADDR | I2C_ISR_RXNE | I2C_ISR_TXIS)) #define I2C_ERROR_MASK ((uint32_t)(I2C_ISR_BERR | I2C_ISR_ARLO | I2C_ISR_OVR | I2C_ISR_PECERR | I2C_ISR_TIMEOUT | I2C_ISR_ALERT)) #define I2C_NO_ERROR 0x00 // No error #define I2C_BUS_ERROR 0x01 // Bus Error #define I2C_ARBITRATION_LOST 0x02 // Arbitration Lost #define I2C_ACK_FAILURE 0x04 // Acknowledge Failure #define I2C_OVERRUN 0x08 // Overrun/Underrun #define I2C_PEC_ERROR 0x10 // PEC Error in reception #define I2C_TIMEOUT 0x20 // Hardware timeout #define I2C_SMB_ALERT 0x40 // SMBus Alert #endif #if I2C1_ENABLED static const i2cParams_t I2C1Params = { I2C1, I2C1_GPIO, I2C1_SCL, I2C1_SDA, I2C_AF, I2C1_DMA_TX, I2C1_DMA_RX, I2C_DMATX_MODE(I2C1_DMA_CHNL), I2C_DMARX_MODE(I2C1_DMA_CHNL), #if defined STM32L4XX STM32_I2C1_EVENT_NUMBER, STM32_I2C1_ERROR_NUMBER, I2C_CLK_SRC #else STM32_I2C1_GLOBAL_NUMBER, STM32_I2C1_GLOBAL_NUMBER, #endif }; i2c_t i2c1 {&I2C1Params}; #endif #if I2C2_ENABLED static const i2cParams_t I2C2Params = { I2C2, I2C2_GPIO, I2C2_SCL, I2C2_SDA, I2C_AF, I2C2_DMA_TX, I2C2_DMA_RX, I2C_DMATX_MODE(I2C2_DMA_CHNL), I2C_DMARX_MODE(I2C2_DMA_CHNL), #if defined STM32L4XX STM32_I2C2_EVENT_NUMBER, STM32_I2C2_ERROR_NUMBER, I2C_CLK_SRC #else STM32_I2C1_GLOBAL_NUMBER, STM32_I2C1_GLOBAL_NUMBER, #endif }; i2c_t i2c2 {&I2C2Params}; #endif #if I2C3_ENABLED static const i2cParams_t I2C3Params = { I2C3, I2C3_GPIO, I2C3_SCL, I2C3_SDA, I2C_AF, I2C3_DMA_TX, I2C3_DMA_RX, I2C_DMATX_MODE(I2C3_DMA_CHNL), I2C_DMARX_MODE(I2C3_DMA_CHNL), #if defined STM32L4XX STM32_I2C3_EVENT_NUMBER, STM32_I2C3_ERROR_NUMBER, I2C_CLK_SRC #else STM32_I2C1_GLOBAL_NUMBER, STM32_I2C1_GLOBAL_NUMBER, #endif }; i2c_t i2c3 {&I2C3Params}; #endif void i2c_t::Init() { // GPIO PinSetupAlterFunc(PParams->PGpio, PParams->SclPin, omOpenDrain, pudNone, PParams->PinAF); PinSetupAlterFunc(PParams->PGpio, PParams->SdaPin, omOpenDrain, pudNone, PParams->PinAF); #if I2C_USE_SEMAPHORE chBSemObjectInit(&BSemaphore, NOT_TAKEN); #endif // I2C I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter if(pi2c == I2C1) { rccResetI2C1(); rccEnableI2C1(FALSE); } else if(pi2c == I2C2) { rccResetI2C2(); rccEnableI2C2(FALSE); } #ifdef I2C3 else if(pi2c == I2C3) { rccResetI2C3(); rccEnableI2C3(FALSE); } #endif pi2c->CR1 = 0; // Clear PE bit => disable and reset i2c // ==== Setup timings ==== // Get input clock uint32_t ClkHz; if(PParams->ClkSrc == i2cclkHSI) { Clk.EnableHSI(); Clk.SetI2CClkSrc(pi2c, i2cclkHSI); ClkHz = HSI_FREQ_HZ; } #if defined STM32L4XX else if(PParams->ClkSrc == i2cclkPCLK1) { Clk.SetI2CClkSrc(pi2c, i2cclkPCLK1); ClkHz = Clk.APB1FreqHz; } #endif else { Clk.SetI2CClkSrc(pi2c, i2cclkSYSCLK); ClkHz = Clk.GetSysClkHz(); } // Calc prescaler uint32_t Prescaler = ClkHz / 16000000; if(Prescaler > 0) Prescaler--; // Calc Scl & Sda len uint32_t SclLen = ((ClkHz / 2) / I2C_BAUDRATE_HZ) - 1; if(SclLen >= 4) SclLen -= 4; pi2c->TIMINGR = (Prescaler << 28) | 0x00100000 | (SclLen << 8) | SclLen; // Analog filter enabled, digital disabled, clk stretch enabled, DMA enabled pi2c->CR1 = I2C_CR1_TXDMAEN | I2C_CR1_RXDMAEN; // ==== DMA ==== PDmaTx = dmaStreamAlloc(PParams->DmaTxID, IRQ_PRIO_MEDIUM, nullptr, nullptr); PDmaRx = dmaStreamAlloc(PParams->DmaRxID, IRQ_PRIO_MEDIUM, nullptr, nullptr); dmaStreamSetPeripheral(PDmaTx, &pi2c->TXDR); dmaStreamSetPeripheral(PDmaRx, &pi2c->RXDR); // ==== IRQ ==== nvicEnableVector(PParams->IrqEvtNumber, IRQ_PRIO_MEDIUM); nvicEnableVector(PParams->IrqErrorNumber, IRQ_PRIO_MEDIUM); } void i2c_t::ScanBus() { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return; #endif Printf(" 0 1 2 3 4 5 6 7 8 9 a b c d e f"); uint32_t AddrHi, Addr; I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter for(AddrHi = 0; AddrHi < 0x80; AddrHi += 0x10) { Printf("\r%02X: ", AddrHi); for(uint32_t n=0; n < 0x10; n++) { Addr = AddrHi + n; if(Addr <= 0x01 or Addr > 0x77) Printf(" "); else { IReset(); // Reset I2C // Set addr and autoend; NBYTES = 0 pi2c->CR2 = (Addr << 1) | I2C_CR2_AUTOEND; pi2c->CR2 |= I2C_CR2_START; // Start while(!(pi2c->ISR & I2C_ISR_STOPF)); if(pi2c->ISR & I2C_ISR_NACKF) Printf("__ "); else Printf("%02X ", Addr); } } // for lo } // for hi // Disable I2C pi2c->CR1 &= ~I2C_CR1_PE; Printf("\r"); #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif } uint8_t i2c_t::CheckAddress(uint32_t Addr) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return FAILURE; #endif IReset(); // Reset I2C uint8_t Rslt; int32_t Retries = 9999; I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter if(IBusyWait() != retvOk) { Rslt = retvBusy; Printf("i2cC Busy\r"); goto ChckEnd; } IReset(); // Reset I2C pi2c->CR2 = (Addr << 1) | I2C_CR2_AUTOEND; pi2c->CR2 |= I2C_CR2_START; // Start while(!(pi2c->ISR & I2C_ISR_STOPF)) { if(!Retries--) { Rslt = retvTimeout; Printf("i2cC TO\r"); goto ChckEnd; } } if(pi2c->ISR & I2C_ISR_NACKF) Rslt = retvNotFound; else Rslt = retvOk; ChckEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } uint8_t i2c_t::Write(uint32_t Addr, uint8_t *WPtr, uint32_t WLength) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return FAILURE; #endif uint8_t Rslt; msg_t r; I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter if(WLength == 0 or WPtr == nullptr) { Rslt = retvCmdError; goto WriteEnd; } if(IBusyWait() != retvOk) { Rslt = retvBusy; Printf("i2cW Busy\r"); goto WriteEnd; } IReset(); // Reset I2C // Prepare TX DMA dmaStreamSetMode(PDmaTx, PParams->DmaModeTx); dmaStreamSetMemory0(PDmaTx, WPtr); dmaStreamSetTransactionSize(PDmaTx, WLength); // Prepare tx IState = istWrite; // Nothing to read pi2c->CR2 = (Addr << 1) | (WLength << 16); chSysLock(); dmaStreamEnable(PDmaTx); // Enable TX DMA // Enable IRQs: TX completed, error, NAck pi2c->CR1 |= (I2C_CR1_TCIE | I2C_CR1_ERRIE | I2C_CR1_NACKIE); pi2c->CR2 |= I2C_CR2_START; // Start transmission // Wait completion r = chThdSuspendTimeoutS(&PThd, TIME_MS2I(I2C_TIMEOUT_MS)); chSysUnlock(); // Disable IRQs pi2c->CR1 &= ~(I2C_CR1_TCIE | I2C_CR1_ERRIE | I2C_CR1_NACKIE); if(r == MSG_TIMEOUT) { pi2c->CR2 |= I2C_CR2_STOP; Rslt = retvTimeout; } else Rslt = (IState == istFailure)? retvFail : retvOk; WriteEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } uint8_t i2c_t::WriteRead(uint32_t Addr, uint8_t *WPtr, uint32_t WLength, uint8_t *RPtr, uint32_t RLength) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return FAILURE; #endif uint8_t Rslt; msg_t r; I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter if(WLength == 0 or WPtr == nullptr) { Rslt = retvCmdError; goto WriteReadEnd; } if(IBusyWait() != retvOk) { Rslt = retvBusy; Printf("i2cWR Busy\r"); goto WriteReadEnd; } IReset(); // Reset I2C // Prepare TX DMA dmaStreamSetMode(PDmaTx, PParams->DmaModeTx); dmaStreamSetMemory0(PDmaTx, WPtr); dmaStreamSetTransactionSize(PDmaTx, WLength); if(RLength != 0 and RPtr != nullptr) { // Prepare RX DMA dmaStreamSetMode(PDmaRx, PParams->DmaModeRx); dmaStreamSetMemory0(PDmaRx, RPtr); dmaStreamSetTransactionSize(PDmaRx, RLength); ILen = RLength; IState = istWriteRead; } else IState = istWrite; // Nothing to read pi2c->CR2 = (Addr << 1) | (WLength << 16); dmaStreamEnable(PDmaTx); // Enable TX DMA chSysLock(); // Enable IRQs: TX completed, error, NAck pi2c->CR1 |= (I2C_CR1_TCIE | I2C_CR1_ERRIE | I2C_CR1_NACKIE); pi2c->CR2 |= I2C_CR2_START; // Start transmission // Wait completion r = chThdSuspendTimeoutS(&PThd, TIME_MS2I(I2C_TIMEOUT_MS)); chSysUnlock(); // Disable IRQs pi2c->CR1 &= ~(I2C_CR1_TCIE | I2C_CR1_ERRIE | I2C_CR1_NACKIE); if(r == MSG_TIMEOUT) { pi2c->CR2 |= I2C_CR2_STOP; Rslt = retvTimeout; } else Rslt = (IState == istFailure)? retvFail : retvOk; WriteReadEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } uint8_t i2c_t::WriteReadNoDMA(uint32_t Addr, uint8_t *WPtr, uint32_t WLength, uint8_t *RPtr, uint32_t RLength) { return 0; } uint8_t i2c_t::WriteWrite(uint32_t Addr, uint8_t *WPtr1, uint32_t WLength1, uint8_t *WPtr2, uint32_t WLength2) { #if I2C_USE_SEMAPHORE if(chBSemWait(&BSemaphore) != MSG_OK) return FAILURE; #endif uint8_t Rslt; msg_t r; I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter if(WLength1 == 0 or WPtr1 == nullptr) { Rslt = retvCmdError; goto WriteWriteEnd; } if(IBusyWait() != retvOk) { Rslt = retvBusy; goto WriteWriteEnd; } IReset(); // Reset I2C // Prepare TX DMA dmaStreamSetMode(PDmaTx, PParams->DmaModeTx); dmaStreamSetMemory0(PDmaTx, WPtr1); dmaStreamSetTransactionSize(PDmaTx, WLength1); // Prepare transmission if(WLength2 != 0 and WPtr2 != nullptr) { IState = istWriteWrite; IPtr = WPtr2; ILen = WLength2; pi2c->CR2 = (Addr << 1) | (WLength1 << 16) | I2C_CR2_RELOAD; } else { // No second write IState = istWrite; pi2c->CR2 = (Addr << 1) | (WLength1 << 16); } chSysLock(); // Enable IRQs: TX completed, error, NAck pi2c->CR1 |= (I2C_CR1_TCIE | I2C_CR1_ERRIE | I2C_CR1_NACKIE); pi2c->CR2 |= I2C_CR2_START; // Start transmission dmaStreamEnable(PDmaTx); // Enable TX DMA // Wait completion r = chThdSuspendTimeoutS(&PThd, TIME_MS2I(I2C_TIMEOUT_MS)); chSysUnlock(); // Disable IRQs pi2c->CR1 &= ~(I2C_CR1_TCIE | I2C_CR1_ERRIE | I2C_CR1_NACKIE); if(r == MSG_TIMEOUT) { pi2c->CR2 |= I2C_CR2_STOP; Rslt = retvTimeout; } else Rslt = (IState == istFailure)? retvFail : retvOk; WriteWriteEnd: #if I2C_USE_SEMAPHORE chBSemSignal(&BSemaphore); #endif return Rslt; } void i2c_t::IReset() { PParams->pi2c->CR1 &= ~I2C_CR1_PE; __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); // Wait 9 cycles PParams->pi2c->CR1 |= I2C_CR1_PE; } void i2c_t::Standby() { PParams->pi2c->CR1 &= ~I2C_CR1_PE; PinSetupAnalog(PParams->PGpio, PParams->SclPin); PinSetupAnalog(PParams->PGpio, PParams->SdaPin); __NOP(); __NOP(); __NOP(); // Wait 3 cycles } void i2c_t::PutBusLow() { PParams->pi2c->CR1 &= ~I2C_CR1_PE; __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); __NOP(); PinSetupOut(PParams->PGpio, PParams->SclPin, omOpenDrain); PinSetupOut(PParams->PGpio, PParams->SdaPin, omOpenDrain); PinSetLo(PParams->PGpio, PParams->SclPin); PinSetLo(PParams->PGpio, PParams->SdaPin); } void i2c_t::Resume() { PParams->pi2c->CR1 |= I2C_CR1_PE; PinSetupAlterFunc(PParams->PGpio, PParams->SclPin, omOpenDrain, pudNone, PParams->PinAF); PinSetupAlterFunc(PParams->PGpio, PParams->SdaPin, omOpenDrain, pudNone, PParams->PinAF); } uint8_t i2c_t::IBusyWait() { uint8_t RetryCnt = 4; while(RetryCnt--) { if(!(PParams->pi2c->ISR & I2C_ISR_BUSY)) return retvOk; chThdSleepMilliseconds(1); } return retvTimeout; } void i2c_t::IServeIRQ(uint32_t isr) { I2C_TypeDef *pi2c = PParams->pi2c; // To make things shorter #if 1 // ==== NACK ==== if((isr & I2C_ISR_NACKF) != 0) { PrintfI("i2c 0x%X NACK\r", (pi2c->CR2 >> 1) & 0xFF); // Stop DMA dmaStreamDisable(PDmaTx); dmaStreamDisable(PDmaRx); // Stop transaction pi2c->CR2 |= I2C_CR2_STOP; // Disable IRQs pi2c->CR1 &= ~(I2C_CR1_TCIE | I2C_CR1_TXIE | I2C_CR1_RXIE); IState = istFailure; IWakeup(); return; } #endif #if 1 // ==== TX partly completed ==== if((isr & I2C_ISR_TCR) != 0) { dmaStreamDisable(PDmaTx); if(IState == istWriteWrite) { // Send next ILen bytes pi2c->CR2 = (pi2c->CR2 & ~(I2C_CR2_NBYTES | I2C_CR2_RELOAD)) | (ILen << 16); // Prepare and enable TX DMA for second write dmaStreamSetMode(PDmaTx, PParams->DmaModeTx); dmaStreamSetMemory0(PDmaTx, IPtr); dmaStreamSetTransactionSize(PDmaTx, ILen); dmaStreamEnable(PDmaTx); IState = istWrite; } } #endif #if 1 // ==== TX completed ==== if((isr & I2C_ISR_TC) != 0) { dmaStreamDisable(PDmaTx); // } dmaStreamDisable(PDmaRx); // } Both sorts of transaction may be completed if(IState == istWriteRead) { // Write phase completed // Receive ILen bytes pi2c->CR2 = (pi2c->CR2 & ~I2C_CR2_NBYTES) | I2C_CR2_RD_WRN | (ILen << 16); dmaStreamEnable(PDmaRx); pi2c->CR2 |= I2C_CR2_START; // Send repeated start IState = istRead; } // if WriteRead else { // istWrite, istRead IState = istIdle; pi2c->CR2 |= I2C_CR2_STOP; pi2c->CR1 &= ~I2C_CR1_TCIE; // Disable TransferComplete IRQ IWakeup(); } } #endif } void i2c_t::IServeErrIRQ(uint32_t isr) { // Uart.PrintfI("isre: %X\r", isr); // Stop DMA dmaStreamDisable(PDmaTx); dmaStreamDisable(PDmaRx); // Check errors uint32_t Errors = 0; if(isr & I2C_ISR_BERR) Errors |= I2C_BUS_ERROR; if(isr & I2C_ISR_ARLO) Errors |= I2C_ARBITRATION_LOST; if(isr & I2C_ISR_OVR) Errors |= I2C_OVERRUN; if(isr & I2C_ISR_TIMEOUT) Errors |= I2C_TIMEOUT; // If some error has been identified then wake the waiting thread if(Errors != I2C_NO_ERROR) { PrintfI("i2c err: %X\r", Errors); IWakeup(); } } void i2c_t::IWakeup() { chSysLockFromISR(); chThdResumeI(&PThd, MSG_OK); chSysUnlockFromISR(); } #if 1 // =============================== IRQs ================================== extern "C" { #if I2C1_ENABLED // ==== I2C1 ==== #if defined STM32L4XX OSAL_IRQ_HANDLER(STM32_I2C1_EVENT_HANDLER) { // Uart.PrintfI("i2c1 irq\r"); uint32_t isr = I2C1->ISR; OSAL_IRQ_PROLOGUE(); I2C1->ICR = isr & I2C_INT_MASK; // Clear IRQ bits i2c1.IServeIRQ(isr); OSAL_IRQ_EPILOGUE(); } OSAL_IRQ_HANDLER(STM32_I2C1_ERROR_HANDLER) { uint32_t isr = I2C1->ISR; OSAL_IRQ_PROLOGUE(); I2C1->ICR = isr & I2C_ERROR_MASK; // Clear IRQ bits i2c1.IServeErrIRQ(isr); OSAL_IRQ_EPILOGUE(); } #else OSAL_IRQ_HANDLER(STM32_I2C1_GLOBAL_HANDLER) { // Uart.PrintfI("i2c1 irq\r"); uint32_t isr = I2C1->ISR; uint32_t isrEvt = isr & I2C_INT_MASK; uint32_t isrErr = isr & I2C_ERROR_MASK; OSAL_IRQ_PROLOGUE(); I2C1->ICR = isr; // Clear IRQ bits if(isrEvt != 0) i2c1.IServeIRQ(isrEvt); if(isrErr != 0) i2c1.IServeErrIRQ(isrErr); OSAL_IRQ_EPILOGUE(); } #endif // MCU type #endif #if I2C2_ENABLED // ==== I2C2 ==== OSAL_IRQ_HANDLER(STM32_I2C2_EVENT_HANDLER) { uint32_t isr = I2C2->ISR; OSAL_IRQ_PROLOGUE(); I2C2->ICR = isr & I2C_INT_MASK; // Clear IRQ bits i2c2.IServeIRQ(isr); OSAL_IRQ_EPILOGUE(); } OSAL_IRQ_HANDLER(STM32_I2C2_ERROR_HANDLER) { uint32_t isr = I2C2->ISR; OSAL_IRQ_PROLOGUE(); I2C2->ICR = isr & I2C_ERROR_MASK; // Clear IRQ bits i2c2.IServeErrIRQ(isr); OSAL_IRQ_EPILOGUE(); } #endif #if I2C3_ENABLED// ==== I2C3 ==== OSAL_IRQ_HANDLER(STM32_I2C3_EVENT_HANDLER) { uint32_t isr = I2C3->ISR; OSAL_IRQ_PROLOGUE(); I2C3->ICR = isr & I2C_INT_MASK; // Clear IRQ bits i2c3.IServeIRQ(isr); OSAL_IRQ_EPILOGUE(); } OSAL_IRQ_HANDLER(STM32_I2C3_ERROR_HANDLER) { uint32_t isr = I2C3->ISR; OSAL_IRQ_PROLOGUE(); I2C3->ICR = isr & I2C_ERROR_MASK; // Clear IRQ bits i2c3.IServeErrIRQ(isr); OSAL_IRQ_EPILOGUE(); } #endif } // extern C #endif #endif // L476
[ "laystoll@yandex.ru" ]
laystoll@yandex.ru
a368bd575332fd1a09477f53aa2021e271329460
ad10052619b7bc79d311940bd2419772c4bc8a53
/topcoder-master-2/SkipRope.cpp
473fe16a53cf0dec4f8084ad500485305d5bb3eb
[]
no_license
bluepine/topcoder
3af066a5b1ac6c448c50942f98deb2aa382ba040
d300c8a349a8346dba4a5fe3b4f43b17207627a1
refs/heads/master
2021-01-19T08:15:06.539102
2014-04-02T21:10:58
2014-04-02T21:10:58
18,381,690
1
0
null
null
null
null
UTF-8
C++
false
false
3,661
cpp
// BEGIN CUT HERE // END CUT HERE #include <sstream> #include <string> #include <vector> #include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <algorithm> using namespace std; class SkipRope { public: vector <int> partners(vector <int> candidates, int height) { unsigned int i; vector <int> heightAbs(candidates.size()); vector <int> ret(2); int flg1 = 0, flg2 = 0; int tmp; for(i=0; i<candidates.size(); i++) heightAbs[i] = abs(height - candidates[i]); sort(heightAbs.begin(), heightAbs.end()); for(i=0; i<candidates.size(); i++) { if(height + heightAbs[0] == candidates[i]) flg1 = 1; if(height + heightAbs[1] == candidates[i]) flg2 = 1; } if(flg1) ret[0] = height + heightAbs[0]; else ret[0] = height - heightAbs[0]; if(flg2) ret[1] = height + heightAbs[1]; else ret[1] = height - heightAbs[1]; if(ret[0] > ret[1]) { tmp = ret[0]; ret[0] = ret[1]; ret[1] = tmp; } return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { int Arr0[] = {102, 99, 104}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 100; int Arr2[] = { 99, 102 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, partners(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {102, 97, 104}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 100; int Arr2[] = { 97, 102 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, partners(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {101, 100, 99}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 100; int Arr2[] = { 100, 101 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, partners(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {75, 117, 170, 175, 168, 167, 167, 142, 170, 85, 89, 170}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 169; int Arr2[] = { 170, 170 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, partners(Arg0, Arg1)); } void test_case_4() { int Arr0[] = {134, 79, 164, 86, 131, 78, 99, 150, 105, 163, 150, 110, 90, 137, 127, 130, 121, 93, 97, 131, 170, 137, 171, 153, 137, 138, 92, 103, 149, 110, 156}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 82; int Arr2[] = { 79, 86 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, partners(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { SkipRope ___test; ___test.run_test(-1); } // END CUT HERE
[ "1983.song.wei@gmail.com" ]
1983.song.wei@gmail.com
c76dfae0da5f0506224cbe1e46634614e3e66ea0
8dc84558f0058d90dfc4955e905dab1b22d12c08
/third_party/blink/renderer/modules/media_capabilities/media_capabilities.h
3c1c8f2ff9929999d5fee4fc5754a4744cded16d
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
992
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_H_ #define THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_H_ #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/heap/visitor.h" namespace blink { class MediaDecodingConfiguration; class MediaEncodingConfiguration; class ScriptPromise; class ScriptState; class MediaCapabilities final : public ScriptWrappable { DEFINE_WRAPPERTYPEINFO(); public: MediaCapabilities(); ScriptPromise decodingInfo(ScriptState*, const MediaDecodingConfiguration&); ScriptPromise encodingInfo(ScriptState*, const MediaEncodingConfiguration&); }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CAPABILITIES_MEDIA_CAPABILITIES_H_
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
7059010a6225ec3c4edc704279ae98198c2a7909
e433566a524fd56b871bdd93685e0b8f2985574c
/bebop_ws/devel/include/bebop_msgs/Ardrone3CameraStateVelocityRange.h
69d210cb9b24d65ce6c823e9d5211ad633ace8d7
[]
no_license
JarrettPhilips/self_landing_drone
000b2f386302555f1876fbc38ada71d12451f8e0
7e497492941d9f642d4991c3fbc5be20e63f965e
refs/heads/master
2021-09-14T13:20:14.536053
2017-12-20T00:16:55
2017-12-20T00:16:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,389
h
// Generated by gencpp from file bebop_msgs/Ardrone3CameraStateVelocityRange.msg // DO NOT EDIT! #ifndef BEBOP_MSGS_MESSAGE_ARDRONE3CAMERASTATEVELOCITYRANGE_H #define BEBOP_MSGS_MESSAGE_ARDRONE3CAMERASTATEVELOCITYRANGE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <std_msgs/Header.h> namespace bebop_msgs { template <class ContainerAllocator> struct Ardrone3CameraStateVelocityRange_ { typedef Ardrone3CameraStateVelocityRange_<ContainerAllocator> Type; Ardrone3CameraStateVelocityRange_() : header() , max_tilt(0.0) , max_pan(0.0) { } Ardrone3CameraStateVelocityRange_(const ContainerAllocator& _alloc) : header(_alloc) , max_tilt(0.0) , max_pan(0.0) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef float _max_tilt_type; _max_tilt_type max_tilt; typedef float _max_pan_type; _max_pan_type max_pan; typedef boost::shared_ptr< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> const> ConstPtr; }; // struct Ardrone3CameraStateVelocityRange_ typedef ::bebop_msgs::Ardrone3CameraStateVelocityRange_<std::allocator<void> > Ardrone3CameraStateVelocityRange; typedef boost::shared_ptr< ::bebop_msgs::Ardrone3CameraStateVelocityRange > Ardrone3CameraStateVelocityRangePtr; typedef boost::shared_ptr< ::bebop_msgs::Ardrone3CameraStateVelocityRange const> Ardrone3CameraStateVelocityRangeConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> & v) { ros::message_operations::Printer< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace bebop_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'bebop_msgs': ['/home/anthony/Documents/Final/bebop_ws/src/bebop_autonomy/bebop_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > { static const char* value() { return "cda98074fc63d3bb789505d7a068cced"; } static const char* value(const ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xcda98074fc63d3bbULL; static const uint64_t static_value2 = 0x789505d7a068ccedULL; }; template<class ContainerAllocator> struct DataType< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > { static const char* value() { return "bebop_msgs/Ardrone3CameraStateVelocityRange"; } static const char* value(const ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > { static const char* value() { return "# Ardrone3CameraStateVelocityRange\n\ # auto-generated from up stream XML files at\n\ # github.com/Parrot-Developers/libARCommands/tree/master/Xml\n\ # To check upstream commit hash, refer to last_build_info file\n\ # Do not modify this file by hand. Check scripts/meta folder for generator files.\n\ #\n\ # SDK Comment: Camera Orientation velocity limits.\n\ \n\ Header header\n\ \n\ # Absolute max tilt velocity [deg/s]\n\ float32 max_tilt\n\ # Absolute max pan velocity [deg/s]\n\ float32 max_pan\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ "; } static const char* value(const ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.max_tilt); stream.next(m.max_pan); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Ardrone3CameraStateVelocityRange_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::bebop_msgs::Ardrone3CameraStateVelocityRange_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "max_tilt: "; Printer<float>::stream(s, indent + " ", v.max_tilt); s << indent << "max_pan: "; Printer<float>::stream(s, indent + " ", v.max_pan); } }; } // namespace message_operations } // namespace ros #endif // BEBOP_MSGS_MESSAGE_ARDRONE3CAMERASTATEVELOCITYRANGE_H
[ "Anke5631@colorado.edu" ]
Anke5631@colorado.edu
f24e212652b16d524c14b11ee5eff7a7f50cbbe8
61281e4061fd363d494bb242bfa885b91108f9c0
/conditionals-arrays-vectors-Strings-loops/birthday.cpp
04d0ca707ed5b2785840a41548646b89b330dd16
[]
no_license
abidSaifeddine/C-basics
235afec4e4fbd1f48c12b70eaf2399aec63b7db1
55144cfc9827b14a3ed943cd80b9837f9d4488d2
refs/heads/master
2020-04-19T13:47:12.674700
2019-01-29T20:51:38
2019-01-29T20:51:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
834
cpp
#include <iostream> #include <iostream> #include <string> #include <vector> #include <sstream> #include <limits> using namespace std; int main() { std::cout << "Hello, age" << std::endl; int age; bool isImportant; bool again = true; string rep; while(again){ isImportant = false; cout << "Enter your age" << endl; cin >> age; if(age >=1 && age<=18) isImportant=true; else if(age == 21 || age == 50 || age > 60) isImportant = true; if(isImportant) cout << "Birthday important"<<endl; else cout << "Birthday not important"<<endl; cout << "Play again ? "<<endl; cin >> rep; if(rep == "yes") again = true; else again = false; } return 0; }
[ "abid.saifeddine123@gmail.com" ]
abid.saifeddine123@gmail.com
6f27186ba865a655adb5c9136870adb14bc55cc9
1f03303d3003903f38897a55feb77fe8e1151975
/aws-cpp-sdk-accessanalyzer/source/model/FindingSummary.cpp
6b395f8bb3edad9ec8859b77f3a3207ed31c1ff8
[ "Apache-2.0", "MIT", "JSON" ]
permissive
xcode6/aws-sdk-cpp
fa392dfeb7d073416ef2858d9606210e7d5d0ea3
85b6a087b359d1c43fbf81cbbd28049832a7611d
refs/heads/master
2020-09-30T12:24:48.464922
2019-12-10T21:12:12
2019-12-10T21:12:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,154
cpp
/* * Copyright 2010-2017 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 <aws/accessanalyzer/model/FindingSummary.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace AccessAnalyzer { namespace Model { FindingSummary::FindingSummary() : m_actionHasBeenSet(false), m_analyzedAtHasBeenSet(false), m_conditionHasBeenSet(false), m_createdAtHasBeenSet(false), m_errorHasBeenSet(false), m_idHasBeenSet(false), m_isPublic(false), m_isPublicHasBeenSet(false), m_principalHasBeenSet(false), m_resourceHasBeenSet(false), m_resourceType(ResourceType::NOT_SET), m_resourceTypeHasBeenSet(false), m_status(FindingStatus::NOT_SET), m_statusHasBeenSet(false), m_updatedAtHasBeenSet(false) { } FindingSummary::FindingSummary(JsonView jsonValue) : m_actionHasBeenSet(false), m_analyzedAtHasBeenSet(false), m_conditionHasBeenSet(false), m_createdAtHasBeenSet(false), m_errorHasBeenSet(false), m_idHasBeenSet(false), m_isPublic(false), m_isPublicHasBeenSet(false), m_principalHasBeenSet(false), m_resourceHasBeenSet(false), m_resourceType(ResourceType::NOT_SET), m_resourceTypeHasBeenSet(false), m_status(FindingStatus::NOT_SET), m_statusHasBeenSet(false), m_updatedAtHasBeenSet(false) { *this = jsonValue; } FindingSummary& FindingSummary::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("action")) { Array<JsonView> actionJsonList = jsonValue.GetArray("action"); for(unsigned actionIndex = 0; actionIndex < actionJsonList.GetLength(); ++actionIndex) { m_action.push_back(actionJsonList[actionIndex].AsString()); } m_actionHasBeenSet = true; } if(jsonValue.ValueExists("analyzedAt")) { m_analyzedAt = jsonValue.GetDouble("analyzedAt"); m_analyzedAtHasBeenSet = true; } if(jsonValue.ValueExists("condition")) { Aws::Map<Aws::String, JsonView> conditionJsonMap = jsonValue.GetObject("condition").GetAllObjects(); for(auto& conditionItem : conditionJsonMap) { m_condition[conditionItem.first] = conditionItem.second.AsString(); } m_conditionHasBeenSet = true; } if(jsonValue.ValueExists("createdAt")) { m_createdAt = jsonValue.GetDouble("createdAt"); m_createdAtHasBeenSet = true; } if(jsonValue.ValueExists("error")) { m_error = jsonValue.GetString("error"); m_errorHasBeenSet = true; } if(jsonValue.ValueExists("id")) { m_id = jsonValue.GetString("id"); m_idHasBeenSet = true; } if(jsonValue.ValueExists("isPublic")) { m_isPublic = jsonValue.GetBool("isPublic"); m_isPublicHasBeenSet = true; } if(jsonValue.ValueExists("principal")) { Aws::Map<Aws::String, JsonView> principalJsonMap = jsonValue.GetObject("principal").GetAllObjects(); for(auto& principalItem : principalJsonMap) { m_principal[principalItem.first] = principalItem.second.AsString(); } m_principalHasBeenSet = true; } if(jsonValue.ValueExists("resource")) { m_resource = jsonValue.GetString("resource"); m_resourceHasBeenSet = true; } if(jsonValue.ValueExists("resourceType")) { m_resourceType = ResourceTypeMapper::GetResourceTypeForName(jsonValue.GetString("resourceType")); m_resourceTypeHasBeenSet = true; } if(jsonValue.ValueExists("status")) { m_status = FindingStatusMapper::GetFindingStatusForName(jsonValue.GetString("status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("updatedAt")) { m_updatedAt = jsonValue.GetDouble("updatedAt"); m_updatedAtHasBeenSet = true; } return *this; } JsonValue FindingSummary::Jsonize() const { JsonValue payload; if(m_actionHasBeenSet) { Array<JsonValue> actionJsonList(m_action.size()); for(unsigned actionIndex = 0; actionIndex < actionJsonList.GetLength(); ++actionIndex) { actionJsonList[actionIndex].AsString(m_action[actionIndex]); } payload.WithArray("action", std::move(actionJsonList)); } if(m_analyzedAtHasBeenSet) { payload.WithDouble("analyzedAt", m_analyzedAt.SecondsWithMSPrecision()); } if(m_conditionHasBeenSet) { JsonValue conditionJsonMap; for(auto& conditionItem : m_condition) { conditionJsonMap.WithString(conditionItem.first, conditionItem.second); } payload.WithObject("condition", std::move(conditionJsonMap)); } if(m_createdAtHasBeenSet) { payload.WithDouble("createdAt", m_createdAt.SecondsWithMSPrecision()); } if(m_errorHasBeenSet) { payload.WithString("error", m_error); } if(m_idHasBeenSet) { payload.WithString("id", m_id); } if(m_isPublicHasBeenSet) { payload.WithBool("isPublic", m_isPublic); } if(m_principalHasBeenSet) { JsonValue principalJsonMap; for(auto& principalItem : m_principal) { principalJsonMap.WithString(principalItem.first, principalItem.second); } payload.WithObject("principal", std::move(principalJsonMap)); } if(m_resourceHasBeenSet) { payload.WithString("resource", m_resource); } if(m_resourceTypeHasBeenSet) { payload.WithString("resourceType", ResourceTypeMapper::GetNameForResourceType(m_resourceType)); } if(m_statusHasBeenSet) { payload.WithString("status", FindingStatusMapper::GetNameForFindingStatus(m_status)); } if(m_updatedAtHasBeenSet) { payload.WithDouble("updatedAt", m_updatedAt.SecondsWithMSPrecision()); } return payload; } } // namespace Model } // namespace AccessAnalyzer } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
0879dae0386b93940e1d81aec60e298f8e75f718
cc36bf3a46b06af454e42f88865aa2b16caefc2c
/ObjEditor/Mesh/editableobject.h
db3d087be9abc336b42ad26274f2abb7876f0488
[]
no_license
artcampo/2012_3D_Procedural_Object_Editor
058548468514da39d1434b024bcf42e17f1e0af4
ddb75c727bfb12f1d39786dd72928dc35539c860
refs/heads/master
2021-01-12T04:27:28.204089
2016-12-29T13:57:45
2016-12-29T13:57:45
77,615,572
1
0
null
null
null
null
UTF-8
C++
false
false
533
h
#ifndef _editableobject_H #define _editableobject_H #include <string> class editableobject { public: editableobject(); editableobject( int aUniqueId, std::string& aName ); virtual ~editableobject() = 0; void setName( const std::string& aName ); std::string name(); void setHighlighted ( const bool& aValue ); bool isHighlighted(); int getId(); protected: bool mHighLighted; std::string mName; int mUniqueId; }; #endif // editableobject
[ "arturocampos82@gmail.com" ]
arturocampos82@gmail.com
c76f191529d34ee89bfd987cc69bb057e62a91f2
a65c77b44164b2c69dfe4bfa2772d18ae8e0cce2
/0contest/leet_wc_158/pA.cpp
005440190af75ec6388e84946938f55daafd7acd
[]
no_license
dl8sd11/online-judge
553422b55080e49e6bd9b38834ccf1076fb95395
5ef8e3c5390e54381683f62f88d03629e1355d1d
refs/heads/master
2021-12-22T15:13:34.279988
2021-12-13T06:45:49
2021-12-13T06:45:49
111,268,306
1
6
null
null
null
null
UTF-8
C++
false
false
2,641
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef pair<int, ll> pil; typedef pair<int, ll> pli; typedef pair<double,double> pdd; #define SQ(i) ((i)*(i)) #define MEM(a, b) memset(a, (b), sizeof(a)) #define SZ(i) int(i.size()) #define FOR(i, j, k, in) for (int i=j ; i<k ; i+=in) #define RFOR(i, j, k, in) for (int i=j ; i>=k ; i-=in) #define REP(i, j) FOR(i, 0, j, 1) #define REP1(i,j) FOR(i, 1, j+1, 1) #define RREP(i, j) RFOR(i, j, 0, 1) #define ALL(_a) _a.begin(),_a.end() #define mp make_pair #define pb push_back #define eb emplace_back #define X first #define Y second #ifdef tmd #define TIME(i) Timer i(#i) #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,deque<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;} #define IOS() class Timer { private: string scope_name; chrono::high_resolution_clock::time_point start_time; public: Timer (string name) : scope_name(name) { start_time = chrono::high_resolution_clock::now(); } ~Timer () { auto stop_time = chrono::high_resolution_clock::now(); auto length = chrono::duration_cast<chrono::microseconds>(stop_time - start_time).count(); double mlength = double(length) * 0.001; debug(scope_name, mlength); } }; #else #define TIME(i) #define debug(...) #define pary(...) #define endl '\n' #define IOS() ios_base::sync_with_stdio(0);cin.tie(0) #endif const ll MOD = 1000000007; const ll INF = 0x3f3f3f3f3f3f3f3f; const int iNF = 0x3f3f3f3f; // const ll MAXN = /********** Good Luck :) **********/ int main () { TIME(main); IOS(); return 0; }
[ "tmd910607@gmail.com" ]
tmd910607@gmail.com
bc7f6ea1b5f2aaa65e1475b80400d747e7180e52
156de3c57af4c6541b0c1cabfc933fb622aef44f
/.RootCoreBin/include/QuickAna/EventInfoIsData.h
f78863a461f71b71624c877bc100ce7bf0c30cb5
[]
no_license
Crashtime/ATLAS-JetCleaning
704937a36e2b7c1d6908745eef1d02923b274447
442f298bfcd9196bef86b978588cce0c430507d7
refs/heads/master
2021-01-21T09:06:30.007753
2016-09-16T21:48:22
2016-09-16T21:48:22
68,410,571
0
1
null
null
null
null
UTF-8
C++
false
false
2,285
h
#ifndef QUICK_ANA__EVENT_INFO_IS_DATA_H #define QUICK_ANA__EVENT_INFO_IS_DATA_H // Copyright Iowa State University 2015. // Author: Nils Krumnack // 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) // Please feel free to contact me (nils.erik.krumnack@cern.ch) for bug // reports, feature suggestions, praise and complaints. #include <QuickAna/Global.h> #include <QuickAna/AnaTool.h> namespace ana { /// \brief this tool checks whether the isData flag in the input /// event matches the isData flag from configuration class EventInfoIsData : public AnaTool { // // public interface // ASG_TOOL_CLASS (EventInfoIsData, ana::IAnaTool) /// \brief test the invariant of this object /// \par Guarantee /// no-fail public: void testInvariant () const; /// \brief standard constructor /// \par Guarantee /// strong /// \par Failures /// out of memory II public: EventInfoIsData (const std::string& name, bool isData = false); /// effects: apply this analysis tool to the objects /// guarantee: basic /// failures: tool dependent public: virtual StatusCode execute (IEventObjects& objects) override; /// \copydoc IAnaTool::setObjectType /// \sa IAnaTool::setObjectType public: virtual StatusCode setObjectType (ObjectType type, const std::string& workingPoint) override; /// \copydoc IAnaTool::step /// \sa IAnaTool::step public: virtual AnalysisStep step () const override; /// \copydoc IAnaTool::inputTypes /// \sa IAnaTool::inputTypes public: virtual unsigned inputTypes () const override; /// \copydoc IAnaTool::outputTypes /// \sa IAnaTool::outputTypes public: virtual unsigned outputTypes () const override; // // private interface // /// \brief whether we already checked one of the events /// /// for performance reasons we only check the first event, and /// skip the rest private: bool m_checkedInput = false; /// \brief whether we expect this to be data private: bool m_isData = false; }; } #endif
[ "crashtime@gmail.com" ]
crashtime@gmail.com
183cbb5438d3d50279fc55741d1a29874133afe4
f54bc0fbdc7b205f453069c5d054d98f2ce46a70
/MyGame/Game/GameObjects/Stage.cpp
b5e3a7a67086d5eb77017a7580a2794730b9df0b
[]
no_license
s-tama/Toywars
ad3033ed4bcd48640069d685c389006005133d27
582f26c87b5173827f5b842969380dc0f1a5c1f0
refs/heads/master
2020-04-15T19:52:26.043395
2019-01-10T01:32:07
2019-01-10T01:32:07
164,968,541
1
0
null
null
null
null
UTF-8
C++
false
false
929
cpp
// // Stage.cpp // // ヘッダーファイルのインクルード -------------------------------------------------- #include "Stage.h" // usingディレクティブ ------------------------------------------------------------- using namespace MyLibrary; using namespace MyGame; using namespace DirectX; using namespace DirectX::SimpleMath; // メンバ関数の定義 ---------------------------------------------------------------- /// <summary> /// コンストラクタ /// </summary> Stage::Stage() { SetTag("Stage"); } /// <summary> /// 初期化処理 /// </summary> void Stage::Initialize() { Obj3D* pObj = new Obj3D; pObj->SetModel(ModelRepository::GetInstance()->GetModel(L"Room")); pObj->SetLight(true); pObj->GetTransform()->SetScale(2); AddChild(pObj); } /// <summary> /// 更新処理 /// </summary> /// <param name="elapsedTime">経過時間</param> void Stage::Update(float elapsedTime) { }
[ "syuuki0105@gmail.com" ]
syuuki0105@gmail.com
f1fb9c31b086cf86cc42a56de29035b3c2cc77c5
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/new_hunk_6809.cpp
59e27a2097adcf5e22837b8d54241c74174c247d
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
for (i = 0; i < argc; i++) { struct object *o; struct commit *commit; o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT); if (!o) die("%s - not something we can merge", argv[i]); commit = lookup_commit(o->sha1); commit->util = (void *)argv[i]; remotes = &commit_list_insert(commit, remotes)->next; strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1)); setenv(buf.buf, argv[i], 1);
[ "993273596@qq.com" ]
993273596@qq.com
95bde9608ebedcb0c82f7c04df7d8cb02abe2ea9
3a9d933d71a40b2810d7f0559a5024347aefa677
/test/client.cpp
27829b27932774ae21d07369e4cb2b02fb4f3370
[]
no_license
shiThomas/Stock_Exchange_Matching_Server
7b4f12ed2ac1cec89b3ed0e7e83c7e58802e3e21
656dc98e15983e2291dba22bdcd6394032ec1eb3
refs/heads/master
2020-05-07T20:23:25.654410
2019-04-11T18:52:51
2019-04-11T18:52:51
180,857,736
1
0
null
null
null
null
UTF-8
C++
false
false
2,826
cpp
#include <arpa/inet.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <cstring> #include <fstream> #include <iostream> int status; // int player_fd; int len; int player_id; int port_num_master; struct sockaddr_in master_sock; char buffer[40960]; struct hostent *master_host_addr; struct sockaddr_in player_in; const char *port; using namespace std; int set_client(const char *host, int port_num_master) { master_sock.sin_family = AF_INET; master_sock.sin_port = htons(port_num_master); memcpy(&master_sock.sin_addr, master_host_addr->h_addr_list[0], master_host_addr->h_length); int player_fd = socket(AF_INET, SOCK_STREAM, 0); if (player_fd == -1) { cerr << "Error: cannot create socket" << endl; cerr << " (" << host << "," << port << ")" << endl; exit(-1); } // if status = connect(player_fd, (struct sockaddr *)&master_sock, sizeof(master_sock)); ; if (status == -1) { cerr << "Error: cannot connect to socket" << endl; cerr << " (" << host << "," << port << ")" << endl; exit(-1); } // if char plyr_id[64]; // len = recv(player_fd, plyr_id, sizeof(plyr_id), 0); plyr_id[len] = '\0'; return player_fd; // player_id = atoi(plyr_id); } void request(int fd, string fn) { ifstream in(fn.c_str()); string all, line; while (getline(in, line)) all += line + "\r\n"; // const char * message = "hi there!"; const char *message = all.c_str(); cout << message << endl; // send(socket_fd, all, all.size(), 0); send(fd, message, strlen(message), 0); // cout << "send success" << endl; // sleep(3); char receive_msg[40960]; len = recv(fd, receive_msg, sizeof(receive_msg), 0); receive_msg[len] = '\0'; cout << receive_msg << endl; // sleep(3); } int main(int argc, char *argv[]) { srand(time(NULL)); const char *host = NULL; if (argc != 4) { cout << "Syntax:" << argv[0] << "<machine_name> <port_num><filename>" << endl; return 1; } master_host_addr = gethostbyname(argv[1]); if (master_host_addr == NULL) { fprintf(stderr, "%s: host not found (%s)\n", argv[0], host); exit(1); } host = argv[1]; port = argv[2]; port_num_master = atoi(argv[2]); // acquire player_id here; int fd = set_client(host, port_num_master); // server set up // cout << user_id << endl; /* The following lines are used to test transferring files */ // string fn = "trans.xml"; char *fn_str = argv[3]; string fn(fn_str); request(fd, fn); close(fd); /* close(fd); fd = set_client(host, port_num_master); request(fd, "trans1.xml"); close(fd); */ return 0; }
[ "ws146@duke.edu" ]
ws146@duke.edu
e37c5fa9664d0b9c5753c787d5099ca8fa531ebb
fec81bfe0453c5646e00c5d69874a71c579a103d
/blazetest/src/mathtest/operations/smatsmatadd/UCaMZb.cpp
fed21f33bdd67725bddd0141ab69cc16ec5501e9
[ "BSD-3-Clause" ]
permissive
parsa/blaze
801b0f619a53f8c07454b80d0a665ac0a3cf561d
6ce2d5d8951e9b367aad87cc55ac835b054b5964
refs/heads/master
2022-09-19T15:46:44.108364
2022-07-30T04:47:03
2022-07-30T04:47:03
105,918,096
52
7
null
null
null
null
UTF-8
C++
false
false
4,202
cpp
//================================================================================================= /*! // \file src/mathtest/operations/smatsmatadd/UCaMZb.cpp // \brief Source file for the UCaMZb sparse matrix/sparse matrix addition math test // // Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedMatrix.h> #include <blaze/math/UpperMatrix.h> #include <blaze/math/ZeroMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/operations/smatsmatadd/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'UCaMZb'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Matrix type definitions using UCa = blaze::UpperMatrix< blaze::CompressedMatrix<TypeA> >; using MZb = blaze::ZeroMatrix<TypeB>; // Creator type definitions using CUCa = blazetest::Creator<UCa>; using CMZb = blazetest::Creator<MZb>; // Running tests with small matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=UCa::maxNonZeros( i ); ++j ) { RUN_SMATSMATADD_OPERATION_TEST( CUCa( i, j ), CMZb( i, i ) ); } } // Running tests with large matrices RUN_SMATSMATADD_OPERATION_TEST( CUCa( 67UL, 7UL ), CMZb( 67UL, 67UL ) ); RUN_SMATSMATADD_OPERATION_TEST( CUCa( 128UL, 16UL ), CMZb( 128UL, 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix addition:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
41e6d7fa77ce74257b3cfbf3e78d06161c36d967
1d529373f57a1d351dcf4eb01582bdc685857111
/SmoothCam/source/camera_states/thirdperson_horse.cpp
05e94e2285f727de04bd7e8000286aa6b5dd9b49
[]
no_license
ciathyza/SkyrimSE-SmoothCam
dcb563ffdaf393619584c5704024da0ef5ba7b88
cd91c92927b07a3bf2c180dd0be3767fd7fec2a3
refs/heads/master
2022-12-29T08:21:19.404326
2020-10-13T06:58:52
2020-10-13T06:58:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,749
cpp
#include "camera_states/thirdperson_horse.h" #include "camera.h" Camera::State::ThirdpersonHorseState::ThirdpersonHorseState(Camera::SmoothCamera* camera) noexcept : BaseCameraState(camera) { } void Camera::State::ThirdpersonHorseState::OnBegin(const PlayerCharacter* player, const CorrectedPlayerCamera* camera) { } void Camera::State::ThirdpersonHorseState::OnEnd(const PlayerCharacter* player, const CorrectedPlayerCamera* camera) { } void Camera::State::ThirdpersonHorseState::Update(PlayerCharacter* player, const CorrectedPlayerCamera* camera) { // Get our computed local-space xyz offset. const auto cameraLocal = GetCameraLocalPosition(player, camera); // Get the base world position for the camera which we will offset with the local-space values. const auto worldTarget = GetCameraWorldPosition(player, camera); // Transform the camera offsets based on the computed view matrix const auto transformedLocalPos = GetTransformedCameraLocalPosition(player, camera); // Define the starting point for our raycast const auto start = worldTarget + glm::vec3(0.0f, 0.0f, cameraLocal.z); glm::vec3 localPos; glm::vec3 preFinalPos; if (GetConfig()->separateLocalInterp) { // Handle separate local-space interpolation // Interpolate the local position (rotation and translation offsets) localPos = UpdateInterpolatedLocalPosition(player, transformedLocalPos); // And the world target const auto lerpedWorldPos = UpdateInterpolatedWorldPosition(player, worldTarget, glm::length(GetLastWorldPosition() - worldTarget)); // Compute offset clamping if enabled const auto clampedWorldPos = ComputeOffsetClamping(player, start, lerpedWorldPos); StoreLastWorldPosition(clampedWorldPos); // Construct the final position preFinalPos = clampedWorldPos + localPos; } else { // Combined case // Add the final local space transformation to the player postion const auto targetWorldPos = worldTarget + transformedLocalPos; // Now lerp it based on camera distance to player position const auto lerpedWorldPos = UpdateInterpolatedWorldPosition(player, targetWorldPos, glm::length(targetWorldPos - worldTarget)); // Compute offset clamping if enabled preFinalPos = ComputeOffsetClamping(player, camera, transformedLocalPos, worldTarget, lerpedWorldPos); StoreLastWorldPosition(preFinalPos); localPos = lerpedWorldPos - worldTarget; } // Cast our ray and update the camera position const auto finalPos = ComputeRaycast(start, preFinalPos); // Set the position SetCameraPosition(finalPos, camera); // Feed our local position offsets to the game camera state for correct crosshair alignment ApplyLocalSpaceGameOffsets(localPos, player, camera); // Update crosshair UpdateCrosshair(player, camera); }
[ "mwilsnd@gmail.com" ]
mwilsnd@gmail.com
1bad1384a3777807f5a3674e8037594d251c8ed2
51632023d380d8a561be668a88bc264531531a77
/Library.h
ba9ecb09c4629201e13b230def051b8ab3ead706
[]
no_license
OmegaSyrus/comp2404-A4
77cae61e8a9a63156c2159b352881916a6a8e887
2c3308c8758f841e874b4a4741ea0163ca474db0
refs/heads/master
2021-01-19T14:52:50.906489
2014-11-20T16:29:22
2014-11-20T16:29:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,019
h
#ifndef LIBRARY_H #define LIBRARY_H #include <string> #include "types.h" #include "Book.h" #include "Patron.h" #include "PDeque.h" #include "PatronArray.h" #include "BookArray.h" #include "Storage.h" using namespace std; class Library { public: Library(); ~Library(); void init(); int addBook(Book*); int addPatron(Patron*); int remPatron(int); void remPatron(Patron*); int findBook(int, Book**, int*); Book* findBook(int); int findPatron(string, string, Patron**, int*); Patron* findPatron(string, string); int getMaxCollIndex(); int getMaxPatronsIndex(); BookArray* GetBooks(); PDeque* GetPatrons(); void getStorage(); Book* getBook(int); Patron* getPatron(int); void addDependent(Patron*, Patron*); private: //Book* collection[MAX_COLL_SIZE]; //Patron* patrons[MAX_COLL_SIZE]; //int maxCollIndex; //int maxPatronsIndex; BookArray* books; PDeque* patroncollection; Storage* storage; }; #endif
[ "Omega_Syrus@hotmail.com" ]
Omega_Syrus@hotmail.com
bf4e85ef79f3388c3e4aefb26a532a6ad90a1594
073f5571fd887fcc22d82c9296b1b70203297ac0
/B/05-template/specialzation/Lookup.cpp
83fe8627bbe660c6c388751572a1baac1467727f
[]
no_license
haolaoshi/thinkingincpp
8f51408b055828335800e2511403679ec4f2ae89
1c9bcc13673e1e5af9e40b8fe0a0045ad520cd7c
refs/heads/master
2023-07-11T15:14:11.296776
2021-08-08T15:31:28
2021-08-08T15:31:28
174,854,234
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
#include <iostream> using std::cout; using std::endl; void f(double){cout << "fdouble" << endl;} template<class T> class X{ public: void g(){f(1);} }; void f(int){cout << " fint" << endl;} int main() { X<int>().g(); }
[ "liujiahao.oak@gmail.com" ]
liujiahao.oak@gmail.com
bcc53bbe3b574804d6051b2d3f1a98478b79f3b5
ade8ecf6afcd34572f6ae9e258b121cb6fc0a763
/Marlin/ErrorReport.h
351944144089c1a7201321a9c20a120d969a4286
[ "MIT" ]
permissive
radtek/Marlin
9d098b892cc7717f87cafaa281caad84a8c7e746
f97b93155f29abec5438a5c15d70e592e727b90b
refs/heads/master
2020-07-16T19:36:15.377379
2019-09-01T17:44:00
2019-09-01T17:44:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,640
h
///////////////////////////////////////////////////////////////////////////////// // // SourceFile: ErrorReport.h // // Marlin Server: Internet server/client // // Copyright (c) 2015-2018 ir. W.E. Huisman // 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. // #pragma once class StackTrace; class HTTPMessage; struct _EXCEPTION_POINTERS; extern __declspec(thread) bool g_exception; extern __declspec(thread) bool g_reportException; // To be called before program begins running void PrepareProcessForSEH(); // To be called after SEH handlers are used void ResetProcessAfterSEH(); class ErrorReport { public: ErrorReport(); virtual ~ErrorReport(); // Send an error report static void Report(const CString& p_subject,unsigned int p_skip, CString p_directory,CString p_url); static void Report(const CString& p_subject,const StackTrace& p_trace,CString p_directory,CString p_url); static void Report(int p_signal ,unsigned int p_skip, CString p_directory,CString p_url); static bool Report(DWORD p_error,struct _EXCEPTION_POINTERS* p_exc, CString& p_directory,CString& p_url); static bool Report(DWORD p_error,struct _EXCEPTION_POINTERS* p_exc); // Multi threading CRITICAL_SECTION m_lock; // Locking on a thread basis protected: // Go send an error report virtual void DoReport(const CString& p_subject ,const StackTrace& p_trace ,const CString& p_webroot ,const CString& p_url) const; };
[ "edwig.huisman@hetnet.nl" ]
edwig.huisman@hetnet.nl
ea787132a7e3c1a8a7be3f330719d3c7de69b6f7
ed2706cb30e7cd66fe1feb2ceec1cd8e00a0ef26
/include/io/date.hh
ef58e2c4ddef50cdc2efe6e5de8ea0fab8eb9737
[ "MIT" ]
permissive
king1600/valk
736634a361a13eaf92ece8f4953239131cf2f8c0
b376a0dcce522ae03ced7d882835e4dea98df86e
refs/heads/master
2021-01-01T20:02:14.595013
2017-10-27T11:38:23
2017-10-27T11:38:23
98,746,792
0
1
null
null
null
null
UTF-8
C++
false
false
2,054
hh
#pragma once namespace io { class Date { private: std::tm dtime; public: inline Date() : Date(now()) {} inline Date(const std::time_t _time) { dtime = *(std::gmtime(&_time)); } inline Date(const std::string &datetime) { static const char* format = "%Y-%m-%dT%H:%M:%SZ"; std::istringstream ss{ datetime.c_str() }; ss >> std::get_time(&dtime, format); } inline static std::time_t now() { return std::time(nullptr); } inline const int day() const { return dtime.tm_mday; } inline const int year() const { return dtime.tm_year + 1900; } inline const int month() const { return dtime.tm_mon + 1; } inline const int secs() const { return dtime.tm_sec; } inline const int mins() const { return dtime.tm_min; } inline const int hours() const { return dtime.tm_hour; } inline const std::time_t getTime() const { return std::mktime((std::tm*)(&dtime)); } inline std::string toString() { char t[126] = {0}; static const char* format = "%Y-%m-%dT%H:%M:%SZ"; std::strftime(t, sizeof(t), format, &dtime); return std::string(t); } inline Date operator+(const Date& other) { return Date(this->getTime() + other.getTime()); } inline Date operator-(const Date& other) { return Date(this->getTime() - other.getTime()); } inline const bool operator> (const Date& d2) { return this->getTime() > d2.getTime(); } inline const bool operator<= (const Date& d2) { return this->getTime() <= d2.getTime(); } inline const bool operator< (const Date& d2) { return this->getTime() < d2.getTime(); } inline const bool operator>= (const Date& d2) { return this->getTime() >= d2.getTime(); } inline operator const char*() { return this->toString().c_str(); } inline friend std::ostream& operator<<(std::ostream &s, Date& d) { s << d.toString(); return s; } }; }
[ "3dsarcard@gmail.com" ]
3dsarcard@gmail.com
08ad5525541d725090015548f2f1e754783c6852
d31418056028cde6c00bcb227be50473f3233edf
/src/sentis_m100_node.cpp
f4bd8a1b61b78746c00a84ca3ebeb9425c2092c2
[]
no_license
akihikoy/lfd_vision.old
6fdb5d16a8b3b92508d4e6e7f507d837434e16ce
84124f36d4c6e79630e77cc3bb4432ae0aecd68c
refs/heads/master
2021-05-03T06:01:59.887056
2016-02-05T20:49:19
2016-02-05T20:49:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,202
cpp
//------------------------------------------------------------------------------------------- /*! \file sentis_m100_node.cpp \brief Load data from Sentis M100 and send it as a point cloud topic. \author Akihiko Yamaguchi, info@akihikoy.net \version 0.1 \date Apr.22, 2015 */ //------------------------------------------------------------------------------------------- #include "lfd_vision/sentis_m100.h" // #include "lfd_vision/geom_util.h" //------------------------------------------------------------------------------------------- #include "lfd_vision/ReadRegister.h" #include "lfd_vision/WriteRegister.h" #include "lfd_vision/SetFrameRate.h" //------------------------------------------------------------------------------------------- #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <pcl/ros/conversions.h> #include <pcl_conversions/pcl_conversions.h> // #include <pcl/filters/passthrough.h> //------------------------------------------------------------------------------------------- namespace trick { inline double GetCurrentTime(void) { struct timeval time; gettimeofday (&time, NULL); return static_cast<double>(time.tv_sec) + static_cast<double>(time.tv_usec)*1.0e-6; // return ros::Time::now().toSec(); } class TSentisM100Node : public TSentisM100 { public: TSentisM100Node(ros::NodeHandle &node) : TSentisM100(), node_(node) { srv_write_register_= node_.advertiseService("write_register", &TSentisM100Node::SrvWriteRegister, this); srv_read_register_= node_.advertiseService("read_register", &TSentisM100Node::SrvReadRegister, this); srv_set_frame_rate_= node_.advertiseService("set_frame_rate", &TSentisM100Node::SrvSetFrameRate, this); } bool SrvWriteRegister(lfd_vision::WriteRegister::Request &req, lfd_vision::WriteRegister::Response &res) { res.success= WriteRegister(req.address, req.value); return true; } bool SrvReadRegister(lfd_vision::ReadRegister::Request &req, lfd_vision::ReadRegister::Response &res) { res.value= ReadRegister(req.address); res.success= IsNoError(""); return true; } bool SrvSetFrameRate(lfd_vision::SetFrameRate::Request &req, lfd_vision::SetFrameRate::Response &res) { res.success= SetFrameRate(req.frame_rate); return true; } private: ros::NodeHandle &node_; ros::ServiceServer srv_write_register_; ros::ServiceServer srv_read_register_; ros::ServiceServer srv_set_frame_rate_; }; //------------------------------------------------------------------------------------------- } //------------------------------------------------------------------------------------------- using namespace std; // using namespace boost; using namespace trick; //------------------------------------------------------------------------------------------- // #define print(var) PrintContainer((var), #var"= ") // #define print(var) std::cout<<#var"= "<<(var)<<std::endl //------------------------------------------------------------------------------------------- int main(int argc, char**argv) { ros::init(argc, argv, "sentis_m100"); ros::NodeHandle node("~"); int init_fps, tcp_port, udp_port, integ_time; std::string tcp_ip, udp_ip; node.param("init_fps",init_fps,1); node.param("tcp_ip",tcp_ip,std::string("192.168.0.10")); node.param("udp_ip",udp_ip,std::string("224.0.0.1")); node.param("tcp_port",tcp_port,10001); node.param("udp_port",udp_port,10002); node.param("integ_time",integ_time,573); // M100_IMAGE_WIDTH,M100_IMAGE_HEIGHT ros::Publisher pub_cloud= node.advertise<sensor_msgs::PointCloud2>("depth_non_filtered", 1); // ros::Publisher pub_cloud= node.advertise<pcl::PointCloud<pcl::PointXYZ> >("/depth_non_filtered", 1); TSentisM100Node tof_sensor(node); tof_sensor.Init(init_fps, /*data_format=*/XYZ_COORDS_DATA, tcp_ip.c_str(), udp_ip.c_str(), tcp_port, udp_port, integ_time); // tof_sensor.PrintRegisters(0); tof_sensor.PrintRegisters(1); // tof_sensor.SetFrameRate(40); double t_start= GetCurrentTime(); ros::Rate loop_rate(40); // 40 Hz for(int f(0); ros::ok(); ++f) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>()); if(!tof_sensor.GetDataAsPointCloud(cloud)) continue; // const double max_depth(0.5); // pcl::PassThrough<pcl::PointXYZ> pass; // pass.setInputCloud(cloud); // pass.setFilterFieldName("z"); // pass.setFilterLimits(-100.0, max_depth); // pass.filter(*cloud); sensor_msgs::PointCloud2 cloud_msg; pcl::toROSMsg(*cloud,cloud_msg); cloud_msg.header.frame_id= "tf_sentis_tof"; cloud_msg.header.stamp= ros::Time::now(); pub_cloud.publish(cloud_msg); if(f%100==0) { double duration= GetCurrentTime()-t_start; std::cerr<<"Duration: "<<duration<<std::endl; std::cerr<<"FPS: "<<double(100)/duration<<std::endl; t_start= GetCurrentTime(); } ros::spinOnce(); loop_rate.sleep(); } tof_sensor.Sleep(); // ros::spin(); return 0; } //-------------------------------------------------------------------------------------------
[ "info@akihikoy.net" ]
info@akihikoy.net
d67f9a219b36b76d87a2cb1278323250728ce7ea
246a16842feb7633edbe6291ff36b4c93edbb3c7
/rxcpp-first/61_create_asio_timer.cpp
185c6d3eea645ac87478a498ca717d001bda3235
[]
no_license
curtkim/c-first
2c223949912c708734648cf29f98778249f79346
f6fa50108ab7c032b74199561698cef087405c37
refs/heads/master
2023-06-08T10:57:35.159250
2023-05-28T05:52:20
2023-05-28T05:52:20
213,894,731
3
1
null
null
null
null
UTF-8
C++
false
false
2,272
cpp
#include <thread> #include <rxcpp/rx.hpp> #include <asio.hpp> #include "rx-asio.hpp" int main() { asio::io_context io_context; asio::system_timer timer(io_context,std::chrono::system_clock::now() + std::chrono::seconds(2)); std::cout << std::this_thread::get_id() << " main thread" << std::endl; auto asio_coordinate = rxcpp::observe_on_asio(io_context); // create auto ints = rxcpp::sources::create<int>( [&timer](rxcpp::subscriber<int> s) { std::cout << std::this_thread::get_id() << " in create" << std::endl; std::cout << std::this_thread::get_id() << " " << s.get_id() << " s.is_subscribed() " << s.is_subscribed() << std::endl; s.on_next(1); // why &s don't work?? timer.async_wait([s](const asio::error_code & error) { std::cout << std::this_thread::get_id() << " in timer" << std::endl; std::cout << std::this_thread::get_id() << " error: " << error << std::endl; if( error){ std::cout << "error" << std::endl; } std::cout << std::this_thread::get_id() << " " << s.get_id() << " s.is_subscribed() " << s.is_subscribed() << std::endl; s.on_next(2); std::cout << std::this_thread::get_id() << " on_next" << std::endl; s.on_completed(); std::cout << std::this_thread::get_id() << " on_completed" << std::endl; }); });//.subscribe_on(asio_coordinate);//.publish(); ints //.observe_on(asio_coordinate) //.observe_on(rxcpp::synchronize_new_thread()) .observe_on(rxcpp::observe_on_new_thread()) //.observe_on(rxcpp::observe_on_asio(io_context)) .subscribe( [](int v) { std::cout << std::this_thread::get_id() << " onNext ===> " << v << std::endl; }, []() { std::cout << std::this_thread::get_id() << " onComplete " << std::endl; } ); //ints.connect(); std::thread thread([&io_context](){ std::cout << std::this_thread::get_id() << " io_context thread" << std::endl; io_context.run(); }); thread.join(); //io_context.stop(); //std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << std::this_thread::get_id() << " end" << std::endl; return 0; }
[ "iamteri@gmail.com" ]
iamteri@gmail.com
e50143d14190faa1c58ac608ccd244c14dfddb73
159f65e94429be116eb8839c8bba2aeca4a19b8b
/ModuleFileSystem.h
7151288870a19c61e2e5a8f95faa86a3b38f8fba
[ "MIT" ]
permissive
GBMiro/GomuGomuEngine
863e09affd5543a8fce8ea9586693ffc92a29f07
c9ee5ef94a3c9aeb9697582b568b646c43bacef2
refs/heads/master
2023-02-19T04:08:20.318346
2021-01-17T19:36:31
2021-01-17T19:36:31
312,783,989
0
0
null
null
null
null
UTF-8
C++
false
false
876
h
#pragma once #include <string> #include <vector> #include "Module.h" class ModuleFileSystem : public Module { public: ModuleFileSystem(); ~ModuleFileSystem(); bool Init(); unsigned int Load(const char* path, const char* file, char** buffer) const; unsigned int Load(const char* file, char** buffer) const; unsigned int Save(const char* file, const void* buffer, unsigned int size, bool append = false) const; bool Remove(const char* file); bool Exists(const char* file) const; bool Copy(const char* source, const char* destination); bool MakeDirectory(const char* directory); bool IsDirectory(const char* file) const; void GetFileName(const char* path, std::string& name) const; void GetFileNameNoExtension(const std::string& filename, std::string& name) const; void GetDirectoryFiles(const std::string& path, std::vector<std::string>& files) const; };
[ "guillemburguesmiro@gmail.com" ]
guillemburguesmiro@gmail.com
57bd8b71857b714ffee415dc2a7cbb61939b1fdc
b83decbcf1320d7e29eacfcf1bc382e28c0cb3f2
/Chapter 1/The Clocks.cpp
cf091274fcb59a663fd48e4a17fdbd694f3084b6
[]
no_license
maliemin-Mstar/USACO_TRAINING
75a183a950dae894996830f1c5b7b3292b5b515a
57ef6d4ebcf2284270fc894a41115a14a2e0e4d2
refs/heads/master
2020-05-30T14:39:49.731918
2014-03-21T09:18:18
2014-03-21T09:18:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,340
cpp
/* ID: maliemi2 PROG: clocks LANG: C++ */ #include<iostream> #include<queue> #include <fstream> #include<cstdio> #include<cstring> #include<algorithm> #define SIZE 22 using namespace std; int times[10], myclock[10], min_t, ans[100]; int change[10][10] = { {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 0, 1, 1, 0, 0, 0, 0}, {0, 1, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 1, 1, 0, 1, 1, 0, 0, 0}, {0, 1, 0, 0, 1, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 1, 1, 1, 0, 1, 0}, {0, 0, 0, 1, 0, 0, 1, 0, 0, 1}, {0, 0, 0, 0, 1, 1, 0, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 1}, {0, 0, 0, 0, 0, 1, 1, 0, 1, 1} }; void copy(int a[]) { for (int i = 1; i < 10; i++) a[i] = myclock[i]; } void turn(int a[]) { for (int i = 1; i < 10; i++) { if(!times[i]) continue; for (int j = 1; j < 10; j++) { a[j] += times[i] * change[i][j]; } } for (int i = 1; i < 10; i++) { a[i] %= 4; } } int total() { int sum = 0; for (int i = 1; i < 10; i++) sum += times[i]; return sum; } bool finish(int a[]) { for (int i = 1; i < 10; i++) { if(a[i] != 3) return 0; } return 1; } void write() { int k = 0; for (int i = 1; i < 10; i++) { if (times[i]) { for (int j = 0; j < times[i]; j++) ans[k++] = i; } } } int main() { ofstream fout ("clocks.out"); ifstream fin ("clocks.in"); int i, j; min_t = 100; for (i = 1; i < 10; i++) { fin >> myclock[i]; myclock[i] /= 3; myclock[i]--; } for (times[9] = 0; times[9] < 4; times[9]++) { for (times[8] = 0; times[8] < 4; times[8]++) { for (times[7] = 0; times[7] < 4; times[7]++) { for (times[6] = 0; times[6] < 4; times[6]++) { for (times[5] = 0; times[5] < 4; times[5]++) { for (times[4] = 0; times[4] < 4; times[4]++) { for (times[3] = 0; times[3] < 4; times[3]++) { for (times[2] = 0; times[2] < 4; times[2]++) { for (times[1] = 0; times[1] < 4; times[1]++) { int temp[10]; copy(temp); turn(temp); if(finish(temp)) { int t; t = total(); if (t < min_t) { min_t = t; write(); } } } } } } } } } } } for (i = 0; i < min_t - 1; i++) fout << ans[i] << ' '; fout << ans[i] << endl; return 0; }
[ "maliemin.jj@gmail.com" ]
maliemin.jj@gmail.com
fb7a506a1cec5e01be66895a1de46c023b77899e
ae806d7bca22cac9fe98f9fe4b052a6b68fba7a1
/codeforces/705A.cpp
d041e9a238573f6bb06e8f9ce92c83ded967434a
[]
no_license
AkmalAbdullayev/competitive-programming
09e2c2929f1b33d61a22ca687ba5fbf1c93b24b9
8ef890469eb57bee919b14824f600f5a9944dbbe
refs/heads/master
2023-03-21T00:49:46.396518
2021-03-25T20:17:01
2021-03-25T20:17:01
347,411,783
0
0
null
null
null
null
UTF-8
C++
false
false
72
cpp
#include <iostream> using namespace std; int main() { return 0; }
[ "akmalabdullayev1512@gmail.com" ]
akmalabdullayev1512@gmail.com
832e8727469da486deb4d0699a6f282c7f84b846
3d61fb5fd6b7ff21450e14d5fe49be3aedbbe1e4
/Philotes/EditorFrame/3rdlibs/xtp1501/SyntaxEdit/XTPSyntaxEditStruct.h
771ff025d4a9c62ef467a10aad8c8c1c85e85310
[]
no_license
yannicpeng/erbiqingnian
b3731805b11484ce99b39ba9937f848810001a44
ead102ba873ee3fa163d61c474cfd32147db6c1d
refs/heads/master
2021-03-12T22:28:00.617820
2012-05-26T05:24:53
2012-05-26T05:24:53
33,162,785
0
0
null
null
null
null
UTF-8
C++
false
false
18,476
h
// XTPSyntaxEditStruct.h // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME SYNTAX EDIT LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ////////////////////////////////////////////////////////////////////// //{{AFX_CODEJOCK_PRIVATE #if !defined(__XTPSYNTAXEDITSTRUCT_H__) #define __XTPSYNTAXEDITSTRUCT_H__ //}}AFX_CODEJOCK_PRIVATE #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Common/XTPColorManager.h" namespace XTPSyntaxEditLexAnalyser { class CXTPSyntaxEditLexTextBlock; } class CXTPSyntaxEditCtrl; //=========================================================================== // max line: 1 048 575 // max col: 4 095 //=========================================================================== #define XTP_EDIT_XLC(nL, nC) ( (((DWORD)nL) << 12) | (((DWORD)nC) & 0x00000FFF)) //=========================================================================== // Summary: // XTP_EDIT_LINECOL structure represents coordinates of text items on the // displaying context in terms of line/column. //=========================================================================== struct _XTP_EXT_CLASS XTP_EDIT_LINECOL { int nLine; // stores line identifier int nCol; // stores column identifier static const XTP_EDIT_LINECOL MAXPOS; // maximum position value static const XTP_EDIT_LINECOL MINPOS; // minimum position value static const XTP_EDIT_LINECOL Pos1; // {1,0} position value //---------------------------------------------------------------------- // Summary: // Constructs XTP_EDIT_LINECOL from the pair of coordinates // (line and column). // Parameters: // nParamLine : [in] Line identifier. // nParamCol : [in] Column identifier. //---------------------------------------------------------------------- static const XTP_EDIT_LINECOL MakeLineCol(int nParamLine, int nParamCol); //---------------------------------------------------------------------- // Summary: // This static functions are used to get minimum or maximum of 2 // XTP_EDIT_LINECOL values. // Parameters: // pos1 : [in] First value. // pos2 : [in] Second value. //---------------------------------------------------------------------- static const XTP_EDIT_LINECOL min2(const XTP_EDIT_LINECOL& pos1, const XTP_EDIT_LINECOL& pos2); static const XTP_EDIT_LINECOL max2(const XTP_EDIT_LINECOL& pos1, const XTP_EDIT_LINECOL& pos2); // <COMBINE XTP_EDIT_LINECOL::min2@const XTP_EDIT_LINECOL&@const XTP_EDIT_LINECOL&> //---------------------------------------------------------------------- // Summary: // Returns coordinates in the packed form. // Returns: // DWORD value. //---------------------------------------------------------------------- DWORD GetXLC() const; //---------------------------------------------------------------------- // Summary: // Returns data validation flag. // Returns: // TRUE if line/column identifiers > 0; FALSE otherwise //---------------------------------------------------------------------- BOOL IsValidData() const; //---------------------------------------------------------------------- // Summary: // Clears data members. // Remarks: // Call this member function to set line/column coordinates to 0. //---------------------------------------------------------------------- void Clear(); //---------------------------------------------------------------------- // Summary: // Less than operator. Compares current struct with given. // Parameters: // pos2 : [in] Reference to struct to compare. // Returns: // TRUE if current struct less than given; FALSE otherwise //---------------------------------------------------------------------- BOOL operator < (const XTP_EDIT_LINECOL& pos2) const; //---------------------------------------------------------------------- // Summary: // Less than or equal operator. Compares current struct with given. // Parameters: // pos2 : [in] Reference to struct to compare. // Returns: // TRUE if current struct less than or equal given; FALSE otherwise //---------------------------------------------------------------------- BOOL operator <= (const XTP_EDIT_LINECOL& pos2) const; //---------------------------------------------------------------------- // Summary: // Greater than operator. Compares current struct with given. // Parameters: // pos2 : [in] Reference to struct to compare. // Returns: // TRUE if current struct greater than given; FALSE otherwise. //---------------------------------------------------------------------- BOOL operator > (const XTP_EDIT_LINECOL& pos2) const; //---------------------------------------------------------------------- // Summary: // Greater or equal operator. Compares current struct with given. // Parameters: // pos2 : [in] Reference to struct to compare. // Returns: // TRUE if current struct greater than or equal given; FALSE otherwise //---------------------------------------------------------------------- BOOL operator >= (const XTP_EDIT_LINECOL& pos2) const; //---------------------------------------------------------------------- // Summary: // Equal operator. Compares current struct with given. // Parameters: // pos2 : [in] Reference to struct to compare. // Returns: // TRUE if current struct equal given; FALSE otherwise //---------------------------------------------------------------------- BOOL operator == (const XTP_EDIT_LINECOL& pos2) const; //---------------------------------------------------------------------- // Summary: // Not Equal operator. Compares current struct with given. // Parameters: // pos2 : [in] Reference to struct to compare. // Returns: // TRUE if current struct not equal given; FALSE otherwise //---------------------------------------------------------------------- BOOL operator != (const XTP_EDIT_LINECOL& pos2) const { return !operator==(pos2); } }; //=========================================================================== // XTP_EDIT_COLORVALUES struct stores the colors for different phrases //=========================================================================== struct _XTP_EXT_CLASS XTP_EDIT_COLORVALUES { CXTPPaintManagerColor crText; // text color CXTPPaintManagerColor crBack; // back color CXTPPaintManagerColor crReadOnlyBack; // back color for read only mode CXTPPaintManagerColor crHiliteText; // text color of selection CXTPPaintManagerColor crHiliteBack; // text color of selection back CXTPPaintManagerColor crInactiveHiliteText; // inactive text color of selection CXTPPaintManagerColor crInactiveHiliteBack; // inactive text color of selection back CXTPPaintManagerColor crLineNumberText; // Line numbers text and line color CXTPPaintManagerColor crLineNumberBack; // Line numbers text and line color //----------------------------------------------------------------------- // Summary: // Assign operator needed for working with CList. // Parameters: // src : [in] Reference to source structure. // Returns: // Reference to XTP_EDIT_COLORVALUES struct. //----------------------------------------------------------------------- const XTP_EDIT_COLORVALUES& operator=(const XTP_EDIT_COLORVALUES& src); //----------------------------------------------------------------------- // Summary: Get corresponding background color for edit mode or for // read-only mode (crBack or crReadOnlyBack member value). // Returns: Background color. // See Also: crBack, crReadOnlyBack //----------------------------------------------------------------------- COLORREF GetBackColorEx(CXTPSyntaxEditCtrl* pEditCtrl); }; //=========================================================================== // XTP_EDIT_ROWSBLOCK struct //=========================================================================== struct _XTP_EXT_CLASS XTP_EDIT_ROWSBLOCK { XTP_EDIT_LINECOL lcStart; // Start position. XTP_EDIT_LINECOL lcEnd; // End Position. CString strCollapsedText; //Collapsed text. //----------------------------------------------------------------------- // Summary: // Default destructor.Handles clean up and deallocation. //----------------------------------------------------------------------- virtual ~XTP_EDIT_ROWSBLOCK(){}; //----------------------------------------------------------------------- // Summary: // Assign operator. // Parameters: // src : [in] Reference to source structure. // Returns: // Reference to XTP_EDIT_COLORVALUES struct. //----------------------------------------------------------------------- const XTP_EDIT_ROWSBLOCK& operator=(const XTP_EDIT_ROWSBLOCK& src); }; typedef CArray<XTP_EDIT_ROWSBLOCK, const XTP_EDIT_ROWSBLOCK&> CXTPSyntaxEditRowsBlockArray; //=========================================================================== // Summary: // Stores collapsed block parameters. // See also: // XTP_EDIT_ROWSBLOCK //=========================================================================== struct _XTP_EXT_CLASS XTP_EDIT_COLLAPSEDBLOCK { XTP_EDIT_ROWSBLOCK collBlock; // Collapsed block parameters CRect rcCollMark; // Rectangle area to display collapsed block // mark. //----------------------------------------------------------------------- // Summary: // Default destructor.Handles clean up and deallocation. //----------------------------------------------------------------------- virtual ~XTP_EDIT_COLLAPSEDBLOCK(){}; //----------------------------------------------------------------------- // Summary: // Assign operator. // Parameters: // src : [in] Reference to source structure. // Returns: // Reference to XTP_EDIT_COLORVALUES struct. //----------------------------------------------------------------------- const XTP_EDIT_COLLAPSEDBLOCK& operator=(const XTP_EDIT_COLLAPSEDBLOCK& src); }; const UINT XTP_EDIT_ROWNODE_NOTHING = 0x00; // Define that row has no node mark. const UINT XTP_EDIT_ROWNODE_COLLAPSED = 0x01; // Define that row has collapsed node mark. const UINT XTP_EDIT_ROWNODE_EXPANDED = 0x02; // Define that row has expanded node mark. const UINT XTP_EDIT_ROWNODE_ENDMARK = 0x04; // Define that row has end node mark. const UINT XTP_EDIT_ROWNODE_NODEUP = 0x10; // Define that row has up-line node mark. const UINT XTP_EDIT_ROWNODE_NODEDOWN = 0x20; // Define that row has down-line node mark. //=========================================================================== // Summary: // Used with XTP_EDIT_FONTOPTIONS struct and define unspecified member value. // See Also: XTP_EDIT_FONTOPTIONS //=========================================================================== #define XTP_EDIT_FONTOPTIONS_UNSPEC_OPTION (BYTE)-1 //=========================================================================== // XTP_EDIT_FONTOPTIONS struct is a self initializing LOGFONT structure that // initializes all values equal to XTP_EDIT_FONTOPTIONS_UNSPEC_OPTION except // for lfFaceName which is set to zero length. // See Also: XTP_EDIT_FONTOPTIONS_UNSPEC_OPTION //=========================================================================== struct _XTP_EXT_CLASS XTP_EDIT_FONTOPTIONS : public LOGFONT { //----------------------------------------------------------------------- // Summary: // Default constructor. //----------------------------------------------------------------------- XTP_EDIT_FONTOPTIONS(); //----------------------------------------------------------------------- // Summary: // Assign operator. // Parameters: // src : [in] Reference to source structure. // Returns: // Reference to XTP_EDIT_FONTOPTIONS struct. //----------------------------------------------------------------------- const XTP_EDIT_FONTOPTIONS& operator=(const XTP_EDIT_FONTOPTIONS& src); }; //=========================================================================== // Summary: XTP_EDIT_TEXTBLOCK structure stores the text blocks after parsing //=========================================================================== struct _XTP_EXT_CLASS XTP_EDIT_TEXTBLOCK { int nPos; // Position int nNextBlockPos; // Position for the next block XTP_EDIT_COLORVALUES clrBlock; // Color for this block XTP_EDIT_FONTOPTIONS lf;// Font options for this block; //----------------------------------------------------------------------- // Summary: // Default constructor. //----------------------------------------------------------------------- XTP_EDIT_TEXTBLOCK(); //----------------------------------------------------------------------- // Summary: // Assign operator. // Parameters: // src : [in] Reference to source structure. // Returns: // Reference to XTP_EDIT_TEXTBLOCK struct. //----------------------------------------------------------------------- const XTP_EDIT_TEXTBLOCK& operator=(const XTP_EDIT_TEXTBLOCK& src); }; //=========================================================================== // Summary: This is used to define row and col selection rect //=========================================================================== struct XTP_EDIT_ROWCOLRECT { int nRow1; // First row index for a text block. int nCol1; // First column index for a text block. int nRow2; // Last row index for a text block. int nCol2; // Last column index for a text block. }; ////////////////////////////// // Notification structures ////////////////////////////// //=========================================================================== // Summary: Bookmark notification structure // Provided as LPARAM with WM_NOTIFY while // bookmarks are needed to be drawn //=========================================================================== struct XTP_EDIT_SENMBOOKMARK { NMHDR nmhdr; // First param should be NMHDR HDC hDC; // HDC for drawing RECT rcBookmark; // RECT for bookmark int nRow; // The row number }; //=========================================================================== // Summary: Row column notification structure // Provided as LPARAM with WM_NOTIFY // This is used to display current row and column //=========================================================================== struct XTP_EDIT_NMHDR_ROWCOLCHANGED { NMHDR nmhdr; // First param should be NMHDR int nRow; // Current document row int nCol; // Current document col }; //=========================================================================== // Summary: Document notification structure // Provided as LPARAM with WM_NOTIFY // used to notify of a change in the document's modified state. //=========================================================================== struct XTP_EDIT_NMHDR_DOCMODIFIED { NMHDR nmhdr; // First param should be NMHDR BOOL bModified; // TRUE if the document was modified. }; //=========================================================================== // Summary: Structure to notify "Edit changed" event //=========================================================================== struct XTP_EDIT_NMHDR_EDITCHANGED { NMHDR nmhdr; // First param should be NMHDR int nRowFrom; // The start row for the action int nRowTo; // The end row for the action int nAction; // The actual action }; //=========================================================================== // Summary: Structure to notify XTP_EDIT_NM_MARGINCLICKED event //=========================================================================== struct XTP_EDIT_NMHDR_MARGINCLICKED { NMHDR nmhdr; // First param should be NMHDR int nRow; // Document row number int nDispRow; // Visible row number (start from 1); }; //=========================================================================== // Summary: Structure to notify XTP_EDIT_NM_UPDATESCROLLPOS event //=========================================================================== struct XTP_EDIT_NMHDR_SETSCROLLPOS { NMHDR nmhdr; // First param should be NMHDR DWORD dwUpdate; // Scroll position update flags can be any combination of XTP_EDIT_UPDATE_HORZ, XTP_EDIT_UPDATE_VERT or XTP_EDIT_UPDATE_DIAG. }; //=========================================================================== // Summary: Structure to notify XTP_EDIT_NM_ENABLESCROLLBAR event //=========================================================================== struct XTP_EDIT_NMHDR_ENABLESCROLLBAR { NMHDR nmhdr; // First param should be NMHDR DWORD dwScrollBar; // Define the scroll bar(s) to change state as WS_HSCROLL and WS_VSCROLL flags. DWORD dwState; // Define the scroll bar(s) state as WS_HSCROLL and WS_VSCROLL flags. }; //=========================================================================== // Summary: Structure to notify XTP_EDIT_NM_PARSEEVENT event //=========================================================================== struct XTP_EDIT_NMHDR_PARSEEVENT { NMHDR nmhdr; // First param should be NMHDR DWORD code; // Parser event. A value from XTPSyntaxEditOnParseEvent enum. WPARAM wParam; // First event parameter. LPARAM lParam; // Second event parameter. }; #endif // !defined(__XTPSYNTAXEDITSTRUCT_H__)
[ "cjlm007@6cb12ae1-4c77-52bf-f227-7ea6b66274e1" ]
cjlm007@6cb12ae1-4c77-52bf-f227-7ea6b66274e1
227c3f60382baf520a2282d890fb489f771ed003
690b60a57f85bdce71e614676c305e2492fb7608
/QCIFSServer/QCIFSProcessor/cProcessPacketMsg.h
fb23b1c2fb885783f74c116a071de66bf2dba735
[ "Apache-2.0" ]
permissive
rodrigomr/VFS
b07886c0a97bf08c2853fa3182e90eba6ff6ff4e
6b68b00df8cb668106c2d0841cbcd46138298717
refs/heads/master
2020-03-30T13:54:59.627030
2018-10-02T12:06:43
2018-10-02T12:06:43
151,293,022
0
0
NOASSERTION
2018-10-02T17:12:38
2018-10-02T17:12:46
null
UTF-8
C++
false
false
2,593
h
// Copyright 2018 Grass Valley, A Belden Brand // 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. //cProcessPacket.h #pragma once #include "..\common\icompletionmsg.h" class iRXPacket; class iShareManager; class iOpLockManager; class cQCIFSPacketProcessor; template <typename RequestType> class cProcessPacketMsg : public iCompletionMsg, public vfs::cRefCount { public: cProcessPacketMsg(vfs::cPtr<vfs::cMemoryView> pMem , const vfs::cPtr<iRXPacket> pRXPacket , const vfs::cPtr<iShareManager> pShareManager , const vfs::cPtr<iOpLockManager> pOpLockManager , cQCIFSPacketProcessor* pQCIFSPacketProcessor) : m_pMem(pMem) , m_pRXPacket(pRXPacket) , m_pShareManager(pShareManager) , m_pOpLockManager(pOpLockManager) , m_pQCIFSPacketProcessor(pQCIFSPacketProcessor) {} void deliver(ULONG_PTR pCompletionKey, const DWORD dwBytes) { vfs::iActivity::Ptr activity = getActivity(); tResponseList responses; { cActivityScope as1(activity,kGetResponses); RequestType request(m_pRXPacket, m_pShareManager, m_pOpLockManager, m_pQCIFSPacketProcessor); request.getResponses(m_pMem, responses, activity); } cActivityScope as1(activity,kSendResponses); for (tResponseList::const_iterator cit = responses.begin() ; cit != responses.end() ; ++cit) { const cPtr<iResponseWriter>& pResponse = *cit; if (pResponse.isValid()) { cPtr<iTXPacket> pTXPacket = m_pRXPacket->getResponsePacket(); activity->activityStart(kSendResponses+1); pResponse->WritePacket(pTXPacket); activity->activityStart(kSendResponses+2); pTXPacket->Send(); } } } //this shouldn't really happen since the message should be delivered from a 'PostCompletionStatus()' void err(ULONG_PTR pCompletionKey, const DWORD err) {} private: const vfs::cPtr<vfs::cMemoryView> m_pMem; const vfs::cPtr<iRXPacket> m_pRXPacket; const vfs::cPtr<iShareManager> m_pShareManager; const vfs::cPtr<iOpLockManager> m_pOpLockManager; cQCIFSPacketProcessor* m_pQCIFSPacketProcessor; };
[ "drjwcain@gmail.com" ]
drjwcain@gmail.com
f9335e50c9e572dacac6e3a1d9121e3e4f9d6f4d
0d11203e6a143b2383b5baa8a9a2b3e48383c9b1
/DSA09007.cpp
acb1d5ac778fd602f8f725c18d9589cc2a955e2f
[]
no_license
namnguyen215/CTDLGT
c36b8526b3af00ea2d4bd113efe378f95091f895
6e7e602940fb5c28b7af830f44f58443375b7666
refs/heads/main
2023-06-25T08:48:47.269848
2021-07-21T16:36:36
2021-07-21T16:36:36
360,927,428
2
1
null
null
null
null
UTF-8
C++
false
false
1,371
cpp
#include<bits/stdc++.h> using namespace std; vector<int> ke[1007]; int truoc[1007]; bool chuaxet[1007]; int v,e,v1,v2,start,des; void init() { memset(chuaxet,true,sizeof(chuaxet)); for(int i=1;i<=v;i++) truoc[i]=-1; for(int i=1;i<=v;i++) ke[i].clear(); } void BFS(int start,int des) { queue<int> q; chuaxet[start]=false; q.push(start); while(!q.empty()) { int s=q.front(); q.pop(); for(int i=0;i<ke[s].size();i++) { if(chuaxet[ke[s][i]]) { q.push(ke[s][i]); chuaxet[ke[s][i]]=false; truoc[ke[s][i]]=s; } } } } void print(int start,int des) { if(chuaxet[des]) cout<<-1<<endl ; else { vector<int> vt; while(des!=start) { vt.push_back(des); des=truoc[des]; } vt.push_back(start); reverse(vt.begin(),vt.end()); for(int i=0;i<vt.size();i++) cout<<vt[i]<<" "; cout<<endl; } } int main() { int t;cin>>t; while(t--) { init(); cin>>v>>e>>start>>des; for(int i=0;i<e;i++) { cin>>v1>>v2; ke[v1].push_back(v2); ke[v2].push_back(v1); } BFS(start,des); print(start,des); } }
[ "namnguyenphuong215@gmail.com" ]
namnguyenphuong215@gmail.com
a87c0ea8e7c1d272c54fd0c9f997c1662fcb857c
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/rtorrent/gumtree/rtorrent_new_hunk_216.cpp
a613990caf20b594e6d0b13942f04c6adb7fdb26
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,265
cpp
control->command_scheduler()->parse(arg1, arg2, arg3, rpc::convert_list_to_command(itr, args.end())); return torrent::Object(); } torrent::Object apply_load(int flags, const torrent::Object& rawArgs) { const torrent::Object::list_type& args = rawArgs.as_list(); torrent::Object::list_type::const_iterator argsItr = args.begin(); if (argsItr == args.end()) throw torrent::input_error("Too few arguments."); const std::string& filename = argsItr->as_string(); core::Manager::command_list_type commands; while (++argsItr != args.end()) commands.push_back(argsItr->as_string()); control->core()->try_create_download_expand(filename, flags, commands); return torrent::Object(); } void apply_import(const std::string& path) { if (!rpc::parse_command_file(path)) throw torrent::input_error("Could not open option file: " + path); } void apply_try_import(const std::string& path) { if (!rpc::parse_command_file(path)) control->core()->push_log_std("Could not read resource file: " + path); } void apply_close_low_diskspace(int64_t arg) { core::DownloadList* downloadList = control->core()->download_list(); core::Manager::DListItr itr = downloadList->begin(); while ((itr = std::find_if(itr, downloadList->end(), std::mem_fun(&core::Download::is_downloading))) != downloadList->end()) { if ((*itr)->file_list()->free_diskspace() < (uint64_t)arg) { downloadList->close(*itr); (*itr)->set_hash_failed(true); (*itr)->set_message(std::string("Low diskspace.")); } ++itr; } } torrent::Object apply_download_list(const torrent::Object& rawArgs) { const torrent::Object::list_type& args = rawArgs.as_list(); torrent::Object::list_type::const_iterator argsItr = args.begin(); core::ViewManager* viewManager = control->view_manager(); core::ViewManager::iterator viewItr; if (argsItr != args.end() && !argsItr->as_string().empty()) viewItr = viewManager->find((argsItr++)->as_string()); else viewItr = viewManager->find("default"); if (viewItr == viewManager->end()) throw torrent::input_error("Could not find view."); torrent::Object result(torrent::Object::TYPE_LIST); torrent::Object::list_type& resultList = result.as_list();
[ "993273596@qq.com" ]
993273596@qq.com
4ea1c261b2be7235e46514c9f9ac90ebe317186c
c95c22428deebd225e0f46451adf7b2108f6b870
/TFG-Project/Dependencies/NUMCPP/include/NUMCPP/NumCpp/Random/cauchy.hpp
8357d63a10ae0918a120555fe2ee42f8be36319d
[]
no_license
RubenRubioM/Bipedal-Walking-GA
8702a9d9164d63b69340deec216643861b726e43
d56009b1632a465e278b5311144fb2f1852175b1
refs/heads/master
2023-02-04T21:08:46.345015
2020-12-28T12:04:29
2020-12-28T12:04:29
282,260,484
0
0
null
null
null
null
UTF-8
C++
false
false
3,926
hpp
/// @file /// @author David Pilger <dpilger26@gmail.com> /// [GitHub Repository](https://github.com/dpilger26/NumCpp) /// /// License /// Copyright 2020 David Pilger /// /// 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. /// /// Description /// "cauchy" distrubution. /// #pragma once #include "NumCpp/Core/Internal/Error.hpp" #include "NumCpp/Core/Internal/StaticAsserts.hpp" #include "NumCpp/Core/Internal/StlAlgorithms.hpp" #include "NumCpp/Core/Shape.hpp" #include "NumCpp/NdArray.hpp" #include "NumCpp/Random/generator.hpp" #include "boost/random/cauchy_distribution.hpp" #include <string> namespace nc { namespace random { //============================================================================ // Method Description: /// Single random value sampled from the from the "cauchy" distrubution. /// /// @param inMean: Mean value of the underlying normal distribution. Default is 0. /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. Default is 1. /// @return /// NdArray /// template<typename dtype> dtype cauchy(dtype inMean = 0, dtype inSigma = 1) { STATIC_ASSERT_ARITHMETIC(dtype); if (inSigma <= 0) { THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); } boost::random::cauchy_distribution<dtype> dist(inMean, inSigma); return dist(generator_); } //============================================================================ // Method Description: /// Create an array of the given shape and populate it with /// random samples from a "cauchy" distrubution. /// /// @param inShape /// @param inMean: Mean value of the underlying normal distribution. Default is 0. /// @param inSigma: Standard deviation of the underlying normal distribution. Should be greater than zero. Default is 1. /// @return /// NdArray /// template<typename dtype> NdArray<dtype> cauchy(const Shape& inShape, dtype inMean = 0, dtype inSigma = 1) { STATIC_ASSERT_ARITHMETIC(dtype); if (inSigma <= 0) { THROW_INVALID_ARGUMENT_ERROR("input sigma must be greater than zero."); } NdArray<dtype> returnArray(inShape); boost::random::cauchy_distribution<dtype> dist(inMean, inSigma); stl_algorithms::for_each(returnArray.begin(), returnArray.end(), [&dist](dtype& value) -> void { value = dist(generator_); }); return returnArray; } } // namespace random } // namespace nc
[ "rubensipala@gmail.com" ]
rubensipala@gmail.com
dc96e62ba0c2399356b83a3b866b52fee84b9e35
f0b7ddd4bcdf99f027a75e283b22a0264ffa05ba
/ShooterStarter/.history/Source/ShooterStarter/ShooterCharacter_20200907123110.cpp
5b64ce5e07cd7ca14f740f5ea80715bf1608675d
[]
no_license
Onygox/UnrealProjects
cd1d8c29f228a7f8e0e2b84bf3c0102761fd07ef
e079c9593a5d9b794d17a409ff4f5175fbffaa0a
refs/heads/master
2022-12-12T21:19:24.416300
2020-09-11T16:38:08
2020-09-11T16:38:08
277,343,579
0
0
null
null
null
null
UTF-8
C++
false
false
3,560
cpp
// Copyright Lionel Miele-Herndon 2020 #include "ShooterCharacter.h" #include "A_Gun.h" #include "Components/CapsuleComponent.h" #include "ShooterStarterGameModeBase.h" // Sets default values AShooterCharacter::AShooterCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AShooterCharacter::BeginPlay() { Super::BeginPlay(); CurrentHealth = MaxHealth; Gun = GetWorld()->SpawnActor<AA_Gun>(GunClass); GetMesh()->HideBoneByName(TEXT("weapon_r"), EPhysBodyOp::PBO_None); Gun->AttachToComponent(GetMesh(), FAttachmentTransformRules::KeepRelativeTransform, TEXT("weapon_socket")); Gun->SetOwner(this); } // Called every frame void AShooterCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); } // Called to bind functionality to input void AShooterCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); //binding movement and POV controls PlayerInputComponent->BindAxis(TEXT("MoveForward"), this, &AShooterCharacter::MoveForward); PlayerInputComponent->BindAxis(TEXT("LookUp"), this, &AShooterCharacter::LookUp); // PlayerInputComponent->BindAxis(TEXT("LookUp"), this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis(TEXT("MoveRight"), this, &AShooterCharacter::MoveRight); // PlayerInputComponent->BindAxis(TEXT("LookRight"), this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis(TEXT("LookRight"), this, &AShooterCharacter::LookRight); PlayerInputComponent->BindAction(TEXT("Jump"), EInputEvent::IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction(TEXT("Shoot"), EInputEvent::IE_Pressed, this, &AShooterCharacter::Shoot); //for controller gamepads PlayerInputComponent->BindAxis(TEXT("LookUpRate"), this, &AShooterCharacter::LookUpRate); PlayerInputComponent->BindAxis(TEXT("LookRightRate"), this, &AShooterCharacter::LookRightRate); } float AShooterCharacter::TakeDamage(float DamageAmount, struct FDamageEvent const &DamageEvent, class AController *EventInstigator, AActor* DamageCauser) { float DamageToApply = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser); DamageToApply = FMath::Min(CurrentHealth, DamageToApply); CurrentHealth-=DamageToApply; UE_LOG(LogTemp, Warning, TEXT("Current Health: %f"), CurrentHealth); if (IsDead()) { DetachFromControllerPendingDestroy(); GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision); GameModeGetWorld()->GetAuthGameMode<AShooterStarterGameModeBase>(); } return DamageToApply; } bool AShooterCharacter::IsDead() const { return CurrentHealth <= 0; } void AShooterCharacter::MoveForward(float AxisValue) { AddMovementInput(GetActorForwardVector() * AxisValue); } void AShooterCharacter::LookUp(float AxisValue) { AddControllerPitchInput(AxisValue); } void AShooterCharacter::LookUpRate(float AxisValue) { AddControllerPitchInput(AxisValue * RotationRate * GetWorld()->GetDeltaSeconds()); } void AShooterCharacter::LookRightRate(float AxisValue) { AddControllerYawInput(AxisValue * RotationRate * GetWorld()->GetDeltaSeconds()); } void AShooterCharacter::MoveRight(float AxisValue) { AddMovementInput(GetActorRightVector() * AxisValue); } void AShooterCharacter::LookRight(float AxisValue) { AddControllerYawInput(AxisValue); } void AShooterCharacter::Shoot() { Gun->Pull_Trigger(); }
[ "miell534@newschool.edu" ]
miell534@newschool.edu
d2809c79a027522c3e732c1bd43747e5e1dd5923
3ce426448a7afe494fde6e295ac7a93c92e76c8c
/cam2ros/include/TransportLayerInterface.h
f2ec1411280167292cb9816921c4b1c52e0584b8
[]
no_license
oulton/SpinnakerCam2ROS
026f6e879394ca27b2352103d29277b87261e204
cb04ff08d0d73da70ca0580e8001c10f9b9a935c
refs/heads/main
2023-09-05T00:04:02.380113
2021-10-31T13:25:34
2021-10-31T13:25:34
423,140,954
0
0
null
null
null
null
UTF-8
C++
false
false
10,655
h
//============================================================================= // Copyright (c) 2001-2020 FLIR Systems, Inc. All Rights Reserved. // // This software is the confidential and proprietary information of FLIR // Integrated Imaging Solutions, Inc. ("Confidential Information"). You // shall not disclose such Confidential Information and shall use it only in // accordance with the terms of the license agreement you entered into // with FLIR Integrated Imaging Solutions, Inc. (FLIR). // // FLIR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE // SOFTWARE, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE, OR NON-INFRINGEMENT. FLIR SHALL NOT BE LIABLE FOR ANY DAMAGES // SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING // THIS SOFTWARE OR ITS DERIVATIVES. //============================================================================= /* Auto-generated file. Do not modify. */ #ifndef FLIR_SPINNAKER_TRANSPORTLAYERINTERFACE_H #define FLIR_SPINNAKER_TRANSPORTLAYERINTERFACE_H #include "SpinnakerPlatform.h" #include "SpinGenApi/SpinnakerGenApi.h" #include "TransportLayerDefs.h" #include <string> namespace Spinnaker { /** * @defgroup SpinnakerQuickSpinClasses Spinnaker QuickSpin Classes */ /*@{*/ /** * @defgroup TransportLayerInterface_h TransportLayerInterface Class */ /*@{*/ /** *@brief Part of the QuickSpin API to provide access to camera information without having to first initialize the camera. */ class SPINNAKER_API TransportLayerInterface { public: TransportLayerInterface(GenApi::INodeMap *nodeMapTLDevice); ~TransportLayerInterface(); protected: TransportLayerInterface(); private: TransportLayerInterface(const TransportLayerInterface&); TransportLayerInterface& operator=(const TransportLayerInterface&); TransportLayerInterface& operator=(GenApi::INodeMap &); public: /** * Description: Transport layer Producer wide unique identifier of the selected interface. * Visibility: Expert */ GenApi::IString &InterfaceID; /** * Description: User readable name of the selected interface. * Visibility: Expert */ GenApi::IString &InterfaceDisplayName; /** * Description: Transport layer type of the interface. * Visibility: Expert */ GenApi::IEnumerationT<InterfaceTypeEnum> &InterfaceType; /** * Description: Selector for the different gateway entries for this interface. * Visibility: Expert */ GenApi::IInteger &GevInterfaceGatewaySelector; /** * Description: IP address of the selected gateway entry of this interface. * Visibility: Expert */ GenApi::IInteger &GevInterfaceGateway; /** * Description: 48-bit MAC address of this interface. * Visibility: Expert */ GenApi::IInteger &GevInterfaceMACAddress; /** * Description: Selector for the subnet of this interface. * Visibility: Expert */ GenApi::IInteger &GevInterfaceSubnetSelector; /** * Description: IP address of the selected subnet of this interface. * Visibility: Expert */ GenApi::IInteger &GevInterfaceSubnetIPAddress; /** * Description: Subnet mask of the selected subnet of this interface. * Visibility: Expert */ GenApi::IInteger &GevInterfaceSubnetMask; /** * Description: Transmit link speed of this interface in bits per second. * Visibility: Expert */ GenApi::IInteger &GevInterfaceTransmitLinkSpeed; /** * Description: Receive link speed of this interface in bits per second. * Visibility: Expert */ GenApi::IInteger &GevInterfaceReceiveLinkSpeed; /** * Description: Maximum transmission unit of this interface. * Visibility: Expert */ GenApi::IInteger &GevInterfaceMTU; /** * Description: Reports and controls the interface's power over Ethernet status. * Visibility: Expert */ GenApi::IEnumerationT<POEStatusEnum> &POEStatus; /** * Description: Reports whether FLIR Light Weight Filter Driver is enabled or not. * Visibility: Expert */ GenApi::IEnumerationT<FilterDriverStatusEnum> &FilterDriverStatus; /** * Description: Key to authorize the action for the device. * Visibility: Expert */ GenApi::IInteger &GevActionDeviceKey; /** * Description: Provides the key that the device will use to validate the action on reception of the action protocol message. * Visibility: Expert */ GenApi::IInteger &GevActionGroupKey; /** * Description: Provides the mask that the device will use to validate the action on reception of the action protocol message. * Visibility: Expert */ GenApi::IInteger &GevActionGroupMask; /** * Description: Provides the time in nanoseconds when the action is to be executed. * Visibility: Expert */ GenApi::IInteger &GevActionTime; /** * Description: Issues an Action Command to attached GEV devices on interface. * Visibility: Expert */ GenApi::ICommand &ActionCommand; /** * Description: Unlocks devices for internal use. * Visibility: Expert */ GenApi::IString &DeviceUnlock; /** * Description: Updates the internal device list. * Visibility: Expert */ GenApi::ICommand &DeviceUpdateList; /** * Description: Number of compatible devices detected on current interface. * Visibility: Expert */ GenApi::IInteger &DeviceCount; /** * Description: Selector for the different devices on this interface. This value only changes on execution of "DeviceUpdateList". The selector is 0-based in order to match the index of the C interface. * Visibility: Expert */ GenApi::IInteger &DeviceSelector; /** * Description: Interface wide unique identifier of the selected device. This value only changes on execution of "DeviceUpdateList". * Visibility: Expert */ GenApi::IString &DeviceID; /** * Description: Name of the device vendor. This value only changes on execution of "DeviceUpdateList". * Visibility: Expert */ GenApi::IString &DeviceVendorName; /** * Description: Name of the device model. This value only changes on execution of "DeviceUpdateList". * Visibility: Expert */ GenApi::IString &DeviceModelName; /** * Description: Serial number of the selected remote device. * Visibility: Expert */ GenApi::IString &DeviceSerialNumber; /** * Description: Gives the device's access status at the moment of the last execution of "DeviceUpdateList". This value only changes on execution of "DeviceUpdateList". * Visibility: Expert */ GenApi::IEnumerationT<DeviceAccessStatusEnum> &DeviceAccessStatus; /** * Description: Current IP address of the GVCP interface of the selected remote device. * Visibility: Expert */ GenApi::IInteger &GevDeviceIPAddress; /** * Description: Current subnet mask of the GVCP interface of the selected remote device. * Visibility: Expert */ GenApi::IInteger &GevDeviceSubnetMask; /** * Description: Current gateway IP address of the GVCP interface of the selected remote device. * Visibility: Expert */ GenApi::IInteger &GevDeviceGateway; /** * Description: 48-bit MAC address of the GVCP interface of the selected remote device. * Visibility: Expert */ GenApi::IInteger &GevDeviceMACAddress; /** * Description: Number of incompatible devices detected on current interface. * Visibility: Expert */ GenApi::IInteger &IncompatibleDeviceCount; /** * Description: Selector for the devices that are not compatible with Spinnaker on this interface. This value only changes on execution of "DeviceUpdateList". The selector is 0-based in order to match the index of the C interface. * Visibility: Expert */ GenApi::IInteger &IncompatibleDeviceSelector; /** * Description: Interface wide unique identifier of the selected incompatible device. This value only changes on execution of "DeviceUpdateList". * Visibility: Expert */ GenApi::IString &IncompatibleDeviceID; /** * Description: Name of the incompatible device vendor. This value only changes on execution of "DeviceUpdateList". * Visibility: Expert */ GenApi::IString &IncompatibleDeviceVendorName; /** * Description: Name of the incompatible device model. This value only changes on execution of "DeviceUpdateList". * Visibility: Expert */ GenApi::IString &IncompatibleDeviceModelName; /** * Description: Current IP address of the GVCP interface of the selected remote incompatible device. * Visibility: Expert */ GenApi::IInteger &IncompatibleGevDeviceIPAddress; /** * Description: Current subnet mask of the GVCP interface of the selected remote incompatible device. * Visibility: Expert */ GenApi::IInteger &IncompatibleGevDeviceSubnetMask; /** * Description: 48-bit MAC address of the GVCP interface of the selected remote incompatible device. * Visibility: Expert */ GenApi::IInteger &IncompatibleGevDeviceMACAddress; /** * Description: Apply the force IP settings (GevDeviceForceIPAddress, GevDeviceForceSubnetMask and GevDeviceForceGateway) in the selected remote device using ForceIP command. * Visibility: Expert */ GenApi::ICommand &GevDeviceForceIP; /** * Description: Static IP address to set for the GVCP interface of the selected remote device. * Visibility: Expert */ GenApi::IInteger &GevDeviceForceIPAddress; /** * Description: Static subnet mask to set for GVCP interface of the selected remote device. * Visibility: Expert */ GenApi::IInteger &GevDeviceForceSubnetMask; /** * Description: Static gateway IP address to set for the GVCP interface of the selected remote device. * Visibility: Expert */ GenApi::IInteger &GevDeviceForceGateway; /** * Description: Automatically forces the selected remote device to an IP Address on the same subnet as the GVCP interface. * Visibility: Expert */ GenApi::ICommand &GevDeviceAutoForceIP; /** * Description: User readable name of the interface's host adapter. * Visibility: Expert */ GenApi::IString &HostAdapterName; /** * Description: User readable name of the host adapter's vendor. * Visibility: Expert */ GenApi::IString &HostAdapterVendor; /** * Description: Driver version of the interface's host adapter. * Visibility: Expert */ GenApi::IString &HostAdapterDriverVersion; protected: friend class Interface; friend class IInterface; friend class InterfaceInternal; }; /*@}*/ /*@}*/ } #endif // FLIR_SPINNAKER_TRANSPORTLAYERINTERFACE_H
[ "haipengzhu666@126.com" ]
haipengzhu666@126.com
a46705ba14944e79c529da9ce9eb8209582edbca
9df5bfab32d03e22480d4000ad1901334279499f
/C++/find_min_in_rotated_sorted_array_ii.cpp
b2bec1520fcf49081d0eee229c6e862e4aebc7e0
[]
no_license
yanbai1990/lintcode
240a0b1db6aeb8f5ab8117777ee656eaf4f3274f
65f31767962e8a524271e20fcacc6c1eae3ecad4
refs/heads/master
2020-12-24T12:02:13.111177
2016-10-29T15:30:37
2016-10-29T15:30:37
38,703,667
1
0
null
null
null
null
UTF-8
C++
false
false
728
cpp
class Solution { public: /** * @param num: the rotated sorted array * @return: the minimum number in the array */ int findMin(vector<int> &num) { // write your code here int start=0; int end=num.size()-1; int ans=INT_MAX; while(start+1<end) { int mid=start+(end-start)/2; if(ans>num[mid]) { ans=num[mid]; } else if(num[mid]<num[end]) { end=mid; } else if(num[mid]>num[end]){ start=mid; } else { end=end-1; } } if(num[start]<ans) ans=num[start]; if(num[end]<ans) ans=num[end]; return ans; } };
[ "byan1990@gmail.com" ]
byan1990@gmail.com
90a7e30df08197a4a70e99feb3894d2f45e154b2
a077eb51ff18df52d741d6c9ba9a5003673415df
/cpp/graphFunctions/graphFunctions.h
e09e2472353a027c2d9565d6bc0a52270402ac59
[ "MIT" ]
permissive
michieluithetbroek/A-MDVRP
d4a5f2f4e742c70c9cebd7dccde9837b1f718a2f
f378333e21b874e1cfad1333df5d47dec8c7b13e
refs/heads/master
2022-04-30T19:55:40.080660
2022-03-29T15:19:58
2022-03-29T15:19:58
241,376,430
43
13
null
null
null
null
UTF-8
C++
false
false
2,498
h
#pragma once #include <vector> #include <map> #include <utility> #include <lemon/list_graph.h> #include <lemon/euler.h> #include <lemon/concepts/graph_components.h> #include <lemon/adaptors.h> #include <lemon/hao_orlin.h> #include <lemon/preflow.h> #include <lemon/dijkstra.h> #include <lemon/edmonds_karp.h> using namespace std; /* * This namespace provides some functions that are typically used to find cuts * * It requires the EMON library * */ namespace graphFunctions { // An unnamed namespace is only accessible from within the current namespace // You can compare it with private datamembers of a class // // The attributes are used! But in external files. // We indicate that they are unused to avoid several hundreds of warnings.. // namespace // { double const d_eps = 0.001; extern int d_nDepots; extern int d_nCustomers; extern int d_nNodes; // extern int d_vehicleCap; extern std::vector<size_t> d_iDepots; extern std::vector<size_t> d_iCustomers; extern std::vector<size_t> d_iNodes; // } void setValues( int nDepots, int nCustomers, int nNodes, std::vector<size_t> const &iDepots, std::vector<size_t> const &iCustomers, std::vector<size_t> const &iNodes ); void create_listDigraph (lemon::ListDigraph &g, std::vector<std::vector<double>> const &x); /* * The following functions return a vector containing * weakly connected components. You can call the functions * with a ListGraph, a ListDiGraph, or a with given LP relaxation */ std::vector<std::vector<int>> LEMON_get_connected_components (lemon::ListGraph const &g); std::vector<std::vector<int>> LEMON_get_connected_components (lemon::ListDigraph const &g); std::vector<std::vector<int>> LEMON_get_connected_components (std::vector<std::vector<double>> const &x); void get_connected_components_including_depot (std::vector<std::vector<double>> const &x, int *ncomp, int **compscount, int **comps); /* * Transform graphs * */ void transform_to_lysgard_graph_single_depot(std::vector<std::vector<double>> const &x, std::vector<int> &edgeTail, std::vector<int> &edgeHead, std::vector<double> &edgeX); }
[ "a.h.schrotenboer@gmail.com" ]
a.h.schrotenboer@gmail.com
6c2843a2fbafecd769d301b40ce10c1e5f403a7f
0cfa46c1dccd3ad53b16d32c6a00a155c5bc0be5
/cpp/libs/opendnp3/src/opendnp3/master/MasterStackConfig.h
48131e9e1ceb3171ba9903a92ba919dceef1eaba
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference" ]
permissive
atmurray/dnp3
9e5c946c7857523f7d6a8c260b6cdef9fbc60805
0babbe9fc25e8ba952d5443afc75e5448db28a9b
refs/heads/ODC
2021-01-17T14:15:36.244255
2014-11-21T10:38:24
2014-11-24T04:24:08
16,426,140
0
0
null
2015-05-26T23:51:35
2014-02-01T01:52:44
C++
UTF-8
C++
false
false
1,467
h
/** * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #ifndef __MASTER_STACK_CONFIG_H_ #define __MASTER_STACK_CONFIG_H_ #include "opendnp3/master/MasterParams.h" #include "opendnp3/link/LinkConfig.h" namespace opendnp3 { /** A composite configuration struct that contains all the config information for a dnp3 master stack */ struct MasterStackConfig { MasterStackConfig() : link(true, false) {} /// Master config MasterParams master; /// Link layer config LinkConfig link; }; } #endif
[ "jadamcrain@gmail.com" ]
jadamcrain@gmail.com
e52edc51608e6a420c9f58f037d72a3715273dde
01135ea2b2cba847a3e4f0c3b2febe5424763f35
/include/FetchEpisodes.h
a6f4a065dc63000d76fb442d411f411d1f9fc68c
[]
no_license
justmert/Kanzaki
aa9a8b3dc52a769e475317522919283c3ee2cd41
56b47650f2143762edd4c8994f74c71a2ffdeb32
refs/heads/master
2022-02-17T04:21:17.046108
2019-08-14T10:46:15
2019-08-14T10:46:15
201,549,583
1
0
null
null
null
null
UTF-8
C++
false
false
641
h
#include<string> #include<vector> #include<algorithm> class Anime; class FetchEpisodes { private: public: static std::vector<Anime> VectorEpisode; static std::string FetchAnimeEp(int); static void DownloadAnime(std::string,std::string &, std::string &); static void PlayAnime(std::string); static std::string replaceSpaces(std::string ); }; static std::string Trim(std::string str) { str.erase(str.begin(), find_if(str.begin(), str.end(), [](char p) { return !isspace(p); })); str.erase(std::find_if(str.rbegin(), str.rend(), [](int p) { return !std::isspace(p); }).base(), str.end()); return str; }
[ "kklumert@gmail.com" ]
kklumert@gmail.com
8a5f615cceebd36059e207bd99265738352f4e71
79a634d9357a750cbd0efea04d932938e1b7f632
/Contest/Topcoder/Z_Others/250.cpp
e1cea1f694984fcfa5248405d976e0160e93a9b1
[]
no_license
hphp/Algorithm
5f42fe188422427a7762dbbe7af539b89fa796ed
ccbb368a37eed1b0cb37356026b299380f9c008b
refs/heads/master
2016-09-06T02:24:43.141927
2014-05-27T00:49:44
2014-05-27T00:49:44
14,009,913
1
0
null
null
null
null
UTF-8
C++
false
false
849
cpp
#include <vector> #include <string> using namespace std; #define N 61 int dmx[N][N],rmx[N][N]; class AmoebaDivTwo { public: int count(vector <string> table, int K) { int n = table.size(); int m = table[0].length(); for(int i=n-1;i>=0;i--) { for(int j = m-1;j>=0;j--) { if(table[i][j] == 'M') dmx[i][j] = rmx[i][j] = 0; else { if(j == m-1) rmx[i][j] = 1; else rmx[i][j] = rmx[i][j+1]+1; if(i == n-1) dmx[i][j] = 1; else dmx[i][j] = dmx[i+1][j]+1; } } } int cnt = 0; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(dmx[i][j] >= K) cnt++; if(K > 1) if(rmx[i][j] >= K) cnt++; } } return cnt; } }; /* 2011-01-24 14:50 15:03 - 15:10 AC 174.xx */
[ "hphpcarrot@gmail.com" ]
hphpcarrot@gmail.com
d8de2c0b726c8e620b526bbaac0ade97c8ced5e8
e043290612c380ca10290badb2574da006b9dea9
/services/ui/ws/window_server_test_base.cc
bee909e989bd4522396c49f7036700ec598eadc9
[ "BSD-3-Clause" ]
permissive
jeffsseely/chromium
28667a243607baf02c74ccf4cc94a1b36ed2a42b
5c0ead04050ee0787ef0d9af45efc3c740571465
refs/heads/master
2023-03-17T04:31:14.131666
2017-01-24T18:15:39
2017-01-24T18:15:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,278
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/ui/ws/window_server_test_base.h" #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/single_thread_task_runner.h" #include "base/test/test_timeouts.h" #include "base/threading/thread_task_runner_handle.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/interface_registry.h" #include "ui/aura/env.h" #include "ui/aura/mus/window_tree_client.h" #include "ui/aura/mus/window_tree_host_mus.h" #include "ui/display/display.h" #include "ui/display/display_list.h" #include "ui/wm/core/capture_controller.h" namespace ui { namespace { base::RunLoop* current_run_loop = nullptr; void TimeoutRunLoop(const base::Closure& timeout_task, bool* timeout) { CHECK(current_run_loop); *timeout = true; timeout_task.Run(); } } // namespace WindowServerTestBase::WindowServerTestBase() {} WindowServerTestBase::~WindowServerTestBase() {} // static bool WindowServerTestBase::DoRunLoopWithTimeout() { if (current_run_loop != nullptr) return false; bool timeout = false; base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::Bind(&TimeoutRunLoop, run_loop.QuitClosure(), &timeout), TestTimeouts::action_timeout()); current_run_loop = &run_loop; current_run_loop->Run(); current_run_loop = nullptr; return !timeout; } // static bool WindowServerTestBase::QuitRunLoop() { if (!current_run_loop) return false; current_run_loop->Quit(); current_run_loop = nullptr; return true; } void WindowServerTestBase::DeleteWindowTreeClient( aura::WindowTreeClient* client) { for (auto iter = window_tree_clients_.begin(); iter != window_tree_clients_.end(); ++iter) { if (iter->get() == client) { window_tree_clients_.erase(iter); return; } } NOTREACHED(); } std::unique_ptr<aura::WindowTreeClient> WindowServerTestBase::ReleaseMostRecentClient() { if (window_tree_clients_.empty()) return nullptr; std::unique_ptr<aura::WindowTreeClient> result = std::move(window_tree_clients_.back()); window_tree_clients_.pop_back(); return result; } void WindowServerTestBase::SetUp() { WindowServerServiceTestBase::SetUp(); env_ = aura::Env::CreateInstance(aura::Env::Mode::MUS); display::Screen::SetScreenInstance(&screen_); std::unique_ptr<aura::WindowTreeClient> window_manager_window_tree_client = base::MakeUnique<aura::WindowTreeClient>(connector(), this, this); window_manager_window_tree_client->ConnectAsWindowManager(); window_manager_ = window_manager_window_tree_client.get(); window_tree_clients_.push_back(std::move(window_manager_window_tree_client)); // Connecting as the WindowManager results in OnWmNewDisplay() being called // with the display (and root). Wait for it to be called so we have display // and root window information (otherwise we can't really do anything). ASSERT_TRUE(DoRunLoopWithTimeout()); } void WindowServerTestBase::TearDown() { // WindowTreeHost depends on WindowTreeClient. window_tree_hosts_.clear(); window_tree_clients_.clear(); env_.reset(); display::Screen::SetScreenInstance(nullptr); WindowServerServiceTestBase::TearDown(); } bool WindowServerTestBase::OnConnect( const service_manager::Identity& remote_identity, service_manager::InterfaceRegistry* registry) { registry->AddInterface<mojom::WindowTreeClient>(this); return true; } void WindowServerTestBase::OnEmbed( std::unique_ptr<aura::WindowTreeHostMus> window_tree_host) { EXPECT_TRUE(QuitRunLoop()); window_tree_hosts_.push_back(std::move(window_tree_host)); } void WindowServerTestBase::OnLostConnection(aura::WindowTreeClient* client) { window_tree_client_lost_connection_ = true; DeleteWindowTreeClient(client); } void WindowServerTestBase::OnEmbedRootDestroyed( aura::WindowTreeHostMus* window_tree_host) { if (!DeleteWindowTreeHost(window_tree_host)) { // Assume a subclass called Embed() and wants us to destroy it. delete window_tree_host; } } void WindowServerTestBase::OnPointerEventObserved(const ui::PointerEvent& event, aura::Window* target) {} aura::client::CaptureClient* WindowServerTestBase::GetCaptureClient() { return wm_state_.capture_controller(); } aura::PropertyConverter* WindowServerTestBase::GetPropertyConverter() { return &property_converter_; } void WindowServerTestBase::SetWindowManagerClient( aura::WindowManagerClient* client) { window_manager_client_ = client; } bool WindowServerTestBase::OnWmSetBounds(aura::Window* window, gfx::Rect* bounds) { return window_manager_delegate_ ? window_manager_delegate_->OnWmSetBounds(window, bounds) : true; } bool WindowServerTestBase::OnWmSetProperty( aura::Window* window, const std::string& name, std::unique_ptr<std::vector<uint8_t>>* new_data) { return window_manager_delegate_ ? window_manager_delegate_->OnWmSetProperty(window, name, new_data) : true; } aura::Window* WindowServerTestBase::OnWmCreateTopLevelWindow( ui::mojom::WindowType window_type, std::map<std::string, std::vector<uint8_t>>* properties) { return window_manager_delegate_ ? window_manager_delegate_->OnWmCreateTopLevelWindow(window_type, properties) : nullptr; } void WindowServerTestBase::OnWmClientJankinessChanged( const std::set<aura::Window*>& client_windows, bool janky) { if (window_manager_delegate_) window_manager_delegate_->OnWmClientJankinessChanged(client_windows, janky); } void WindowServerTestBase::OnWmWillCreateDisplay( const display::Display& display) { screen_.display_list().AddDisplay(display, display::DisplayList::Type::PRIMARY); if (window_manager_delegate_) window_manager_delegate_->OnWmWillCreateDisplay(display); } void WindowServerTestBase::OnWmNewDisplay( std::unique_ptr<aura::WindowTreeHostMus> window_tree_host, const display::Display& display) { EXPECT_TRUE(QuitRunLoop()); ASSERT_TRUE(window_manager_client_); window_manager_client_->AddActivationParent(window_tree_host->window()); window_tree_hosts_.push_back(std::move(window_tree_host)); if (window_manager_delegate_) window_manager_delegate_->OnWmNewDisplay(nullptr, display); } void WindowServerTestBase::OnWmDisplayRemoved( aura::WindowTreeHostMus* window_tree_host) { if (window_manager_delegate_) window_manager_delegate_->OnWmDisplayRemoved(window_tree_host); ASSERT_TRUE(DeleteWindowTreeHost(window_tree_host)); } void WindowServerTestBase::OnWmDisplayModified( const display::Display& display) { if (window_manager_delegate_) window_manager_delegate_->OnWmDisplayModified(display); } ui::mojom::EventResult WindowServerTestBase::OnAccelerator( uint32_t accelerator_id, const ui::Event& event) { return window_manager_delegate_ ? window_manager_delegate_->OnAccelerator(accelerator_id, event) : ui::mojom::EventResult::UNHANDLED; } void WindowServerTestBase::OnWmPerformMoveLoop( aura::Window* window, ui::mojom::MoveLoopSource source, const gfx::Point& cursor_location, const base::Callback<void(bool)>& on_done) { if (window_manager_delegate_) { window_manager_delegate_->OnWmPerformMoveLoop(window, source, cursor_location, on_done); } } void WindowServerTestBase::OnWmCancelMoveLoop(aura::Window* window) { if (window_manager_delegate_) window_manager_delegate_->OnWmCancelMoveLoop(window); } void WindowServerTestBase::OnWmSetClientArea( aura::Window* window, const gfx::Insets& insets, const std::vector<gfx::Rect>& additional_client_areas) { if (window_manager_delegate_) { window_manager_delegate_->OnWmSetClientArea(window, insets, additional_client_areas); } } bool WindowServerTestBase::IsWindowActive(aura::Window* window) { if (window_manager_delegate_) window_manager_delegate_->IsWindowActive(window); return false; } void WindowServerTestBase::OnWmDeactivateWindow(aura::Window* window) { if (window_manager_delegate_) window_manager_delegate_->OnWmDeactivateWindow(window); } void WindowServerTestBase::Create( const service_manager::Identity& remote_identity, mojom::WindowTreeClientRequest request) { window_tree_clients_.push_back(base::MakeUnique<aura::WindowTreeClient>( connector(), this, nullptr, std::move(request))); } bool WindowServerTestBase::DeleteWindowTreeHost( aura::WindowTreeHostMus* window_tree_host) { for (auto iter = window_tree_hosts_.begin(); iter != window_tree_hosts_.end(); ++iter) { if ((*iter).get() == window_tree_host) { window_tree_hosts_.erase(iter); return true; } } return false; } } // namespace ui
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f45868f08964bbe2b630ec9590525729330e12d8
7b6469d1508f0a67bfe4ca6350357c2c8ffa875a
/Practical 0 - Abstract Factory/Proxy Implementation/GraphicProxy.cpp
9cd7cb19244e069aef9d02f175cdfab6994fffec
[]
no_license
KDaryl/Games-Engineering
785784efe18bfeaee0e9c77fa87a9e45e8b87dc3
24b6bac0e7727ee235678702a791ade956b8271a
refs/heads/master
2020-03-29T02:33:10.114707
2019-03-27T19:08:16
2019-03-27T19:08:16
149,442,486
0
0
null
null
null
null
UTF-8
C++
false
false
312
cpp
#include "GraphicProxy.h" GraphicProxy::GraphicProxy() { this->graphic = nullptr; } GraphicProxy::~GraphicProxy() { if (graphic) delete graphic; } Graphic* GraphicProxy::getInstance(void) { if (!graphic) graphic = new Graphic(); return graphic; } void GraphicProxy::draw() { getInstance()->draw(); }
[ "c00207452@itcarlow.ie" ]
c00207452@itcarlow.ie
6a4c0e75bb10ec54a35b1a850ee4a3a66e7e4153
ebe0cffadf5d04495905bbc75fbfd8acee832f6b
/Cameras/HomefrontTheRevolution/InjectableGenericCameraSystem/CameraManipulator.h
3dcf5679cc8f3c370c7a2f1b1bd48e603aa50d77
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
FransBouma/InjectableGenericCameraSystem
f123f31c676879561fc3a3e2d03579adf2c1f7cf
bdd9e237cef6caba38b946b18c36713f69ab09b9
refs/heads/master
2023-08-24T19:17:59.563669
2023-04-27T18:59:08
2023-04-27T18:59:08
75,194,811
718
278
BSD-2-Clause
2020-09-23T19:12:50
2016-11-30T14:30:36
C++
UTF-8
C++
false
false
2,202
h
//////////////////////////////////////////////////////////////////////////////////////////////////////// // Part of Injectable Generic Camera System // Copyright(c) 2017, Frans Bouma // All rights reserved. // https://github.com/FransBouma/InjectableGenericCameraSystem // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "stdafx.h" using namespace DirectX; namespace IGCS::GameSpecific::CameraManipulator { void writeNewCameraValuesToGameData(XMFLOAT3 newCoords, XMVECTOR newLookQuaternion); void restoreOriginalCameraValues(); void cacheOriginalCameraValues(); void setTimeStopValue(byte newValue); void setSupersamplingFactor(LPBYTE hostImageAddress, float newValue); XMFLOAT3 getCurrentCameraCoords(); void resetFoV(); void changeFoV(float amount); bool isCameraFound(); void displayCameraStructAddress(); }
[ "frans@sd.nl" ]
frans@sd.nl
44178a6fee9bdb535d9e63f90a306f6546a8e1a5
3cb02d8bfd827beaff8f5d284bfeee2099c173e6
/2019年北京师范大学校赛/预赛/f.cpp
94704dc96969e9b443198522ee8c7ee853e647ec
[]
no_license
yyhaos/Competitions
8a88ddfa0606e884c88f17ef391ffdd1ba32bf0f
d291be1327e895883b423eeebad943893f27e66e
refs/heads/master
2021-06-12T13:14:22.354538
2020-08-18T05:24:24
2020-08-18T05:24:24
128,635,106
3
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
//Problem Web:http://39.97.97.11/problem.php?cid=1003&pid=5 #include<bits/stdc++.h> #include<ext/rope> #include<iostream> #include<stack> #include<vector> #include<queue> #include<stdio.h> #include<string.h> using namespace std; #define ll long long #define lowbit(x) (x&-x) #define rep(i,x,y) for(ll i=x;i<=y;i++) #define crep(i,x,y) for(ll i=x;i>=y;i--) #define gcd(x,y) __gcd(x,y) #define mem(x,y) memset(x,y,sizeof(x)) #define pr pair #define mp make_pair #define use_t 1 const double PI=acos(-1.0); const double eps=1e-8; const ll INF = 100000000; const ll maxn=1000; const ll q=1e9+7; ll ksm(ll a,ll b) { ll ans=1LL; while(b>0) { if(b&1LL) ans=ans*a%q; a=a*a%q; b/=2LL; } return ans; } ll used[100005]; ll t,n,m; map <string, int> na; int main () { #ifdef yyhao freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); #endif #ifdef use_t ll ii=1; cin>>t; for(ii=1;ii<=t;ii++) { #endif // use_t mem(used,0); na.clear(); ll th=1; ll ans=0; queue<int > qu; cin>>n; string ty,name; while(n--) { cin>>ty>>name; if(na[name]==0) { na[name]=th++; } if(ty[0]=='i') qu.push(na[name]); else { if(!qu.empty() && qu.front() == na[name]) { ans++; qu.pop(); while(!qu.empty() && used[qu.front()] == 1) qu.pop(); } used[na[name]]=1; } } cout<<ans<<endl; #ifdef use_t } #endif // use_t return 0; }
[ "35396510+yyhaos@users.noreply.github.com" ]
35396510+yyhaos@users.noreply.github.com
cd7faa25d27f0d9e3525b079a98e0cf81d6d5b69
d6750ce224994800a69a0b13f72364854c639cbc
/src/test/amount_tests.cpp
ce14b027bbeb6ec5214e8dae13dbaa194f2a7454
[ "MIT" ]
permissive
BrightonDube/Looniecoin
79719a76f2feb842b3ddfb602ce849a156fed46b
07549342c75e9482fe8977bfabafd2affe76551a
refs/heads/master
2020-03-31T02:24:31.050368
2018-10-13T18:39:42
2018-10-13T18:39:42
151,821,976
0
0
null
null
null
null
UTF-8
C++
false
false
3,672
cpp
// Copyright (c) 2016-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <amount.h> #include <policy/feerate.h> #include <test/test_bitcoin.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(amount_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(MoneyRangeTest) { BOOST_CHECK_EQUAL(MoneyRange(CAmount(-1)), false); BOOST_CHECK_EQUAL(MoneyRange(MAX_MONEY + CAmount(1)), false); BOOST_CHECK_EQUAL(MoneyRange(CAmount(1)), true); } BOOST_AUTO_TEST_CASE(GetFeeTest) { CFeeRate feeRate, altFeeRate; feeRate = CFeeRate(0); // Must always return 0 BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0); BOOST_CHECK_EQUAL(feeRate.GetFee(1e5), 0); feeRate = CFeeRate(1000); // Must always just return the arg BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0); BOOST_CHECK_EQUAL(feeRate.GetFee(1), 1); BOOST_CHECK_EQUAL(feeRate.GetFee(121), 121); BOOST_CHECK_EQUAL(feeRate.GetFee(999), 999); BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), 1e3); BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), 9e3); feeRate = CFeeRate(-1000); // Must always just return -1 * arg BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0); BOOST_CHECK_EQUAL(feeRate.GetFee(1), -1); BOOST_CHECK_EQUAL(feeRate.GetFee(121), -121); BOOST_CHECK_EQUAL(feeRate.GetFee(999), -999); BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), -1e3); BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), -9e3); feeRate = CFeeRate(123); // Truncates the result, if not integer BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0); BOOST_CHECK_EQUAL(feeRate.GetFee(8), 1); // Special case: returns 1 instead of 0 BOOST_CHECK_EQUAL(feeRate.GetFee(9), 1); BOOST_CHECK_EQUAL(feeRate.GetFee(121), 14); BOOST_CHECK_EQUAL(feeRate.GetFee(122), 15); BOOST_CHECK_EQUAL(feeRate.GetFee(999), 122); BOOST_CHECK_EQUAL(feeRate.GetFee(1e3), 123); BOOST_CHECK_EQUAL(feeRate.GetFee(9e3), 1107); feeRate = CFeeRate(-123); // Truncates the result, if not integer BOOST_CHECK_EQUAL(feeRate.GetFee(0), 0); BOOST_CHECK_EQUAL(feeRate.GetFee(8), -1); // Special case: returns -1 instead of 0 BOOST_CHECK_EQUAL(feeRate.GetFee(9), -1); // check alternate constructor feeRate = CFeeRate(1000); altFeeRate = CFeeRate(feeRate); BOOST_CHECK_EQUAL(feeRate.GetFee(100), altFeeRate.GetFee(100)); // Check full constructor // default value BOOST_CHECK(CFeeRate(CAmount(-1), 1000) == CFeeRate(-1)); BOOST_CHECK(CFeeRate(CAmount(0), 1000) == CFeeRate(0)); BOOST_CHECK(CFeeRate(CAmount(1), 1000) == CFeeRate(1)); // lost precision (can only resolve satoshis per kB) BOOST_CHECK(CFeeRate(CAmount(1), 1001) == CFeeRate(0)); BOOST_CHECK(CFeeRate(CAmount(2), 1001) == CFeeRate(1)); // some more integer checks BOOST_CHECK(CFeeRate(CAmount(26), 789) == CFeeRate(32)); BOOST_CHECK(CFeeRate(CAmount(27), 789) == CFeeRate(34)); // Maximum size in bytes, should not crash CFeeRate(MAX_MONEY, std::numeric_limits<size_t>::max() >> 1).GetFeePerK(); } BOOST_AUTO_TEST_CASE(BinaryOperatorTest) { CFeeRate a, b; a = CFeeRate(1); b = CFeeRate(2); BOOST_CHECK(a < b); BOOST_CHECK(b > a); BOOST_CHECK(a == a); BOOST_CHECK(a <= b); BOOST_CHECK(a <= a); BOOST_CHECK(b >= a); BOOST_CHECK(b >= b); // a should be 0.00000002 BTC/kB now a += a; BOOST_CHECK(a == b); } BOOST_AUTO_TEST_CASE(ToStringTest) { CFeeRate feeRate; feeRate = CFeeRate(1); BOOST_CHECK_EQUAL(feeRate.ToString(), "0.00000001 LNI/kB"); } BOOST_AUTO_TEST_SUITE_END()
[ "BrightonDube@users.noreply.github.com" ]
BrightonDube@users.noreply.github.com
fba0d412ca1e6fd44ff29a3503e8ba8f66567a21
afda9a6e85ac236d5dbf80fa388360efe0038341
/src/common/sysinfo.cc
ad05f06694549a6c53d9e97a6cb5d79ebb2ec180
[]
no_license
sybila/NewBioDiVinE
73d2a19812df28dc217213f60f87050efcb69cb2
e046a64b2345b739bcfa64317986f78be9ad0ca3
refs/heads/master
2020-04-25T17:38:59.935101
2014-12-10T01:44:17
2014-12-10T01:44:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,446
cc
#include "common/sysinfo.hh" // {{{ vminfo vminfo_t::vminfo_t(){ pid = getpid(); snprintf (filename,sizeof filename, "/proc/%d/status", pid); vmsize=vmlck=vmrss=vmdata=vmstk=vmexe=vmlib=0; statm=false; char line[1000]; // now detect the number of lines to be skipped FILE *statusfile; lineskip = 0; if ((statusfile = fopen (filename,"r")) != NULL) { vmsize=0; while (vmsize==0) { fscanf (statusfile,"VmSize:%d kB\nVmLck:%d kB\nVmRSS:%d kB\nVmData:%d kB\n\ VmStk:%d kB\nVmExe:%d kB\nVmLib:%d kB\n" ,&vmsize,&vmlck,&vmrss,&vmdata,&vmstk,&vmexe,&vmlib); fgets(line, sizeof line, statusfile); lineskip++; } lineskip--; fclose(statusfile); } } vminfo_t::~vminfo_t() { } void vminfo_t::print() { scan(); using namespace std; cout <<"VM: "; cout <<"size="<<vmsize<<" "; cout <<"rss="<<vmrss<<" "; if (!statm) { cout <<"lck="<<vmlck<<" "; cout <<"data="<<vmdata<<" "; cout <<"stk="<<vmstk<<" "; cout <<"exe="<<vmexe<<" "; cout <<"lib="<<vmlib<<" "; } cout <<endl; } void vminfo_t::scan() { #if defined(__linux__) char line[1000]; FILE *statusfile; if ((statusfile = fopen (filename,"r")) == NULL) { return; } for (int i=0; i<lineskip; i++) { fgets (line, sizeof line, statusfile); } fscanf (statusfile,"VmSize:%d kB\nVmLck:%d kB\nVmRSS:%d kB\nVmData:%d kB\n\ VmStk:%d kB\nVmExe:%d kB\nVmLib:%d kB\n" ,&vmsize,&vmlck,&vmrss,&vmdata,&vmstk,&vmexe,&vmlib); fclose(statusfile); #elif defined(__APPLE__) task_t task = MACH_PORT_NULL; if (task_for_pid (current_task(), pid, &task) != KERN_SUCCESS) { perror ("task_for_pid"); return; } struct task_basic_info task_basic_info; mach_msg_type_number_t task_basic_info_count = TASK_BASIC_INFO_COUNT; task_info(task, TASK_BASIC_INFO, (task_info_t)&task_basic_info, &task_basic_info_count); vmrss = task_basic_info.resident_size / 1024UL; unsigned long int vmsize_bytes = task_basic_info.virtual_size; if (vmsize_bytes > SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE) vmsize_bytes -= SHARED_TEXT_REGION_SIZE + SHARED_DATA_REGION_SIZE; vmsize = vmsize_bytes / 1024UL; #else // getrusage() stats are neither properly supported on Linux nor OSX // (2007-07-13) struct rusage rusage; if (getrusage (RUSAGE_SELF, &rusage) == -1) { perror ("getrusage"); return; } vmrss = rusage.ru_maxrss; // vmsize = ? vmdata = rusage.ru_idrss; //? vmstk = rusage.ru_isrss; //? vmexe = rusage.ru_ixrss; //? #endif } int vminfo_t::getvmsize() { scan(); return vmsize; } int vminfo_t::getvmdata() { scan(); return vmdata; } int vminfo_t::getvmrss() { scan(); return vmrss; } // }}} // {{{ timeinfo timeinfo_t::timeinfo_t() { settimeout(0,0); reset(); } timeinfo_t::timeinfo_t(double time) { settimeout(time); reset(); } timeinfo_t::timeinfo_t(long sec, long msec) { settimeout(sec,msec); reset(); } void timeinfo_t::settimeout(long sec,long msec) { tv_usec = 1000*msec; tv_sec = sec + (tv_usec/1000000); tv_usec %= 1000000; } void timeinfo_t::settimeout(double time) { tv_usec = static_cast<long>(1000000*time)%1000000; tv_sec = static_cast<long>(time); } void timeinfo_t::reset() { gettimeofday(&stored,0); stored.tv_usec += tv_usec; stored.tv_sec += tv_sec + (stored.tv_usec/1000000); stored.tv_usec %= 1000000; } bool timeinfo_t::testtimeout() { timeval current; gettimeofday(&current,0); if (stored.tv_sec < current.tv_sec || (stored.tv_sec == current.tv_sec && stored.tv_usec <= current.tv_usec)) { return true; } return false; } #if !defined(ORIG_TIMEOUT) bool timeinfo_t::testtimeout(timeval& current) { // same as above, but caller supplies current time to compare if (stored.tv_sec < current.tv_sec || (stored.tv_sec == current.tv_sec && stored.tv_usec <= current.tv_usec)) { return true; } return false; } #endif /* !ORIG_TIMEOUT */ void timeinfo_t::print_time(long sec,long microsec) { using namespace std; cout <<sec+microsec/1000000<<"."; if (microsec<10) cout <<"0"; if (microsec<100) cout <<"0"; if (microsec<1000) cout <<"0"; if (microsec<10000) cout <<"0"; if (microsec<100000) cout <<"0"; cout<<microsec; } void timeinfo_t::print() { timeval current; gettimeofday(&current,0); long micro = 1000000 + current.tv_usec - (stored.tv_usec - tv_usec); long sec = current.tv_sec - 1 - (stored.tv_sec - tv_sec) ; sec += micro/1000000; micro %= 1000000; print_time(sec,micro); } double timeinfo_t::gettime() { timeval current; gettimeofday(&current,0); long micro = 1000000 + current.tv_usec - (stored.tv_usec - tv_usec); long sec = current.tv_sec - 1 - (stored.tv_sec - tv_sec) ; sec += micro/1000000; micro %= 1000000; return (sec+(micro/1000000.0)); } // }}} // {{{ timeprofiler timeprofiler_t::timeprofiler_t(int n) { timevalues.resize(n); for (int i=0; i<n; i++) { timevalues[i].tv_sec=0; timevalues[i].tv_usec=0; } focus=0; gettimeofday(&lasttick,0); firsttick = lasttick; }; void timeprofiler_t::profile_off() { profile_on(0); } void timeprofiler_t::profile_on(int n) { timeval tick; gettimeofday(&tick,0); timevalues[focus].tv_sec += tick.tv_sec - lasttick.tv_sec; timevalues[focus].tv_usec += tick.tv_usec - lasttick.tv_usec; if (timevalues[focus].tv_usec>1000000) { timevalues[focus].tv_sec += timevalues[focus].tv_usec/1000000; timevalues[focus].tv_usec %= 1000000; } lasttick.tv_sec = tick.tv_sec; lasttick.tv_usec = tick.tv_usec; focus=n; } long timeprofiler_t::get_time_on(int n) { timevalues[n].tv_sec += timevalues[n].tv_usec/1000000; timevalues[n].tv_usec = timevalues[n].tv_usec%1000000; return static_cast<long> (1000*(timevalues[n].tv_sec+timevalues[n].tv_usec/1000000.0)); } long timeprofiler_t::get_global_time() { timeval tick; gettimeofday(&tick,0); long micro = 1000000 + tick.tv_usec - firsttick.tv_usec; long sec = tick.tv_sec - 1 - firsttick.tv_sec; sec += micro/1000000; micro %= 1000000; return static_cast<long>(1000*(sec+micro/1000000.0)); } // }}} // {{{ loadinfo int loadinfo_t::getload() { double result; getloadavg(&result,1); return static_cast<int>(100*result); } // }}}
[ "325073@mail.muni.cz" ]
325073@mail.muni.cz
16515e3d4a9db2dd60b0d32557c9490e1bace854
40416cef809fa0a88afef5b5e8f7a04e16abbc20
/Zenitka/Object.cpp
7ef43fe327dea540170fdc08c8348ddb98a782a5
[]
no_license
GetRight23/AntiaircraftGun
111989db7923935ee8f57515206997bea46f7412
a5dbdde925efbce5bcac859e4cd45796615e7d1a
refs/heads/master
2020-04-01T21:29:44.232549
2018-10-18T17:13:42
2018-10-18T17:13:42
153,659,046
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
#include "Object.h" Object::Object() : x(0), y(0), w(0), h(0), startX(0), startY(0) { sprite.setPosition(x, y); } Object::Object(float x, float y, float sx, float sy, float w, float h, sf::Texture& texture) : x(x), y(y), w(w), h(h), startX(sx), startY(sy) { setTexture(texture); sprite.setPosition(x, y); } Object::~Object() { } void Object::setTexture(sf::Texture& texture) { sprite.setTexture(texture); sprite.setTextureRect(sf::IntRect(static_cast<int>(startX), static_cast<int>(startY), static_cast<int>(w), static_cast<int>(h))); sprite.setOrigin(w / 2.0f, h / 2.0f); }
[ "ivasilich23@gmail.com" ]
ivasilich23@gmail.com
f16c6c59f0ef239c683bb4ce01099c6ce1508b2c
03a44baca9e6ed95705432d96ba059f16e62a662
/OtherTrains/2019南昌网预/I.cpp
d1fd0439c7549f2692a89bb651e2ca2bd5b56185
[]
no_license
ytz12345/2019_ICPC_Trainings
5c6e113afb8e910dd91c8340ff43af00a701c7c7
cf0ce781675a7dbc454fd999693239e235fbbe87
refs/heads/master
2020-05-14T08:29:19.671739
2020-04-03T03:21:30
2020-04-03T03:21:30
181,722,314
0
0
null
null
null
null
UTF-8
C++
false
false
1,941
cpp
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, m, k; int a[N], b[N]; struct node { int x, y, v, id; }c[N * 5], c0[N * 5]; int id, ans[N]; inline void clr(int i) { if (i > n || !b[i]) return; b[i] = 0, c[++ k] = (node){i, a[i], -1, 0}; } inline void check(int i) { if (i > n || a[i] == a[i - 1]) return; b[i] = 1, c[++ k] = (node){i, a[i], 1, 0}; } template <int N>struct bit { int c[N]; bit() {memset (c, 0, sizeof c);} int lb(int x) {return x & (-x);} void add(int i, int x) {while (i < N) c[i] += x, i += lb(i);} int ask(int i) {int res = 0; while (i > 0) res += c[i], i -= lb(i); return res;} }; void solve(int l, int r) { static bit <N> t; if (l >= r) return; int sum = 0, mid = l + r >> 1; for (int i = l; i <= mid; i ++) if (c[i].id == 0) c0[++ sum] = c[i]; for (int i = mid + 1; i <= r; i ++) if (c[i].id != 0) c0[++ sum] = c[i]; sort (c0 + 1, c0 + sum + 1, [&](node a, node b) { if (a.x != b.x) return a.x < b.x; if (a.y != b.y) return a.y < b.y; return a.id < b.id; }); for (int i = 1; i <= sum; i ++) if (c0[i].id == 0) t.add(c0[i].y, c0[i].v); else ans[c0[i].id] += t.ask(c0[i].y) * c0[i].v; for (int i = 1; i <= sum; i ++) if (c0[i].id == 0) t.add(c0[i].y, -c0[i].v); solve(l, mid), solve(mid + 1, r); } int main() { ios::sync_with_stdio(false); cin >> n >> m; for (int i = 1; i <= n; i ++) cin >> a[i], check(i); for (int op, l, r, x, y, i = 1; i <= m; i ++) { cin >> op >> l >> r; if (op == 1) { if (a[l] == r) continue; clr(l), clr(l + 1); a[l] = r, check(l), check(l + 1); } else { cin >> x >> y; ans[++ id] = (!b[l]) & (x <= a[l] && a[l] <= y); c[++ k] = (node){r, y, 1, id}; c[++ k] = (node){l - 1, y, -1, id}; c[++ k] = (node){r, x - 1, -1, id}; c[++ k] = (node){l - 1, x - 1, 1, id}; } } solve(1, k); for (int i = 1; i <= id; i ++) printf("%d\n", ans[i]); return 0; }
[ "1217783313@qq.com" ]
1217783313@qq.com
54c32181fda033b69bfb9d00cbb6c132331694be
7067fef998a194e5f0997a1def3b7326947c0b54
/Common/AEAliasList.cp
2d269ba086014c0f8ced177a2f513209947129eb
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
quicksilver/OnMyCommand-qsplugin
3c8a0017603e809c11a50c2c4c3c5cea0d368bd7
14bd6c31c1210013db2c73fee249bdbf9b08a7ea
refs/heads/main
2022-06-02T09:53:48.389877
2011-07-26T09:40:46
2011-07-26T09:40:46
1,885,847
1
1
null
null
null
null
WINDOWS-1252
C++
false
false
5,786
cp
//************************************************************************************** // Filename: AEAliasList.cp // Part of Contextual Menu Workshop by Abracode Inc. // http://free.abracode.com/cmworkshop/ // Copyright © 2002-2003 Abracode, Inc. All rights reserved. // // Description: Lightweight list of alias objects stored in AEDescList // Main design features: // - the acutal list can be owned by this object or not // (there are many cases when we do not want this object to destroy the list) // - designed not to throw exceptions // - the list is 1-based // - no attempt is made to eliminate duplicates (ie pointing to the same objects) // //************************************************************************************** // Revision History: // Monday, August 12, 2002 - Original //************************************************************************************** #include "AEAliasList.h" #include "StAEDesc.h" #include "CMUtils.h" AEAliasList::AEAliasList(void) { mList.descriptorType = typeNull; mList.dataHandle = NULL; OSErr err = ::AECreateList( NULL, 0, false, &mList ); if(err == noErr) { mOwnList = true; } //what can I do about the error here? //I do nothing, hoping that mList.dataHandle will be null if error occured } AEAliasList::AEAliasList(const AEDescList *inList, Boolean inTakeOwnership, Boolean inCopyList /*= false*/) { mList.descriptorType = typeNull; mList.dataHandle = NULL; mOwnList = false; if(inCopyList) { CopyList( inList );//if you copy list, you always take ownership of it. inTakeOwnership is ignored } else { if(inTakeOwnership) { AdoptList( inList );//take ownership without copying } else if(inList != NULL) { mList = *inList;//just assign it } } } AEAliasList::~AEAliasList(void) { DisposeOfList(); } SInt32 AEAliasList::GetCount() const { if( mList.dataHandle == NULL ) return 0; SInt32 theCount = 0; if( ::AECountItems( &mList, &theCount) == noErr ) return theCount; return 0; } //add item to the end of the list OSErr AEAliasList::AddItem(const FSRef *inRef) { if( inRef == NULL) return paramErr; if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; OSErr err = CMUtils::CreateAliasDesc( inRef, objDesc ); if(err == noErr) { err = ::AEPutDesc( &mList, 0, objDesc ); } return err; } //add item to the end of the list OSErr AEAliasList::AddItem(const FSSpec *inFSSpec) { if( inFSSpec == NULL) return paramErr; if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; OSErr err = CMUtils::CreateAliasDesc( inFSSpec, objDesc ); if(err == noErr) { err = ::AEPutDesc( &mList, 0, objDesc ); } return err; } //add item to the end of the list OSErr AEAliasList::AddItem(const AliasHandle inAliasH) { if( inAliasH == NULL) return paramErr; if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; OSErr err = CMUtils::CreateAliasDesc( inAliasH, objDesc ); if(err == noErr) { err = ::AEPutDesc( &mList, 0, objDesc ); } return err; } //remember: 1-based indexes OSErr AEAliasList::FetchItemAt(SInt32 inIndex, FSSpec &outSpec) const { if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; AEKeyword theKeyword; OSErr err = ::AEGetNthDesc(&mList, inIndex, typeWildCard, &theKeyword, objDesc); if (err == noErr) { err = CMUtils::GetFSSpec(objDesc, outSpec); } return err; } //remember: 1-based indexes OSErr AEAliasList::FetchItemAt(SInt32 inIndex, FSRef &outRef) const { if( mList.dataHandle == NULL ) return nilHandleErr; StAEDesc objDesc; AEKeyword theKeyword; OSErr err = ::AEGetNthDesc(&mList, inIndex, typeWildCard, &theKeyword, objDesc); if (err == noErr) { err = CMUtils::GetFSRef(objDesc, outRef); } return err; } //remember: 1-based indexes OSErr AEAliasList::RemoveItemAt(SInt32 inIndex) { if( mList.dataHandle == NULL ) return nilHandleErr; return ::AEDeleteItem( &mList, inIndex); } OSErr AEAliasList::RemoveAllItems() { if( mList.dataHandle == NULL ) return nilHandleErr; OSErr err = noErr; SInt32 theCount = GetCount(); for(SInt32 i = 1; i<= theCount; i++) { err = ::AEDeleteItem( &mList, i); if(err != noErr) break; } return err; } OSErr AEAliasList::CopyList(const AEDescList *inList) { if( inList == NULL ) return nilHandleErr; if( inList->dataHandle == NULL ) return nilHandleErr; if( mOwnList && (inList->dataHandle == mList.dataHandle) ) {//self assignment case - when we own the list, there is no need to copy it return noErr; } AEDescList newList = {typeNull, NULL}; OSErr err = ::AEDuplicateDesc( inList, &newList); if( err == noErr ) { DisposeOfList();//it is now safe to destroy our previous data mList = newList; mOwnList = true; } return err; } //take ownership of the list OSErr AEAliasList::AdoptList(const AEDescList *inList) { if( inList == NULL ) return nilHandleErr; //check for self assignment, disposing of our data and then assigning it would be catastrophic if( inList->dataHandle == mList.dataHandle ) {//take ownership of it if we are not owning it yet mOwnList = true; return noErr;//we own it, there is need to reassign } DisposeOfList();//destroy our previous data mList = *inList; mOwnList = true; return noErr; } //releses ownership of the list //but does keep its data AEDescList AEAliasList::DisownList() { mOwnList = false; return mList; } //disposes of the list only when we own it //or forgets its data if we do not own it void AEAliasList::DisposeOfList() { if( mOwnList ) { if( mList.dataHandle != NULL ) { ::AEDisposeDesc( &mList ); } } mList.descriptorType = typeNull; mList.dataHandle = NULL; //mOwnList = false;//it does not matter if we own an empty list or not }
[ "jnj@57e2f9b5-c12c-0410-8e95-a1ee7272c91a" ]
jnj@57e2f9b5-c12c-0410-8e95-a1ee7272c91a
7fd5c3dd274707cf6e7443105f8b131b07097583
55b7dcc2d67efdf35106f8a9dcc3191333507dac
/sge/include/core/sgeMath.h
0c1ba29a5dea1c2251b2c7016899eb2fc8f7fd2f
[]
no_license
xiangwencheng1994/GLEngine
e1266e7e4fbc6f62be371a4ddc816a2a2167c537
0c60d52fe05a9ba7aeff09d1bab2d9290ace2211
refs/heads/master
2020-03-19T02:18:29.420897
2019-03-14T13:30:32
2019-03-14T13:30:32
135,616,823
1
0
null
null
null
null
UTF-8
C++
false
false
141,780
h
/** * * Simple graphic engine * "sge" libraiy is a simple graphics engine, named sge. * * sgeMath.h * date: 2017/12/01 * author: xiang * * License * * Copyright (c) 2017-2019, Xiang Wencheng <xiangwencheng@outlook.com> * 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 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. */ /************************************************************************/ /*This file copy can copy to everywhere, it does not include other file */ /************************************************************************/ #ifndef SGE_MATH_H #define SGE_MATH_H #pragma warning(push) #pragma warning(disable: 4251 4554) #pragma pack(push, 1) #include <cmath> #include <cstring> #include <iostream> #include <sstream> #include <string> #include <cassert> #ifndef M_PI #define M_PI (3.14159265358979323846) #endif #ifndef M_SQRT2 #define M_SQRT2 1.41421356237309504880 #endif #ifndef M_SQRT1_2 #define M_SQRT1_2 0.707106781186547524401 #endif #ifndef MAX # define MAX(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN # define MIN(a,b) (((a) < (b)) ? (a) : (b)) #endif #ifdef FLT_EPSILON #undef FLT_EPSILON #endif // FLT_EPSILON #define FLT_EPSILON 0.0000001f #ifdef FLT_EPSILON #undef DBL_EPSILON #endif // FLT_EPSILON #define DBL_EPSILON 0.0000000000000001 #ifdef max # undef max #endif #ifdef min # undef min #endif #ifndef MATH_TOLERANCE # define MATH_TOLERANCE 2e-37f #endif #define HAS_FLAG(item, flag) ((item) & (flag)) #define ADD_FLAG(item, flag) ((item) |= (flag)) #define REMOVE_FLAG(item, flag) ((item) &= ~(flag)) #define SET_FLAG(item, flag, enable) ((enable) ? ((item) |= (flag)) : ((item) &= ~(flag))) namespace sge { typedef unsigned char uchar; typedef unsigned char byte; typedef unsigned short ushort; typedef unsigned int uint; //-------------[ overload math functions ]------------- // Convert angle from degree to radian ,eg: 180 --> M_PI(3.14***) inline float DEG2RAD(int x) { return x * ((float)M_PI / (float)180); } inline float DEG2RAD(float x) { return x * ((float)M_PI / (float)180); } inline double DEG2RAD(double x) { return x * ((double)M_PI / (double)180); } // Convert angle from radian to degree ,eg: M_PI(3.14***) --> 180 inline float RAD2EDG(int x) { return (x) * ((float)180 / (float)M_PI); } inline float RAD2EDG(float x) { return (x) * ((float)180 / (float)M_PI); } inline double RAD2EDG(double x) { return (x) * ((double)180 / (double)M_PI); } // Equal test,"x==y" for integer, "fabs(x - y) < epsilon" for float inline bool equal(int x, int y) { return x == y; } inline bool equal(float x, float y) { return fabsf(x - y) < FLT_EPSILON; } inline bool equal(double x, double y) { return std::fabs(x - y) < DBL_EPSILON; } // Less test, "x<y" for int,"y - x > epsilon" for float inline bool less(int x, int y) { return x < y; } inline bool less(float x, float y) { return y - x > FLT_EPSILON; } inline bool less(double x, double y) { return y - x > DBL_EPSILON; } // sin(x),sine inline float sin(float x) { return sinf(x); } inline double sin(double x) { return std::sin(x); } // cos(x),cos inline float cos(float x) { return cosf(x); } inline double cos(double x) { return std::cos(x); } // sincos(x), *_S=sin(_X),*_C=cos(_X) inline void sincos(float _X, float *_S, float *_C) { *_S = sin(_X); *_C = cos(_X); } inline void sincos(double _X, double *_S, double *_C) { *_S = sin(_X); *_C = cos(_X); } // tan(x),tan inline float tan(float x) { return tanf(x); } inline double tan(double x) { return std::tan(x); } // asin(x), arcsin inline float asin(float x) { return asinf(x); } inline double asin(double x) { return std::asin(x); } // acos(x), arccos inline float acos(float x) { return acosf(x); } inline double acos(double x) { return std::acos(x); } // atan(x), arctan inline float atan(float x) { return atanf(x); } inline double atan(double x) { return std::atan(x); } // atan2(x), arctan2 inline float atan2(float x, float y) { return atan2f(x, y); } inline double atan2(double x, double y) { return std::atan2(x, y); } // sqrt(x), square inline float sqrt(int x) { return sqrtf((float)x); } inline float sqrt(float x) { return sqrtf(x); } inline double sqrt(double x) { return std::sqrt(x); } // abs inline long abs(long x) { return std::abs(x); } inline long long abs(long long x) { return std::abs(x); } inline int abs(int x) { return std::abs(x); } inline float abs(float x) { return fabsf(x); } inline double abs(double x) { return std::fabs(x); } template<typename T> class Vector2; template<typename T> class Vector3; template<typename T> class Vector4; template<typename T> class Matrix3; template<typename T> class Matrix4; template<typename T> class Quaternion; template<typename T> class Sphere; template<typename T> class Ray; /** * Class for two dimensional vector */ template<typename T> class Vector2 { public: T x; T y; public: /** * Creates and sets to (0,0) */ Vector2() : x(0), y(0) { } /** * Creates and sets to (x,y) * @param x initial x-coordinate value * @param y initial y-coordinate value */ Vector2(T x, T y) : x(x), y(y) { } /** * Copy constructor * @param src Source of data for new created instance */ Vector2(const Vector2<T> &src) : x(src.x), y(src.y) { } /** * Copy casting constructor * @param src Source of data for new created instance */ template<class FromT> Vector2(const Vector2<FromT>& src) : x(static_cast<T>(src.x)), y(static_cast<T>(src.y)) { } /** * Copy operator * @param rhs Right side argument of binary operator */ Vector2<T>& operator=(const Vector2<T> &rhs) { x = rhs.x; y = rhs.y; return *this; } /** * Copy casting operator * @param rhs Right side argument of binary operator */ template<class FromT> Vector2<T>& operator=(const Vector2<FromT>& rhs) { x = static_cast<T>(rhs.x); y = static_cast<T>(rhs.y); return *this; } /** * Array access operator * @param n Array index * @return x if n = 0, else return y */ T& operator[](int n) { ASSERT(n >= 0 && n <= 1); if (0 == n) return x; else return y; } /** * Constant array access operator * @param n Array index * @return x if n = 0, else return y */ const T& operator[](int n) const { ASSERT(n >= 0 && n <= 1); if (0 == n) return x; else return y; } /** * Get negate vector */ friend Vector2<T> operator-(const Vector2 &v) { return Vector2<T>( -v.x, -v.y); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Vector2<T> operator+(T rhs) const { return Vector2<T>(x + rhs, y + rhs); } /** * Operator for add with a vector * @param rhs Right side vector. */ Vector2<T> operator+(const Vector2<T>& rhs) const { return Vector2<T>(x + rhs.x, y + rhs.y); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Vector2<T>& operator+=(T rhs) { x += rhs; y += rhs; return *this; } /** * Operator for add with a vector * @param rhs Right side vector. */ Vector2<T>& operator+=(const Vector2<T>& rhs) { x += rhs.x; y += rhs.y; return *this; } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Vector2<T> operator-(T rhs) const { return Vector2<T>(x - rhs, y - rhs); } /** * Operator for subtract with a vector * @param rhs Right side vector. */ Vector2<T> operator-(const Vector2<T>& rhs) const { return Vector2<T>(x - rhs.x, y - rhs.y); } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Vector2<T>& operator-=(T rhs) { x -= rhs; y -= rhs; return *this; } /** * Operator for subtract with a vector * @param rhs Right side vector. */ Vector2<T>& operator-=(const Vector2<T>& rhs) { x -= rhs.x; y -= rhs.y; return *this; } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Vector2<T> operator*(T rhs) const { return Vector2<T>(x * rhs, y * rhs); } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector2<T> operator*(const Vector2<T>& rhs) const { return Vector2<T>(x * rhs.x, y * rhs.y); } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Vector2<T>& operator*=(T rhs) { x *= rhs; y *= rhs; return *this; } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector2<T>& operator*=(const Vector2<T>& rhs) { x *= rhs.x; y *= rhs.y; return *this; } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Vector2<T> operator/(T rhs) const { return Vector2<T>(x / rhs, y / rhs); } /** * Operator for divide with a vector * @param rhs Right side vector. */ Vector2<T> operator/(const Vector2<T>& rhs) const { return Vector2<T>(x / rhs.x, y / rhs.y); } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Vector2<T>& operator/=(T rhs) { x /= rhs; y /= rhs; return *this; } /** * Operator for divide with a vector * @param rhs Right side vector. */ Vector2<T>& operator/=(const Vector2<T>& rhs) { x /= rhs.x; y /= rhs.y; return *this; } /** * Equal test operator * @param rhs Right side vector. * @note Test of equality is based of equal fun. */ bool operator==(const Vector2<T>& rhs) const { return equal(x, rhs.x) && equal(y, rhs.y); } /** * Not equal test operator * @param rhs Right side vector. * @note Test of equality is based of equal fun. */ bool operator!=(const Vector2<T>& rhs) const { return !(*this == rhs); } /** * Get length of vector */ T length() const { return (T)sqrt(x * x + y * y); } /** * Return square of length. * @return length ^ 2 */ T lengthSq() const { return x * x + y * y; } /** * Normalize vector */ void normalize() { T s = length(); x /= s; y /= s; } /** * Conversion to pointer operator */ operator T*() { return (T*)this; } /** * Conversion to constant pointer operator */ operator const T*() const { return (const T*)this; } /** * Output to stream operator */ friend std::ostream& operator<<(std::ostream& lhs, const Vector2<T>& rhs) { lhs << rhs.toString(); return lhs; } /** * To string operator. */ std::string toString() const { char buffer[32]; sprintf(buffer, "%f,%f", x, y); return buffer; } /** * Linear interpolation of two vectors * @param fact Factor of interpolation. For translation from positon * of this vector to vector r, values of factor goes from 0.0 to 1.0. * @param v1 First Vector for interpolation * @param v2 Second Vector for interpolation */ static Vector2<T> lerp(const Vector2<T>& v1, const Vector2<T>& v2, T fact) { return v1 + (v2 - v1) * fact; } /** * Gets vector containing minimal values of @a a and @a b coordinates. * @return Vector of minimal coordinates. */ static Vector2<T> min(const Vector2<T>& a, const Vector2<T>& b) { return Vector2<T>(MIN(a.x, b.x), MIN(a.y, b.y)); } /** * Gets vector containing maximal values of @a a and @a b coordinates. * @return Vector of maximal coordinates. */ static Vector2<T> max(const Vector2<T>& a, const Vector2<T>& b) { return Vector2<T>(MAX(a.x, b.x), MAX(a.y, b.y)); } }; /** * Get a normalized vector2 */ template<typename T> Vector2<T> normalize(const Vector2<T>& v) { Vector2<T> ret = v; ret.normalize(); return ret; } /** * Rect */ template<typename T> struct Rect { public: Vector2<T> pos; Vector2<T> size; }; typedef Vector2<int> vec2i; typedef Vector2<int> int2; typedef Vector2<short> short2; typedef Vector2<ushort> ushort2; typedef Vector2<uint> uint2; typedef Vector2<float> vec2f; typedef Vector2<float> float2; typedef Vector2<double> vec2r; typedef Vector2<double> real2; typedef Rect<int> rect2i; typedef Rect<float> rect2f; typedef Rect<double> rect2r; /** * Dot product of two vectors. * @param a left side vector * @param b right side vector */ template<typename T> T dot(const Vector2<T>& a, const Vector2<T>& b) { return a.x * b.x + a.y * b.y; } /** * Calc the lengh of vector P project on vector Q dir * @param P vector * @param Q vector */ template<typename T> T projLength(const Vector2<T>& p, const Vector2<T>& q) { return dot(p, q) / q.length(); } /** * Calc the vecotr of vector P project on vector Q dir * @param P vector * @param Q vector */ template<typename T> Vector2<T> proj(const Vector2<T>& p, const Vector2<T>& q) { return q * (dot(p, q) / q.lengthSq()); } /** * Class for three dimensional vector */ template<typename T> class Vector3 { public: //union //{ // struct // { T x; T y; T z; // }; // Vector2<T> xy; //}; public: /** * Creates and sets to (0,0,0) */ Vector3() : x(0), y(0), z(0) { } /** * Creates and sets to (x,y,z) * @param x initial x-coordinate value * @param y initial y-coordinate value * @param z initial z-coordinate value */ Vector3(T x, T y, T z) : x(x), y(y), z(z) { } /** * Copy constructor * @param src Source of data for new created instance */ Vector3(const Vector3<T> &src) : x(src.x), y(src.y), z(src.z) { } /** * Copy casting constructor * @param src Source of data for new created instance */ template<class FromT> Vector3(const Vector3<FromT>& src) : x(static_cast<T>(src.x)) , y(static_cast<T>(src.y)) , z(static_cast<T>(src.z)) { } /** * Copy operator * @param rhs Right side argument of binary operator */ Vector3<T>& operator=(const Vector3<T> &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; return *this; } /** * Copy casting operator * @param rhs Right side argument of binary operator */ template<class FromT> Vector3<T>& operator=(const Vector3<FromT>& rhs) { x = static_cast<T>(rhs.x); y = static_cast<T>(rhs.y); z = static_cast<T>(rhs.z); return *this; } /** * Array access operator * @param n Array index * @return x if n = 0, return y if n = 1, else return z */ T& operator[](int n) { ASSERT(n >= 0 && n <= 2); if (0 == n) return x; else if (1 == n) return y; else return z; } /** * Constant array access operator * @param n Array index * @return x if n = 0, return y if n = 1, else return z */ const T& operator[](int n) const { ASSERT(n >= 0 && n <= 2); if (0 == n) return x; else if (1 == n) return y; else return z; } /** * Get negate vector */ friend Vector3<T> operator-(const Vector3& v) { return Vector3<T>(-v.x, -v.y, -v.z); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Vector3<T> operator+(T rhs) const { return Vector3<T>(x + rhs, y + rhs, z + rhs); } /** * Operator for add with a vector * @param rhs Right side vector. */ Vector3<T> operator+(const Vector3<T>& rhs) const { return Vector3<T>(x + rhs.x, y + rhs.y, z + rhs.z); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Vector3<T>& operator+=(T rhs) { x += rhs; y += rhs; z += rhs; return *this; } /** * Operator for add with a vector * @param rhs Right side vector. */ Vector3<T>& operator+=(const Vector3<T>& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Vector3<T> operator-(T rhs) const { return Vector3<T>(x - rhs, y - rhs, z - rhs); } /** * Operator for subtract with a vector * @param rhs Right side vector. */ Vector3<T> operator-(const Vector3<T>& rhs) const { return Vector3<T>(x - rhs.x, y - rhs.y, z - rhs.z); } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Vector3<T>& operator-=(T rhs) { x -= rhs; y -= rhs; z -= rhs; return *this; } /** * Operator for subtract with a vector * @param rhs Right side vector. */ Vector3<T>& operator-=(const Vector3<T>& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Vector3<T> operator*(T rhs) const { return Vector3<T>(x * rhs, y * rhs, z * rhs); } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector3<T> operator*(const Vector3<T>& rhs) const { return Vector3<T>(x * rhs.x, y * rhs.y, z * rhs.z); } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Vector3<T>& operator*=(T rhs) { x *= rhs; y *= rhs; z *= rhs; return *this; } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector3<T>& operator*=(const Vector3<T>& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; return *this; } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Vector3<T> operator/(T rhs) const { return Vector3<T>(x / rhs, y / rhs, z / rhs); } /** * Operator for divide with a vector * @param rhs Right side vector. */ Vector3<T> operator/(const Vector3<T>& rhs) const { return Vector3<T>(x / rhs.x, y / rhs.y, z / rhs.z); } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Vector3<T>& operator/=(T rhs) { x /= rhs; y /= rhs; z /= rhs; return *this; } /** * Operator for divide with a vector * @param rhs Right side vector. */ Vector3<T>& operator/=(const Vector3<T>& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; return *this; } /** * Equal test operator * @param rhs Right side vector. * @note Test of equality is based of equal fun. */ bool operator==(const Vector3<T>& rhs) const { return equal(x, rhs.x) && equal(y, rhs.y) && equal(z, rhs.z); } /** * Not equal test operator * @param rhs Right side vector. * @note Test of equality is based of equal fun. */ bool operator!=(const Vector3<T>& rhs) const { return !(*this == rhs); } /** * Get length of vector */ T length() const { return (T)sqrt(x * x + y * y + z * z); } /** * Return square of length. * @return length ^ 2 */ T lengthSq() const { return x * x + y * y + z * z; } /** * Normalize vector */ void normalize() { T s = length(); x /= s; y /= s; z /= s; } /** * Conversion to pointer operator */ operator T*() { return (T*)this; } /** * Conversion to constant pointer operator */ operator const T*() const { return (const T*)this; } /** * Output to stream operator */ friend std::ostream& operator<<(std::ostream& lhs, const Vector3<T>& rhs) { lhs << rhs.toString(); return lhs; } /** * To string operator. */ std::string toString() const { char buffer[48]; sprintf(buffer, "%f,%f,%f", x, y, z); return buffer; } /** * Linear interpolation of two vectors * @param fact Factor of interpolation. For translation from positon * of this vector to vector r, values of factor goes from 0.0 to 1.0. * @param v1 First Vector for interpolation * @param v2 Second Vector for interpolation */ static Vector3<T> lerp(const Vector3<T>& v1, const Vector3<T>& v2, T fact) { return v1 + (v2 - v1) * fact; } /** * Gets vector containing minimal values of @a a and @a b coordinates. * @return Vector of minimal coordinates. */ static Vector3<T> min(const Vector3<T>& a, const Vector3<T>& b) { return Vector3<T>(MIN(a.x, b.x), MIN(a.y, b.y), MIN(a.z, b.z)); } /** * Gets vector containing maximal values of @a a and @a b coordinates. * @return Vector of maximal coordinates. */ static Vector3<T> max(const Vector3<T>& a, const Vector3<T>& b) { return Vector3<T>(MAX(a.x, b.x), MAX(a.y, b.y), MAX(a.z, b.z)); } /** * Rotate a vector around X-axis. * @param v The target vector * @param angle The angle in degree * @return the vector after around */ static Vector3<T> rotateX(const Vector3<T>& v, T angle) { Vector3<T> res(v); T c, s; sincos(DEG2RAD(angle), &s, &c); res.y = v.y * c - v.z * s; res.z = v.y * s + v.z * c; return res; } /** * Rotate a vector around Y-axis. * @param v The target vector * @param angle The angle in degree * @return the vector after around */ static Vector3<T> rotateY(Vector3<T> const & v, T angle) { Vector3<T> res = v; T c, s; sincos(DEG2RAD(angle), &s, &c); res.x = v.x * c + v.z * s; res.z = -v.x * s + v.z * c; return res; } /** * Rotate a vector around Z-axis. * @param v The target vector * @param angle The angle in degree * @return the vector after around */ static Vector3<T> rotateZ(Vector3<T> const & v, T angle) { Vector3<T> res = v; T c, s; sincos(DEG2RAD(angle), &s, &c); res.x = v.x * c - v.y * s; res.y = v.x * s + v.y * c; return res; } }; /** * Get a normalized vector3 */ template<typename T> Vector3<T> normalize(const Vector3<T>& v) { Vector3<T> ret = v; ret.normalize(); return ret; } typedef Vector3<char> char3; typedef Vector3<uchar> uchar3; typedef Vector3<uchar> rgb; typedef Vector3<int> vec3i; typedef Vector3<int> int3; typedef Vector3<short> short3; typedef Vector3<ushort> ushort3; typedef Vector3<uint> uint3; typedef Vector3<float> vec3f; typedef Vector3<float> float3; typedef Vector3<double> vec3r; typedef Vector3<double> real3; /** * Dot product of two vectors. * @param a left side vector * @param b right side vector */ template<typename T> T dot(const Vector3<T>& a, const Vector3<T>& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } /** * Cross product of two vectors. * @param a left side vector * @param b right side vector */ template<typename T> Vector3<T> cross(const Vector3<T>& a, const Vector3<T>& b) { return Vector3<T>(a.y * b.z - b.y * a.z, a.z * b.x - b.z * a.x, a.x * b.y - b.x * a.y); } /** * Calc the lengh of vector P project on vector Q dir * @param P vector * @param Q vector */ template<typename T> T projLength(const Vector3<T>& p, const Vector3<T>& q) { return dot(p, q) / q.length(); } /** * Calc the vecotr of vector P project on vector Q dir * @param P vector * @param Q vector */ template<typename T> Vector3<T> proj(const Vector3<T>& p, const Vector3<T>& q) { return q * (dot(p, q) / q.lengthSq()); } /** * Class for four dimensional vector */ template<typename T> class Vector4 { public: //union //{ // struct // { T x; T y; T z; T w; // }; // Vector3<T> xyz; //}; public: /** * Creates and sets to (0,0,0,0) */ Vector4() : x(0), y(0), z(0), w(0) { } /** * Creates and sets to (x,y,z,w) * @param x initial x-coordinate value * @param y initial y-coordinate value * @param z initial z-coordinate value * @param w initial w-coordinate value */ Vector4(T x, T y, T z, T w) : x(x), y(y), z(z), w(w) { } /** * Creates from vector3 and sets to (v.x,v.y,v.z,w) * @param v initial vector3 * @param w initial w-coordinate value */ Vector4(const Vector3<T>& v, T w = 1) : x(v.x), y(v.y), z(v.z), w(w) { } /** * Copy constructor * @param src Source of data for new created instance */ Vector4(const Vector4<T> &src) : x(src.x), y(src.y), z(src.z), w(src.w) { } /** * Copy casting constructor * @param src Source of data for new created instance */ template<class FromT> Vector4(const Vector4<FromT>& src) : x(static_cast<T>(src.x)) , y(static_cast<T>(src.y)) , z(static_cast<T>(src.z)) , w(static_cast<T>(src.w)) { } /** * Copy operator * @param rhs Right side argument of binary operator */ Vector4<T>& operator=(const Vector4<T> &rhs) { x = rhs.x; y = rhs.y; z = rhs.z; w = rhs.w; return *this; } /** * Copy casting operator * @param rhs Right side argument of binary operator */ template<class FromT> Vector4<T>& operator=(const Vector4<FromT>& rhs) { x = static_cast<T>(rhs.x); y = static_cast<T>(rhs.y); z = static_cast<T>(rhs.z); w = static_cast<T>(rhs.w); return *this; } /** * Array access operator * @param n Array index * @return x if n = 0, return y if n = 1, return z if n = 2,else return w */ T& operator[](int n) { ASSERT(n >= 0 && n <= 3); if (0 == n) return x; else if (1 == n) return y; else if (2 == n) return z; else return w; } /** * Array access operator * @param n Array index * @return x if n = 0, return y if n = 1, return z if n = 2,else return w */ const T& operator[](int n) const { ASSERT(n >= 0 && n <= 3); if (0 == n) return x; else if (1 == n) return y; else if (2 == n) return z; else return w; } /** * Get negate vector */ friend Vector4<T> operator-(const Vector4& v) { return Vector4<T>(-v.x, -v.y, -v.z, -v.w); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Vector4<T> operator+(T rhs) const { return Vector4<T>(x + rhs, y + rhs, z + rhs, w + rhs); } /** * Operator for add with a vector * @param rhs Right side vector. */ Vector4<T> operator+(const Vector4<T>& rhs) const { return Vector4<T>(x + rhs.x, y + rhs.y, z + rhs.z, w + rhs.w); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Vector4<T>& operator+=(T rhs) { x += rhs; y += rhs; z += rhs; w += rhs; return *this; } /** * Operator for add with a vector * @param rhs Right side vector. */ Vector4<T>& operator+=(const Vector4<T>& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; w += rhs.w; return *this; } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Vector4<T> operator-(T rhs) const { return Vector4<T>(x - rhs, y - rhs, z - rhs, w - rhs); } /** * Operator for subtract with a vector * @param rhs Right side vector. */ Vector4<T> operator-(const Vector4<T>& rhs) const { return Vector4<T>(x - rhs.x, y - rhs.y, z - rhs.z, w - rhs.w); } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Vector4<T>& operator-=(T rhs) { x -= rhs; y -= rhs; z -= rhs; w -= rhs; return *this; } /** * Operator for subtract with a vector * @param rhs Right side vector. */ Vector4<T>& operator-=(const Vector4<T>& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; w -= rhs.w; return *this; } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Vector4<T> operator*(T rhs) const { return Vector4<T>(x * rhs, y * rhs, z * rhs, w * rhs); } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector4<T> operator*(const Vector4<T>& rhs) const { return Vector4<T>(x * rhs.x, y * rhs.y, z * rhs.z, w * rhs.w); } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Vector4<T>& operator*=(T rhs) { x *= rhs; y *= rhs; z *= rhs; w *= rhs; return *this; } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector4<T>& operator*=(const Vector4<T>& rhs) { x *= rhs.x; y *= rhs.y; z *= rhs.z; w *= rhs.w; return *this; } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Vector4<T> operator/(T rhs) const { return Vector4<T>(x / rhs, y / rhs, z / rhs, w / rhs); } /** * Operator for divide with a vector * @param rhs Right side vector. */ Vector4<T> operator/(const Vector4<T>& rhs) const { return Vector4<T>(x / rhs.x, y / rhs.y, z / rhs.z, w / rhs.w); } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Vector4<T>& operator/=(T rhs) { x /= rhs; y /= rhs; z /= rhs; w /= rhs; return *this; } /** * Operator for divide with a vector * @param rhs Right side vector. */ Vector4<T>& operator/=(const Vector4<T>& rhs) { x /= rhs.x; y /= rhs.y; z /= rhs.z; w /= rhs.w; return *this; } /** * Equal test operator * @param rhs Right side vector. * @note Test of equality is based of equal fun. */ bool operator==(const Vector4<T>& rhs) const { return equal(x, rhs.x) && equal(y, rhs.y) && equal(z, rhs.z) && equal(w, rhs.w); } /** * Not equal test operator * @param rhs Right side vector. * @note Test of equality is based of equal fun. */ bool operator!=(const Vector4<T>& rhs) const { return !(*this == rhs); } /** * Get length of vector */ T length() const { return (T)sqrt(x * x + y * y + z * z + w * w); } /** * Return square of length. * @return length ^ 2 */ T lengthSq() const { return x * x + y * y + z * z + w * w; } /** * Normalize vector */ void normalize() { T s = length(); x /= s; y /= s; z /= s; w /= s; } /** * Conversion to pointer operator */ operator T*() { return (T*)this; } /** * Conversion to constant pointer operator */ operator const T*() const { return (const T*)this; } /** * Output to stream operator */ friend std::ostream& operator<<(std::ostream& lhs, const Vector4<T>& rhs) { lhs << rhs.toString(); return lhs; } /** * To string operator. */ std::string toString() const { char buffer[64]; sprintf(buffer, "%f,%f,%f,%f", x, y, z, w); return buffer; } /** * Linear interpolation of two vectors * @param fact Factor of interpolation. For translation from positon * of this vector to vector r, values of factor goes from 0.0 to 1.0. * @param v1 First Vector for interpolation * @param v2 Second Vector for interpolation */ static Vector4<T> lerp(const Vector4<T>& v1, const Vector4<T>& v2, T fact) { return v1 + (v2 - v1) * fact; } /** * Gets vector containing minimal values of @a a and @a b coordinates. * @return Vector of minimal coordinates. */ static Vector4<T> min(const Vector4<T>& a, const Vector4<T>& b) { return Vector4<T>(MIN(a.x, b.x), MIN(a.y, b.y), MIN(a.z, b.z), MIN(a.w, b.w)); } /** * Gets vector containing maximal values of @a a and @a b coordinates. * @return Vector of maximal coordinates. */ static Vector4<T> max(const Vector4<T>& a, const Vector4<T>& b) { return Vector4<T>(MAX(a.x, b.x), MAX(a.y, b.y), MAX(a.z, b.z), MAX(a.w, b.w)); } }; typedef Vector4<uchar> char4; typedef Vector4<uchar> uchar4; typedef Vector4<uchar> rgba; typedef Vector4<short> short4; typedef Vector4<ushort> ushort4; typedef Vector4<int> vec4i; typedef Vector4<int> int4; typedef Vector4<uint> uint4; typedef Vector4<float> vec4f; typedef Vector4<float> float4; typedef Vector4<double> vec4r; typedef Vector4<double> real4; /** * Make a int color from a rgba data * @param r The red channel * @param g The green channel * @param b The blue channel * @param a The alpha channel * @return The int value */ inline int INT_RGBA(uchar r, uchar g, uchar b, uchar a) { return ((int)r) << 24 + ((int)g) << 16 + ((int)b) << 8 + (int)a; } /** * Make a int color from a rgb data * @param r The red channel * @param g The green channel * @param b The blue channel * @return The int value */ inline int INT_RGB(uchar r, uchar g, uchar b) { return ((int)r) << 24 + ((int)g) << 16 + ((int)b) << 8; } /** * Get the red channel from a int color */ inline uchar INT_RED(int color) { return (uchar)((color & 0xFF000000) >> 24); } /** * Get the red channel from a int color */ inline uchar INT_GREEN(int color) { return (uchar)((color & 0x00FF0000) >> 16); } /** * Get the blue channel from a int color */ inline uchar INT_BLUE(int color) { return (uchar)((color & 0x0000FF00) >> 8); } /** * Get the alpha channel from a int color */ inline uchar INT_ALPHA(int color) { return (uchar)color & 0x000000FF; } /** * Class for rgba color */ class Rgba : public Vector4<uchar> { public: Rgba(uchar r, uchar g, uchar b, uchar a = 255) : Vector4(r, g, b, a) {} Rgba(int rgba) : Vector4(INT_RED(rgba), INT_GREEN(rgba), INT_BLUE(rgba), INT_ALPHA(rgba)) { } Rgba(Vector4<float> color) : Vector4((uchar)(color.x * 255), (uchar)(color.y * 255), (uchar)(color.z * 255), (uchar)(color.w * 255)) { } Rgba(Vector3<float> color) : Vector4((uchar)(color.x * 255), (uchar)(color.y * 255), (uchar)(color.z * 255), (uchar)(255)) { } uchar red() { return x; } uchar green() { return y; } uchar blue() { return z; } uchar alpha() { return w; } int value() { return operator int(); } operator Vector4<float>() { return Vector4<float>(x / 255.0f, y / 255.0f, z / 255.0f, w / 255.0f); } operator int() { return INT_RGBA(red(), green(), blue(), alpha()); } }; /** * Class for matrix 3x3. * @note Data stored in this matrix are in column major order. This arrangement suits OpenGL. * If you're using row major matrix, consider using fromRowMajorArray as way for construction * Matrix3<T> instance. */ template<typename T> class Matrix3 { public: union { T cel[3][3]; T data[9]; Vector3<T> row[3]; }; public: /** * Creates identity matrix */ Matrix3() { } /** * Copy matrix values from array * @param dt data array (these data must be in column major order!) */ Matrix3(const T * dt) { memcpy(data, dt, sizeof(T) * 9); } /** * Copy constructor. * @param src Data source for new created instance of Matrix3 */ Matrix3(const Matrix3<T>& src) { memcpy(data, src.data, sizeof(T) * 9); } /** * Copy casting constructor. * @param src Data source for new created instance of Matrix3 */ template<class FromT> Matrix3(const Matrix3<FromT>& src) { for (int i = 0; i < 9; i++) { data[i] = static_cast<T>(src.data[i]); } } /** * Copy operator * @param rhs source matrix. */ Matrix3<T>& operator=(const Matrix3<T>& rhs) { memcpy(data, rhs.data, sizeof(T) * 9); return *this; } /** * Copy casting operator * @param rhs source matrix. */ template<class FromT> Matrix3<T>& operator=(const Matrix3<FromT>& rhs) { for (int i = 0; i < 9; i++) { data[i] = static_cast<T>(rhs.data[i]); } return *this; } /** * Copy operator * @param rhs source array. */ Matrix3<T>& operator=(const T* rhs) { memcpy(data, rhs, sizeof(T) * 9); return *this; } /** * Resets matrix to be identity matrix */ void identity() { for (int i = 0; i < 9; i++) data[i] = (i % 4) ? (T)0 : (T)1; } /** * Creates rotation matrix by rotation around axis. * @param xDeg Angle (in degrees) of rotation around axis X. * @param yDeg Angle (in degrees) of rotation around axis Y. * @param zDeg Angle (in degrees) of rotation around axis Z. */ static Matrix3<T> createRotationAroundAxis(T xDeg, T yDeg, T zDeg) { T xRads(DEG2RAD(xDeg)); T yRads(DEG2RAD(yDeg)); T zRads(DEG2RAD(zDeg)); Matrix3<T> ma, mb, mc; T ac, as, bc, bs, cc, cs; sincos(xRads, &as, &ac); sincos(yRads, &bs, &bc); sincos(zRads, &cs, &cc); ma.identity(); ma.cel[1][1] = ac; ma.cel[2][1] = as; ma.cel[1][2] = -as; ma.cel[2][2] = ac; mb.identity(); mb.cel[0][0] = bc; mb.cel[2][0] = -bs; mb.cel[0][2] = bs; mb.cel[2][2] = bc; mc.identity(); mc.cel[0][0] = cc; mc.cel[1][0] = cs; mc.cel[0][1] = -cs; mc.cel[1][1] = cc; Matrix3<T> ret = ma * mb * mc; return ret; } /** * Create scale matrix with @a sx, @a sy, and @a sz * being values of matrix main diagonal. * @param sx Scale in X-axis * @param sy Scale in Y-axis * @param sz Scale in Z-axis * @return Transform matrix 4x4 with scale transformation. */ static Matrix3<T> createScale(T sx, T sy, T sz) { Matrix3<T> ret; ret.identity(); ret.cel[0][0] = sx; ret.cel[1][1] = sy; ret.cel[2][2] = sz; return ret; } /** * Creates new matrix 3x3 from a array in row major order. * @param arr An array of elements for 3x3 matrix in row major order. * @return An instance of Matrix3<T> representing @a arr */ template<class FromT> static Matrix3<T> fromRowMajorArray(const FromT* arr) { const T retData[] = { static_cast<T>(arr[0]), static_cast<T>(arr[3]), static_cast<T>(arr[6]), static_cast<T>(arr[1]), static_cast<T>(arr[4]), static_cast<T>(arr[7]), static_cast<T>(arr[2]), static_cast<T>(arr[5]), static_cast<T>(arr[8]) }; return retData; } /** * Creates new matrix 3x3 from a array in column major order. * @param arr An array of elements for 3x3 matrix in column major order. * @return An instance of Matrix3<T> representing @a arr */ template<class FromT> static Matrix3<T> fromColumnMajorArray(const FromT* arr) { const T retData[] = { static_cast<T>(arr[0]), static_cast<T>(arr[1]), static_cast<T>(arr[2]), static_cast<T>(arr[3]), static_cast<T>(arr[4]), static_cast<T>(arr[5]), static_cast<T>(arr[6]), static_cast<T>(arr[7]), static_cast<T>(arr[8]) }; return retData; } /** * Equal operator * @param rhs right side matirx. * @return true if all data[i] equal with rhs.data[i] * @note Test of equality is based of equal function. */ bool operator==(const Matrix3<T>& rhs) const { for (int i = 0; i < 9; i++) { if (! equal(data[i], rhs.data[i])) return false; } return true; } /** * Not equal operator * @param rhs right side matirx. * @return not (lhs == rhs) :-P */ bool operator!=(const Matrix3<T>& rhs) const { return !(*this == rhs); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Matrix3<T> operator+(T rhs) const { Matrix3<T> ret; for (int i = 0; i < 9; i++) ret.data[i] = data[i] + rhs; return ret; } /** * Operator for add with a matrix * @param rhs Right side matrix. */ Matrix3<T> operator+(const Matrix3<T>& rhs) const { Matrix3<T> ret; for (int i = 0; i < 9; i++) ret.data[i] = data[i] + rhs.data[i]; return ret; } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Matrix3<T> operator-(T rhs) const { Matrix3<T> ret; for (int i = 0; i < 9; i++) ret.data[i] = data[i] - rhs; return ret; } /** * Operator for subtract with a matrix * @param rhs Right side matrix. */ Matrix3<T> operator-(const Matrix3<T>& rhs) const { Matrix3<T> ret; for (int i = 0; i < 9; i++) ret.data[i] = data[i] - rhs.data[i]; return ret; } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Matrix3<T> operator*(T rhs) const { Matrix3<T> ret; for (int i = 0; i < 9; i++) ret.data[i] = data[i] * rhs; return ret; } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Matrix3<T> operator/(T rhs) const { Matrix3<T> ret; for (int i = 0; i < 9; i++) ret.data[i] = data[i] / rhs; return ret; } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector3<T> operator*(const Vector3<T>& rhs) const { return Vector3<T>(data[0] * rhs.x + data[3] * rhs.y + data[6] * rhs.z, data[1] * rhs.x + data[4] * rhs.y + data[7] * rhs.z, data[2] * rhs.x + data[5] * rhs.y + data[8] * rhs.z); } /** * Operator for multiply with a matrix * @param rhs Right side matrix. */ Matrix3<T> operator*(Matrix3<T> rhs) const { Matrix3<T> w; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { T n = 0; for (int k = 0; k < 3; k++) n += rhs.cel[i][k] * cel[k][j]; w.cel[i][j] = n; } } return w; } /** * Transpose matrix. */ Matrix3<T> transpose() { Matrix3<T> ret; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { ret.cel[i][j] = cel[j][i]; } } return ret; } /** * Get determinant of matrix * @return Determinant of matrix. */ T det() { return +cel[0][0] * cel[1][1] * cel[2][2] + cel[0][1] * cel[1][2] * cel[2][0] + cel[0][2] * cel[1][0] * cel[2][1] - cel[0][0] * cel[1][2] * cel[2][1] - cel[0][1] * cel[1][0] * cel[2][2] - cel[0][2] * cel[1][1] * cel[2][0]; } /** * Get inverse matrix * @return Inverse matrix of this matrix. */ Matrix3<T> inverse() { Matrix3<T> ret; ret.cel[0][0] = cel[1][1] * cel[2][2] - cel[2][1] * cel[1][2]; ret.cel[0][1] = cel[2][1] * cel[0][2] - cel[0][1] * cel[2][2]; ret.cel[0][2] = cel[0][1] * cel[1][2] - cel[1][1] * cel[0][2]; ret.cel[1][0] = cel[2][0] * cel[1][2] - cel[1][0] * cel[2][2]; ret.cel[1][1] = cel[0][0] * cel[2][2] - cel[2][0] * cel[0][2]; ret.cel[1][2] = cel[1][0] * cel[0][2] - cel[0][0] * cel[1][2]; ret.cel[2][0] = cel[1][0] * cel[2][1] - cel[2][0] * cel[1][1]; ret.cel[2][1] = cel[2][0] * cel[0][1] - cel[0][0] * cel[2][1]; ret.cel[2][2] = cel[0][0] * cel[1][1] - cel[1][0] * cel[0][1]; return ret / det(); } /** * Conversion to pointer * @return Data pointer */ operator T*() { return (T*)data; } /** * Conversion to pointer * @return Constant Data pointer */ operator const T*() const { return (const T*)data; } /** * Output to stream operator */ friend std::ostream& operator <<(std::ostream& lhs, const Matrix3<T>& rhs) { lhs << rhs.toString(); return lhs; } /** * To string operator. */ std::string toString() const { char buffer[16 * 4 * 4]; sprintf(buffer, "\n\t\t|%f,%f,%f|\n" "\t\t|%f,%f,%f|\n" "\t\t|%f,%f,%f|\n", data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]); return buffer; } }; typedef Matrix3<float> mat3f; typedef Matrix3<double> mat3r; /** * Class for matrix 4x4. * @note Data stored in this matrix are in column major order. This arrangement suits OpenGL. * If you're using row major matrix, consider using fromRowMajorArray as way for construction * Matrix4<T> instance. */ template<typename T> class Matrix4 { public: /** * Data stored in column major order */ union { T cel[4][4]; T data[16]; Vector4<T> row[4]; }; public: /** * Creates identity matrix */ Matrix4() { } /** * Copy matrix values from array * @param dt data array (these data must be in column major order!) */ Matrix4(const T * dt) { memcpy(data, dt, sizeof(T) * 16); } /** * Copy constructor. * @param src Data source for new created instance of Matrix3 */ Matrix4(const Matrix4<T>& src) { memcpy(data, src.data, sizeof(T) * 16); } /** * Copy casting constructor. * @param src Data source for new created instance of Matrix3 */ template<class FromT> Matrix4(const Matrix4<FromT>& src) { for (int i = 0; i < 16; i++) { data[i] = static_cast<T>(src.data[i]); } } /** * Copy operator * @param rhs source matrix. */ Matrix4<T>& operator=(const Matrix4<T>& rhs) { memcpy(data, rhs.data, sizeof(T) * 16); return *this; } /** * Copy casting operator * @param rhs source matrix. */ template<class FromT> Matrix4<T>& operator=(const Matrix4<FromT>& rhs) { for (int i = 0; i < 16; i++) { data[i] = static_cast<T>(rhs.data[i]); } return *this; } /** * Copy operator * @param rhs source array. */ Matrix4<T>& operator=(const T* rhs) { memcpy(data, rhs, sizeof(T) * 16); return *this; } /** * Resets matrix to be identity matrix */ void identity() { for (int i = 0; i < 16; i++) data[i] = (i % 5) ? (T)0 : (T)1; } /** * Creates rotation matrix by rotation around axis. * @param xDeg Angle (in degrees) of rotation around axis X. * @param yDeg Angle (in degrees) of rotation around axis Y. * @param zDeg Angle (in degrees) of rotation around axis Z. */ static Matrix4<T> createRotationAroundAxis(T xDeg, T yDeg, T zDeg) { Matrix4<T> mat; mat.toRotationAroundAxis(xDeg, yDeg, zDeg); return mat; } /** * Change matrix to rotation matrix by rotation around axis. * @param xDeg Angle (in degrees) of rotation around axis X. * @param yDeg Angle (in degrees) of rotation around axis Y. * @param zDeg Angle (in degrees) of rotation around axis Z. */ void toRotationAroundAxis(T xDeg, T yDeg, T zDeg) { T xRads(DEG2RAD(xDeg)); T yRads(DEG2RAD(yDeg)); T zRads(DEG2RAD(zDeg)); Matrix4<T> ma, mb, mc; T ac, as, bc, bs, cc, cs; sincos(xRads, &as, &ac); sincos(yRads, &bs, &bc); sincos(zRads, &cs, &cc); ma.identity(); ma.cel[1][1] = ac; ma.cel[2][1] = as; ma.cel[1][2] = -as; ma.cel[2][2] = ac; mb.identity(); mb.cel[0][0] = bc; mb.cel[2][0] = -bs; mb.cel[0][2] = bs; mb.cel[2][2] = bc; mc.identity(); mc.cel[0][0] = cc; mc.cel[1][0] = cs; mc.cel[0][1] = -cs; mc.cel[1][1] = cc; *this = ma * mb * mc; } /** * Creates rotation matrix to rotation around the axis * @param angle The around angle (in degrees) * @param axis The axis of rotation */ static Matrix4<T> createRotationAroundAxis(T angle, Vector3<T> axis) { Matrix4<T> mat; mat.toRotationAroundAxis(angle, axis); return mat; } /** * Change matrix to rotation around the axis. * @param angle The around angle (in degrees) * @param axis The axis of rotation */ void toRotationAroundAxis(T angle, Vector3<T> axis) { // Make sure the input axis is normalized. axis.normalize(); T c = cos(DEG2RAD(angle)); T s = sin(DEG2RAD(angle)); T t = T(1) - c; T tx = t * axis.x; T ty = t * axis.y; T tz = t * axis.z; T txy = tx * axis.y; T txz = tx * axis.z; T tyz = ty * axis.z; T sx = s * axis.x; T sy = s * axis.y; T sz = s * axis.z; data[0] = c + tx * axis.x; data[1] = txy + sz; data[2] = txz - sy; data[3] = T(0); data[4] = txy - sz; data[5] = c + ty * axis.y; data[6] = tyz + sx; data[7] = T(0); data[8] = txz + sy; data[9] = tyz - sx; data[10] = c + tz * axis.z; data[11] = T(0); data[12] = T(0); data[13] = T(0); data[14] = T(0); data[15] = T(1); } /** * Creates translation matrix. * @param x X-direction translation * @param y Y-direction translation * @param z Z-direction translation * @param w for W-coordinate translation (implicitly set to 1) */ static Matrix4<T> createTranslation(T x, T y, T z, T w = 1) { Matrix4<T> mat; mat.identity(); mat.setTranslation(x, y, z, w); return mat; } /** * Creates translation matrix. * @param v The translation Vector */ static Matrix4<T> createTranslation(const Vector3<T>& v, T w = 1) { Matrix4<T> mat; mat.identity(); mat.setTranslation(v.x, v.y, v.z, w); return mat; } /** * Set translation. * @param x X-direction translation * @param y Y-direction translation * @param z Z-direction translation * @param w for W-coordinate translation (implicitly set to 1) */ void setTranslation(T x, T y, T z, T w = 1) { cel[3][0] = x; cel[3][1] = y; cel[3][2] = z; cel[3][3] = w; } /** * Create scale matrix with @a sx, @a sy, and @a sz * being values of matrix main diagonal. * @param sx Scale in X-axis * @param sy Scale in Y-axis * @param sz Scale in Z-axis * @return Transform matrix 4x4 with scale transformation. */ static Matrix4<T> createScale(T sx, T sy, T sz) { Matrix4<T> mat; mat.identity(); mat.cel[0][0] = sx; mat.cel[1][1] = sy; mat.cel[2][2] = sz; return mat; } /** * Create scale matrix with @a vec3 * being values of matrix main diagonal. * @param v Scale * @return Transform matrix 4x4 with scale transformation. */ static Matrix4<T> createScale(Vector3<T> v) { return createScale(v.x, v.y, v.z); } /** * Creates new view matrix to look from specified position @a eyePos to specified position @a centerPos * @param eyePos A position of camera * @param centerPos A position where camera looks-at * @param upDir Direction of up vector * @return Resulting view matrix that looks from and at specific position. */ static Matrix4<T> createLookAt(const Vector3<T>& eyePos, const Vector3<T>& centerPos, const Vector3<T>& upDir) { Vector3<T> forward, side, up; Matrix4<T> m; forward = centerPos - eyePos; up = upDir; forward.normalize(); // Side = forward x up side = cross(forward, up); side.normalize(); // Recompute up as: up = side x forward up = cross(side, forward); m.identity(); m.cel[0][0] = side.x; m.cel[1][0] = side.y; m.cel[2][0] = side.z; m.cel[0][1] = up.x; m.cel[1][1] = up.y; m.cel[2][1] = up.z; m.cel[0][2] = -forward.x; m.cel[1][2] = -forward.y; m.cel[2][2] = -forward.z; m = m * createTranslation(-eyePos.x, -eyePos.y, -eyePos.z); return m; } /** * Creates perspective projection according specified frustum parameters. * @param left Specify the coordinate for the left vertical clipping plane, * @param right Specify the coordinate for the right vertical clipping plane. * @param bottom Specify the coordinate for the bottom horizontal clipping plane, * @param top Specify the coordinate for the top horizontal clipping plane. * @param zNear Specify the distance to the near clipping plane. Distance must be positive. * @param zFar Specify the distance to the far depth clipping plane. Distance must be positive. * @return Projection matrix for specified frustum. */ static Matrix4<T> createFrustum(T left, T right, T bottom, T top, T zNear, T zFar) { /* |-------------------------------------------------------| | 2 zNear | | ------------ 0 0 0 | | right - left | | | | 2 zNear | | 0 ------------ 0 0 | | top - bottom | | | | A B C -1 | | | | 0 0 D 0 | |-------------------------------------------------------| A = (right + left) / (right - left) B = (top + bottom) / (top - bottom) C = - (zFar + zNear) / (zFar - zNear) D = - (2 zFar zNear) / (zFar - zNear) */ Matrix4<T> ret; const T invWidth = 1 / (right - left); const T invHeight = 1 / (top - bottom); const T invDepth = 1 / (zFar - zNear); const T twoZNear = 2 * zNear; ret.identity(); ret.cel[0][0] = twoZNear * invWidth; ret.cel[1][1] = twoZNear * invHeight; ret.cel[2][0] = (right + left) * invWidth; ret.cel[2][1] = (top + bottom) * invHeight; ret.cel[2][2] = -(zFar + zNear) * invDepth; ret.cel[2][3] = -1; ret.cel[3][2] = -twoZNear * zFar * invDepth; return ret; } /** * Creates perspective projection. * @param fovy The degree angle of view, such the open angle of the eye * @param aspect The aspect ratio of view width and height, usually us screen aspect ratio * @param zNear Specify the distance to the near clipping plane. Distance must be positive * @param zFar Specify the distance to the far depth clipping plane. Distance must be positive * @return Projection matrix for specified frustum */ static Matrix4<T> createPerspective(T fovy, T aspect, T zNear, T zFar) { T k = tan(DEG2RAD(fovy) / 2); T r = zNear * k * aspect; T t = zNear * k; return createFrustum(-r, r, -t, t, zNear, zFar); } /** * Creates OpenGL compatible orthographic projection matrix. * @param left Specify the coordinate for the left vertical clipping plane, * @param right Specify the coordinate for the right vertical clipping plane. * @param bottom Specify the coordinate for the bottom horizontal clipping plane, * @param top Specify the coordinate for the top horizontal clipping plane. * @param zNear Specify the distance to the nearer depth clipping plane. * This value is negative if the plane is to be behind the viewer, * @param zFar Specify the distance to the farther depth clipping plane. * This value is negative if the plane is to be behind the viewer. * @return Othrographic projection matrix. */ static Matrix4<T> createOrtho(T left, T right, T bottom, T top, T zNear, T zFar) { /* |--------------------------------------------------------------| | 2 | | ------------ 0 0 0 | | right - left | | | | 2 | | 0 ------------ 0 0 | | top - bottom | | | | -2 | | 0 0 ------------ 0 | | zFar-zNear | | | | tx ty tz 1 | |--------------------------------------------------------------| tx = - (right + left) / (right - left) ty = - (top + bottom) / (top - bottom) tz = - (zFar + zNear) / (zFar - zNear) */ const T invWidth = 1 / (right - left); const T invHeight = 1 / (top - bottom); const T invDepth = 1 / (zFar - zNear); Matrix4<T> ret; ret.identity(); ret.cel[0][0] = 2 * invWidth; ret.cel[1][1] = 2 * invHeight; ret.cel[2][2] = -2 * invDepth; ret.cel[3][0] = -(right + left) * invWidth; ret.cel[3][1] = -(top + bottom) * invHeight; ret.cel[3][2] = -(zFar + zNear) * invDepth; return ret; } /** * Creates new matrix 4x4 from a array in row major order. * @param arr An array of elements for 4x4 matrix in row major order. * @return An instance of Matrix4<T> representing @a arr */ template<class FromT> static Matrix4<T> fromRowMajorArray(const FromT* arr) { const T retData[] = { static_cast<T>(arr[0]), static_cast<T>(arr[4]), static_cast<T>(arr[8]), static_cast<T>(arr[12]), static_cast<T>(arr[1]), static_cast<T>(arr[5]), static_cast<T>(arr[9]), static_cast<T>(arr[13]), static_cast<T>(arr[2]), static_cast<T>(arr[6]), static_cast<T>(arr[10]), static_cast<T>(arr[14]), static_cast<T>(arr[3]), static_cast<T>(arr[7]), static_cast<T>(arr[11]), static_cast<T>(arr[15]) }; return retData; } /** * Creates new matrix 4x4 from a array in column major order. * @param arr An array of elements for 4x4 matrix in column major order. * @return An instance of Matrix4<T> representing @a arr */ template<class FromT> static Matrix4<T> fromColumnMajorArray(const FromT* arr) { const T retData[] = { static_cast<T>(arr[0]), static_cast<T>(arr[1]), static_cast<T>(arr[2]), static_cast<T>(arr[3]), static_cast<T>(arr[4]), static_cast<T>(arr[5]), static_cast<T>(arr[6]), static_cast<T>(arr[7]), static_cast<T>(arr[8]), static_cast<T>(arr[9]), static_cast<T>(arr[10]), static_cast<T>(arr[11]), static_cast<T>(arr[12]), static_cast<T>(arr[13]), static_cast<T>(arr[14]), static_cast<T>(arr[15]) }; return retData; } /** * Equal operator * @param rhs right side matirx. * @return true if all data[i] equal with rhs.data[i] * @note Test of equality is based of equal function. */ bool operator==(const Matrix4<T>& rhs) const { for (int i = 0; i < 16; i++) { if (! equal(data[i], rhs.data[i])) return false; } return true; } /** * Not equal operator * @param rhs right side matirx. * @return not (lhs == rhs) :-P */ bool operator!=(const Matrix4<T>& rhs) const { return !(*this == rhs); } /** * Operator for add with a scalar * @param rhs Right side scalar. */ Matrix4<T> operator+(T rhs) const { Matrix4<T> ret; for (int i = 0; i < 16; i++) ret.data[i] = data[i] + rhs; return ret; } /** * Operator for add with a matrix * @param rhs Right side matrix. */ Matrix4<T> operator+(const Matrix4<T>& rhs) const { Matrix4<T> ret; for (int i = 0; i < 16; i++) ret.data[i] = data[i] + rhs.data[i]; return ret; } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Matrix4<T> operator-(T rhs) const { Matrix4<T> ret; for (int i = 0; i < 16; i++) ret.data[i] = data[i] - rhs; return ret; } /** * Operator for subtract with a matrix * @param rhs Right side matrix. */ Matrix4<T> operator-(const Matrix4<T>& rhs) const { Matrix4<T> ret; for (int i = 0; i < 16; i++) ret.data[i] = data[i] - rhs.data[i]; return ret; } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Matrix4<T> operator*(T rhs) const { Matrix4<T> ret; for (int i = 0; i < 16; i++) ret.data[i] = data[i] * rhs; return ret; } /** * Operator for divide with a scalar * @param rhs Right side scalar. */ Matrix4<T> operator/(T rhs) const { Matrix4<T> ret; for (int i = 0; i < 16; i++) ret.data[i] = data[i] / rhs; return ret; } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector3<T> operator*(const Vector3<T>& rhs) const { Vector4<T> ret = operator*(Vector4<T>(rhs, 1)); return ret.xyz / ret.w; } /** * Operator for multiply with a vector * @param rhs Right side vector. */ Vector4<T> operator*(const Vector4<T>& rhs) const { return Vector4<T>(data[0] * rhs.x + data[4] * rhs.y + data[8] * rhs.z + data[12] * rhs.w, data[1] * rhs.x + data[5] * rhs.y + data[9] * rhs.z + data[13] * rhs.w, data[2] * rhs.x + data[6] * rhs.y + data[10] * rhs.z + data[14] * rhs.w, data[3] * rhs.x + data[7] * rhs.y + data[11] * rhs.z + data[15] * rhs.w); } /** * Operator for multiply with a matrix * @param rhs Right side matrix. */ Matrix4<T> operator*(Matrix4<T> rhs) const { Matrix4<T> w; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { T n = 0; for (int k = 0; k < 4; k++) n += rhs.cel[i][k] * cel[k][j]; w.cel[i][j] = n; } } return w; } /** * Sets translation part of matrix. * * @param v Vector of translation to be set. */ void setTranslation(const Vector3<T>& v) { cel[3][0] = v.x; cel[3][1] = v.y; cel[3][2] = v.z; cel[3][3] = 1; } /** * Get translation part of matrix. */ Vector3<T> getTranslation() const { return row[3].xyz; } /** * Sets rotation part (matrix 3x3) of matrix. * * @param m Rotation part of matrix */ void setRotation(const Matrix3<T>& m) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cel[i][j] = m.cel[i][j]; } } } /** * Sets matrix uniform scale values * @param s Uniform scale value */ void setScale(T s) { cel[0][0] = cel[1][1] = cel[2][2] = s; } /** * Sets matrix scale for all axises. * @param sx X-axis scale factor * @param sy Y-axis scale factor * @param sz Z-axis scale factor */ void setScale(T sx, T sy, T sz) { cel[0][0] = sx; cel[1][1] = sy; cel[2][2] = sz; } /** * Sets matrix scale for all axes. * @param s Scale factors for X, Y, and Z coordinate. */ void setScale(const Vector3<T>& s) { cel[0][0] = s.x; cel[1][1] = s.y; cel[2][2] = s.z; } /** * Gets matrix scale * @return Scales (i.e. first three values from matrix diagonal. */ Vector3<T> getScale() const { return Vector3<T>(cel[0][0], cel[1][1], cel[2][2]); } /** * Transpose matrix. */ Matrix4<T> transpose() { Matrix4<T> ret; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { ret.cel[i][j] = cel[j][i]; } } return ret; } /** * Get determinant of matrix * @return Determinant of matrix. */ T det() { float a0 = data[0] * data[5] - data[1] * data[4]; float a1 = data[0] * data[6] - data[2] * data[4]; float a2 = data[0] * data[7] - data[3] * data[4]; float a3 = data[1] * data[6] - data[2] * data[5]; float a4 = data[1] * data[7] - data[3] * data[5]; float a5 = data[2] * data[7] - data[3] * data[6]; float b0 = data[8] * data[13] - data[9] * data[12]; float b1 = data[8] * data[14] - data[10] * data[12]; float b2 = data[8] * data[15] - data[11] * data[12]; float b3 = data[9] * data[14] - data[10] * data[13]; float b4 = data[9] * data[15] - data[11] * data[13]; float b5 = data[10] * data[15] - data[11] * data[14]; // Calculate the determinant. return (a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0); } bool decompose(Vector3<T>* scale, Quaternion<T>* rotation, Vector3<T>* translation) const { if (translation) { // Extract the translation. translation->x = data[12]; translation->y = data[13]; translation->z = data[14]; } // Nothing left to do. if (scale == NULL && rotation == NULL) return true; // Extract the scale. // This is simply the length of each axis (row/column) in the matrix. Vector3<T> xaxis(data[0], data[1], data[2]); T scaleX = xaxis.length(); Vector3<T> yaxis(data[4], data[5], data[6]); T scaleY = yaxis.length(); Vector3<T> zaxis(data[8], data[9], data[10]); T scaleZ = zaxis.length(); // Determine if we have a negative scale (true if determinant is less than zero). // In this case, we simply negate a single axis of the scale. T det = det(); if (det < 0) scaleZ = -scaleZ; if (scale) { scale->x = scaleX; scale->y = scaleY; scale->z = scaleZ; } // Nothing left to do. if (rotation == NULL) return true; // Scale too close to zero, can't decompose rotation. if (scaleX < MATH_TOLERANCE || scaleY < MATH_TOLERANCE || abs(scaleZ) < MATH_TOLERANCE) return false; T rn; // Factor the scale out of the matrix axes. rn = (T)1 / scaleX; xaxis.x *= rn; xaxis.y *= rn; xaxis.z *= rn; rn = (T)1 / scaleY; yaxis.x *= rn; yaxis.y *= rn; yaxis.z *= rn; rn = (T)1 / scaleZ; zaxis.x *= rn; zaxis.y *= rn; zaxis.z *= rn; // Now calculate the rotation from the resulting matrix (axes). T trace = xaxis.x + yaxis.y + zaxis.z + 1.0f; if (trace > FLT_EPSILON) { T s = (T)0.5 / sqrt(trace); rotation->w = (T)0.25 / s; rotation->x = (yaxis.z - zaxis.y) * s; rotation->y = (zaxis.x - xaxis.z) * s; rotation->z = (xaxis.y - yaxis.x) * s; } else { // Note: since xaxis, yaxis, and zaxis are normalized, // we will never divide by zero in the code below. if (xaxis.x > yaxis.y && xaxis.x > zaxis.z) { T s = (T)0.5 / sqrt((T)1 + xaxis.x - yaxis.y - zaxis.z); rotation->w = (yaxis.z - zaxis.y) * s; rotation->x = (T)0.25 / s; rotation->y = (yaxis.x + xaxis.y) * s; rotation->z = (zaxis.x + xaxis.z) * s; } else if (yaxis.y > zaxis.z) { T s = (T)0.5 / sqrt((T)1 + yaxis.y - xaxis.x - zaxis.z); rotation->w = (zaxis.x - xaxis.z) * s; rotation->x = (yaxis.x + xaxis.y) * s; rotation->y = (T)0.25 / s; rotation->z = (zaxis.y + yaxis.z) * s; } else { T s = (T)0.5 / sqrt((T)1 + zaxis.z - xaxis.x - yaxis.y); rotation->w = (xaxis.y - yaxis.x) * s; rotation->x = (zaxis.x + xaxis.z) * s; rotation->y = (zaxis.y + yaxis.z) * s; rotation->z = (T)0.25 / s; } } return true; } /** * Get inverse matrix * @return Inverse matrix of this matrix. */ bool inverse() { T a0 = data[0] * data[5] - data[1] * data[4]; T a1 = data[0] * data[6] - data[2] * data[4]; T a2 = data[0] * data[7] - data[3] * data[4]; T a3 = data[1] * data[6] - data[2] * data[5]; T a4 = data[1] * data[7] - data[3] * data[5]; T a5 = data[2] * data[7] - data[3] * data[6]; T b0 = data[8] * data[13] - data[9] * data[12]; T b1 = data[8] * data[14] - data[10] * data[12]; T b2 = data[8] * data[15] - data[11] * data[12]; T b3 = data[9] * data[14] - data[10] * data[13]; T b4 = data[9] * data[15] - data[11] * data[13]; T b5 = data[10] * data[15] - data[11] * data[14]; // Calculate the determinant. T det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; // Close to zero, can't invert. if (abs(det) <= MATH_TOLERANCE) return false; // Support the case where m == dst. Matrix4<T> inverse; inverse.data[0] = data[5] * b5 - data[6] * b4 + data[7] * b3; inverse.data[1] = -data[1] * b5 + data[2] * b4 - data[3] * b3; inverse.data[2] = data[13] * a5 - data[14] * a4 + data[15] * a3; inverse.data[3] = -data[9] * a5 + data[10] * a4 - data[11] * a3; inverse.data[4] = -data[4] * b5 + data[6] * b2 - data[7] * b1; inverse.data[5] = data[0] * b5 - data[2] * b2 + data[3] * b1; inverse.data[6] = -data[12] * a5 + data[14] * a2 - data[15] * a1; inverse.data[7] = data[8] * a5 - data[10] * a2 + data[11] * a1; inverse.data[8] = data[4] * b4 - data[5] * b2 + data[7] * b0; inverse.data[9] = -data[0] * b4 + data[1] * b2 - data[3] * b0; inverse.data[10] = data[12] * a4 - data[13] * a2 + data[15] * a0; inverse.data[11] = -data[8] * a4 + data[9] * a2 - data[11] * a0; inverse.data[12] = -data[4] * b3 + data[5] * b1 - data[6] * b0; inverse.data[13] = data[0] * b3 - data[1] * b1 + data[2] * b0; inverse.data[14] = -data[12] * a3 + data[13] * a1 - data[14] * a0; inverse.data[15] = data[8] * a3 - data[9] * a1 + data[10] * a0; *this = inverse * (1 / det); return true; } /** * Conversion to pointer * @return Data pointer */ operator T*() { return (T*)data; } /** * Conversion to pointer * @return Constant Data pointer */ operator const T*() const { return (const T*)data; } /** * Output to stream operator */ friend std::ostream& operator <<(std::ostream& lhs, const Matrix4<T>& rhs) { lhs << rhs.toString(); return lhs; } /** * To string operator. */ std::string toString() const { char buffer[16 * 4 * 4]; sprintf(buffer, "\n\t\t|%f,%f,%f,%f|\n" "\t\t|%f,%f,%f,%f|\n" "\t\t|%f,%f,%f,%f|\n" "\t\t|%f,%f,%f,%f|\n", data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]); return buffer; } }; typedef Matrix4<float> mat4f; typedef Matrix4<double> mat4r; /** * Quaternion class */ template<class T> class Quaternion { public: /** * Imaginary part of quaternion. */ union { struct { T x; T y; T z; }; Vector3<T> v; }; /** * Real part of quaternion. */ T w; public: /** * Quaternion constructor, sets quaternion to (0 + 0i + 0j + 0k). */ Quaternion() : w(1), x(0), y(0), z(0) { } /** * Copy constructor. */ Quaternion(const Quaternion<T>& q) : w(q.w), x(q.x), y(q.y), z(q.z) { } /** * Copy casting constructor. */ template<class FromT> Quaternion(const Quaternion<FromT>& q) : w(static_cast<T>(q.w)), v(q.v) { } /** * Quaternion constructor * @param w_ Real part of quaternion. * @param v_ Complex part of quaternion (xi + yj + zk). */ Quaternion(T w_, const Vector3<T>& v_) : w(w_), v(v_) { } /** * Quaternion constructor * @param w_ Real part of quaternion. * @param x_ Complex coefficient for i complex constant. * @param y_ Complex coefficient for j complex constant. * @param z_ Complex coefficient for k complex constant. */ Quaternion(T w_, T x_, T y_, T z_) : w(w_), x(x_), y(y_), z(z_) { } /** * Copy operator * @param rhs Right side quaternion. */ Quaternion<T>& operator=(const Quaternion<T>& rhs) { w = rhs.w; x = rhs.x; y = rhs.y; z = rhs.z; return *this; } /** * Copy convert operator * @param rhs Right side quaternion. */ template<class FromT> Quaternion<T>& operator=(const Quaternion<FromT>& rhs) { w = static_cast<T>(rhs.w); v = rhs.v; return *this; } /** * Get negate quaternion */ Quaternion<T> operator-() const { return Quaternion<T>(-w, -x, -y, -z); } /** * Get conjugate quaternion */ Quaternion<T> operator~() const { return Quaternion<T>(w, -x, -y, -z); } /** * Operator for add with a quaternion * @param rhs Right side quaternion. */ Quaternion<T> operator+(const Quaternion<T>& rhs) const { const Quaternion<T>& lhs = *this; return Quaternion<T>(lhs.w + rhs.w, lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z); } /** * Operator for add with a quaternion * @param rhs Right side quaternion. */ Quaternion<T>& operator+=(const Quaternion<T>& rhs) { w += rhs.w; x += rhs.x; y += rhs.y; z += rhs.z; return *this; } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Quaternion<T> operator-(const Quaternion<T>& rhs) const { const Quaternion<T>& lhs = *this; return Quaternion<T>(lhs.w - rhs.w, lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z); } /** * Operator for subtract with a scalar * @param rhs Right side scalar. */ Quaternion<T>& operator-=(const Quaternion<T>& rhs) { w -= rhs.w; x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } /** * Operator for multiply with a quaternion * @param rhs Right side quaternion. */ Quaternion<T> operator*(const Quaternion<T>& rhs) const { const Quaternion<T>& lhs = *this; return Quaternion<T>(lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z, lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y, lhs.w * rhs.y - lhs.x * rhs.z + lhs.y * rhs.w + lhs.z * rhs.x, lhs.w * rhs.z + lhs.x * rhs.y - lhs.y * rhs.x + lhs.z * rhs.w); } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Quaternion<T> operator*(T rhs) const { return Quaternion<T>(w * rhs, x * rhs, y * rhs, z * rhs); } /** * Transform a vector3 * @param v The vector */ Vector3<T> operator*(Vector3<T> v) const { Vector3<T> uv = cross(this->v, v); Vector3<T> uuv = cross(this->v, uv); uv *= (2 * w); uuv *= 2; return v + uv + uuv; } /** * Operator for multiply with a quaternion * @param rhs Right side quaternion. */ Quaternion<T>& operator*=(const Quaternion<T>& rhs) { Quaternion q = (*this) * rhs; w = q.w; x = q.x; y = q.y; z = q.z; return *this; } /** * Operator for multiply with a scalar * @param rhs Right side scalar. */ Quaternion<T>& operator*=(T rhs) { w *= rhs; x *= rhs; y *= rhs; z *= rhs; return *this; } /** * Equal test operator * @param rhs Right side vector. * @note Test of equality is based of equal fun. */ bool operator==(const Quaternion<T>& rhs) const { const Quaternion<T>& lhs = *this; return (equal(lhs.w, rhs.w)) && lhs.v == rhs.v; } /** * Not equal operator * @param rhs right side matirx. * @return not (lhs == rhs) :-P */ bool operator!=(const Quaternion<T>& rhs) const { return !(*this == rhs); } /** * Get lenght of quaternion. */ T length() const { return (T)sqrt(lengthSq()); } /** * Return square of length. * @return length ^ 2 */ T lengthSq() const { return w * w + x * x + y * y + z * z; } /** * Normalize quaternion */ void normalize() { T len = length(); w /= len; x /= len; y /= len; z /= len; } /** * Creates quaternion for eulers angles. * @param x Rotation around x axis (in degrees). * @param y Rotation around y axis (in degrees). * @param z Rotation around z axis (in degrees). */ static Quaternion<T> fromEulerAngles(T x, T y, T z) { Quaternion<T> ret = fromAxisRot(Vector3<T>(1, 0, 0), x) * fromAxisRot(Vector3<T>(0, 1, 0), y) * fromAxisRot(Vector3<T>(0, 0, 1), z); return ret; } /** * Creates quaternion as rotation around axis. * @param axis Unit vector expressing axis of rotation. * @param angleDeg Angle of rotation around axis (in degrees). */ static Quaternion<T> fromAxisRot(Vector3<T> axis, T angleDeg) { T angleRad = (T)DEG2RAD(angleDeg); T sa2, ca2; sincos(angleRad / 2, &sa2, &ca2); return Quaternion<T>(ca2, axis * sa2); } /** * Get the quaternion can transform 'from' vector to 'to' vertor */ static Quaternion<T> fromTwoVectors(const Vector3<T>& from, const Vector3<T>& to) { T cosTheta = dot(from, to); Vector3<T> rotationAxis; if (cosTheta >= static_cast<T>(1) - FLT_EPSILON) { // orig and dest point in the same direction return Quaternion<T>(); } if (cosTheta < static_cast<T>(-1) + FLT_EPSILON) { // special case when vectors in opposite directions : // there is no "ideal" rotation axis // So guess one; any will do as long as it's perpendicular to start // This implementation favors a rotation around the Up axis (Y), // since it's often what you want to do. rotationAxis = cross(Vector3<T>(0, 0, 1), from); if (rotationAxis.lengthSq() < FLT_EPSILON) // bad luck, they were parallel, try again! rotationAxis = cross(Vector3<T>(1, 0, 0), from); rotationAxis.normalize(); return Quaternion<T>::fromAxisRot(rotationAxis, M_PI); } // Implementation from Stan Melax's Game Programming Gems 1 article rotationAxis = cross(from, to); T s = sqrt((T(1) + cosTheta) * static_cast<T>(2)); T invs = static_cast<T>(1) / s; return Quaternion<T>( s * static_cast<T>(0.5f), rotationAxis.x * invs, rotationAxis.y * invs, rotationAxis.z * invs); } /** * Converts quaternion into rotation matrix. * @return Rotation matrix expressing this quaternion. */ Matrix3<T> rotMatrix() { Matrix3<T> ret; T xx = x * x; T xy = x * y; T xz = x * z; T xw = x * w; T yy = y * y; T yz = y * z; T yw = y * w; T zz = z * z; T zw = z * w; ret.cel[0][0] = 1 - 2 * (yy + zz); ret.cel[1][0] = 2 * (xy - zw); ret.cel[2][0] = 2 * (xz + yw); ret.cel[0][1] = 2 * (xy + zw); ret.cel[1][1] = 1 - 2 * (xx + zz); ret.cel[2][1] = 2 * (yz - xw); ret.cel[0][2] = 2 * (xz - yw); ret.cel[1][2] = 2 * (yz + xw); ret.cel[2][2] = 1 - 2 * (xx + yy); return ret; } /** * Converts quaternion into transformation matrix. * @note This method performs same operation as rotMatrix() * conversion method. But returns Matrix of 4x4 elements. * @return Transformation matrix expressing this quaternion. */ Matrix4<T> transform() const { Matrix4<T> ret; T xx = x * x; T xy = x * y; T xz = x * z; T xw = x * w; T yy = y * y; T yz = y * z; T yw = y * w; T zz = z * z; T zw = z * w; ret.cel[0][0] = 1 - 2 * (yy + zz); ret.cel[1][0] = 2 * (xy - zw); ret.cel[2][0] = 2 * (xz + yw); ret.cel[3][0] = 0; ret.cel[0][1] = 2 * (xy + zw); ret.cel[1][1] = 1 - 2 * (xx + zz); ret.cel[2][1] = 2 * (yz - xw); ret.cel[3][1] = 0; ret.cel[0][2] = 2 * (xz - yw); ret.cel[1][2] = 2 * (yz + xw); ret.cel[2][2] = 1 - 2 * (xx + yy); ret.cel[3][2] = 0; ret.cel[0][3] = 0; ret.cel[1][3] = 0; ret.cel[2][3] = 0; ret.cel[3][3] = 1; return ret; } /** * Output to stream operator */ friend std::ostream& operator <<(std::ostream& oss, const Quaternion<T>& q) { oss << q.toString(); return oss; } /** * To string operator. */ std::string toString() const { char buffer[64]; sprintf(buffer, "%f,%f,%f,%f", w, x, y, z); return buffer; } /** * Creates quaternion from transform matrix. * * @param m Transform matrix used to compute quaternion. * @return Quaternion representing rotation of matrix m. */ static Quaternion<T> fromMatrix(const Matrix4<T>& m) { Quaternion<T> q; T tr, s; tr = m.cel[1][1] + m.cel[2][2] + m.cel[3][3]; if (! less((T)0, tr)) { s = (T)0.5 / (T)sqrt(tr + (T)1.0); q.w = (T)0.25 / s; q.x = (m.cel[3][2] - m.cel[2][3]) * s; q.y = (m.cel[1][3] - m.cel[3][1]) * s; q.z = (m.cel[2][1] - m.cel[1][2]) * s; } else { T d0 = m.cel[1][1]; T d1 = m.cel[2][2]; T d2 = m.cel[3][3]; char bigIdx = (d0 > d1) ? ((d0 > d2) ? 0 : 2) : ((d1 > d2) ? 1 : 2); if (bigIdx == 0) { s = (T)2.0 * (T)sqrt((T)1.0 + m.cel[1][1] - m.cel[2][2] - m.cel[3][3]); q.w = (m.cel[3][2] - m.cel[2][3]) / s; q.x = (T)0.25 * s; q.y = (m.cel[1][2] + m.cel[2][1]) / s; q.z = (m.cel[1][3] + m.cel[3][1]) / s; } else if (bigIdx == 1) { s = (T)2.0 * (T)sqrt((T)1.0 + m.cel[2][2] - m.cel[1][1] - m.cel[3][3]); q.w = (m.cel[1][3] - m.cel[3][1]) / s; q.x = (m.cel[1][2] + m.cel[2][1]) / s; q.y = (T)0.25 * s; q.z = (m.cel[2][3] + m.cel[3][2]) / s; } else { s = (T)2.0 * (T)sqrt(1.0 + m.cel[3][3] - m.cel[1][1] - m.cel[2][2]); q.w = (m.cel[2][1] - m.cel[1][2]) / s; q.x = (m.cel[1][3] + m.cel[3][1]) / s; q.y = (m.cel[2][3] + m.cel[3][2]) / s; q.z = (T)0.25 * s; } } return q; } /** * Creates quaternion from rotation matrix. * * @param m Rotation matrix used to compute quaternion. * @return Quaternion representing rotation of matrix m. */ static Quaternion<T> fromMatrix(const Matrix3<T>& m) { Quaternion<T> q; T tr, s; tr = m.cel[1][1] + m.cel[2][2] + m.cel[3][3]; if (!less((T)0, tr)) { s = (T)0.5 / (T)sqrt(tr + (T)1.0); q.w = (T)0.25 / s; q.x = (m.cel[3][2] - m.cel[2][3]) * s; q.y = (m.cel[1][3] - m.cel[3][1]) * s; q.z = (m.cel[2][1] - m.cel[1][2]) * s; } else { T d0 = m.cel[1][1]; T d1 = m.cel[2][2]; T d2 = m.cel[3][3]; char bigIdx = (d0 > d1) ? ((d0 > d2) ? 0 : 2) : ((d1 > d2) ? 1 : 2); if (bigIdx == 0) { s = (T)2.0 * (T)sqrt((T)1.0 + m.cel[1][1] - m.cel[2][2] - m.cel[3][3]); q.w = (m.cel[3][2] - m.cel[2][3]) / s; q.x = (T)0.25 * s; q.y = (m.cel[1][2] + m.cel[2][1]) / s; q.z = (m.cel[1][3] + m.cel[3][1]) / s; } else if (bigIdx == 1) { s = (T)2.0 * (T)sqrt((T)1.0 + m.cel[2][2] - m.cel[1][1] - m.cel[3][3]); q.w = (m.cel[1][3] - m.cel[3][1]) / s; q.x = (m.cel[1][2] + m.cel[2][1]) / s; q.y = (T)0.25 * s; q.z = (m.cel[2][3] + m.cel[3][2]) / s; } else { s = (T)2.0 * (T)sqrt(1.0 + m.cel[3][3] - m.cel[1][1] - m.cel[2][2]); q.w = (m.cel[2][1] - m.cel[1][2]) / s; q.x = (m.cel[1][3] + m.cel[3][1]) / s; q.y = (m.cel[2][3] + m.cel[3][2]) / s; q.z = (T)0.25 * s; } } return q; } /** * Get the angle */ T angle() const { return acos(this->w) * static_cast<T>(2); } /** * Get the rotate axis */ Vector3<T> axis() const { T tmp1 = static_cast<T>(1) - w * w; if (tmp1 <= static_cast<T>(0)) return Vector3<T>(0, 0, 1); T tmp2 = static_cast<T>(1) / sqrt(tmp1); return Vector3<T>(x * tmp2, y * tmp2, z * tmp2); } /** * Linear interpolation of two quaternions * @param fact Factor of interpolation. For translation from position * of this vector to quaternion rhs, values of factor goes from 0.0 to 1.0. * @param q1 First Quaternion for interpolation * @param q2 Second Quaternion for interpolation */ Quaternion<T> lerp(const Quaternion<T>& q1, const Quaternion<T>& q2, T fact) { return Quaternion<T>((1 - fact) * q1.w + fact * q2.w, Vector3<T>::lerp(q1.v, q2.v, fact)); } /** * Computes spherical interpolation between quaternions (q1, q2) * using coefficient of interpolation r (in [0, 1]). * @param q1 First quaternion for interpolation. * @param q2 Second quaternion for interpolation. * @param r The ratio of interpolation form q1 (r = 0) to q2 (r = 1). * @return Result of interpolation. */ static Quaternion<T> slerp(const Quaternion<T>& q1, const Quaternion<T>& q2, T r) { Quaternion<T> ret; T cosTheta = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z; T theta = acos(cosTheta); if (equal(theta, (T)0)) { ret = q1; } else { T sinTheta = sqrt((T)1 - cosTheta * cosTheta); if (equal(sinTheta, (T)0)) { ret.w = (T)0.5 * q1.w + (T)0.5 * q2.w; ret.v = Vector3<T>::lerp(q1.v, q2.v, (T)0.5); } else { T rA = sin(((T)1.0 - r) * theta) / sinTheta; T rB = sin(r * theta) / sinTheta; ret.w = q1.w * rA + q2.w * rB; ret.x = q1.x * rA + q2.x * rB; ret.y = q1.y * rA + q2.y * rB; ret.z = q1.z * rA + q2.z * rB; } } return ret; } }; typedef Quaternion<float> quatf; typedef Quaternion<double> quatr; /** * Axes-aligned bounding-box (aka AABB) class. */ template <typename T> class Aabb2 { public: /** * Position of Min corner of bounding box. */ Vector2<T> min; /** * Position of Max corner of bounding box */ Vector2<T> max; public: /** * Constructs invalid axes-aligned bounding-box. * @see valid() for explanation of invalid bounding-box usage. */ Aabb2() : min(1, 1), max(-1, -1) { } /** * Constructs axes-aligned bound-box containing one point @a point * @param point */ template <typename SrcT> Aabb2(const Vector2<SrcT>& point) : min(point), max(point) { } /** * Constructs axes-aligned bounding-box form two corner points (@a x0, @a y0) * and (@a x1, @a y1) * @param x0 X-coordinate of first point * @param y0 Y-coordinate of first point * @param x1 X-coordinate of second point * @param y1 Y-coordinate of second point */ template <typename SrcT> Aabb2(SrcT x0, SrcT y0, SrcT x1, SrcT y1) : min(MIN(x0, x1), MIN(y0, y1)), max(MAX(x0, x1), MAX(y0, y1)) { } /** * Constructs axes-aligned bounding-box containing point (@a x, @a y) * @param x X-coordinate of point * @param y Y-coordinate of point */ template <typename SrcT> Aabb2(SrcT x, SrcT y) : min(x, y), max(x, y) { } /** * Creates copy of axis-aligned bounding-box * @param src Source bounding-box */ template <typename SrcT> Aabb2(const Aabb2<SrcT>& src) : min(src.min), max(src.max) { } /** * Assign operator * @param rhs source bounding-box * @return refenrence to this */ template <typename SrcT> Aabb2<T>& operator=(const Aabb2<SrcT>& rhs) { min = rhs.min; max = rhs.max; return *this; } /** * Checks if bounding-box is valid. Valid bounding-box has non-negative size. * If an invalid bounding-box is extended by point or another bounding-box, the target * bounding box becomes valid and contains solely the source point or bounding-box respectively. * @return True if box is valid, otherwise false */ bool valid() const { return min.x <= max.x && min.y <= max.y; } /** * Makes this bounding-box invalid. So calling valid() gets false. * @see valid() method for more info on usage of invalid bounding-boxes. */ void invalidate() { min = Vector2<T>(1, 1); max = Vector2<T>(-1, -1); } /** * Extends this bounding-box by a point @a point. * @param point A point to extend bounding-box by. */ template <typename SrcT> void extend(const Vector2<SrcT>& point) { if (!valid()) { min = max = point; } else { min = Vector2<T>::min(min, point); max = Vector2<T>::max(max, point); } } /** * Extends this bounding-box by a box @a box. * @param box A box to extend this bounding-box by. */ template <typename SrcT> void extend(const Aabb2<SrcT>& box) { if (!valid()) { min = box.min; max = box.max; } else { min = Vector2<T>::min(min, box.min); max = Vector2<T>::max(max, box.max); } } /** * Gets a copy of this bounding-box extend by a point @a point. * @param point A point to extend the box by * @return Copy of extended bounding-box */ template <typename SrcT> Aabb2<T> extended(const Vector2<SrcT>& point) const { Aabb2<T> ret(*this); ret.extend(point); return ret; } /** * Gets a copy of this bounding-box extnended by box @a box. * @param box A box to extend the copy be. * @return Copy of extended bounding-box */ template <typename SrcT> Aabb2<T> extended(const Aabb2<SrcT>& box) const { Aabb2<T> ret(*this); ret.extend(box); return ret; } /** * Tests if the point @a point is within this bounding-box * @param point A point to be tested * @return True if point @a point lies within bounding-box, otherwise false. */ template <typename SrcT> bool intersects(const Vector2<SrcT>& point) const { if (min.x > point.x || min.y > point.y || point.x > max.x || point.y > max.y) return false; return true; } /** * Tests if other bounding-box @a box intersects (even partially) with this bouding-box. * @param box A box to be tested for intersection. * @return True if there's intersection between boxes, otherwise false. */ template <typename SrcT> bool intersects(const Aabb2<SrcT>& box) const { if (min.x > box.max.x || min.y > box.max.y || max.x < box.min.x || max.y < box.min.y) return false; return true; } /** * Gets result of intersection of this bounding-box with @a other bounding-box. * In case the boxes don't intersect, the returned bounding-box is invalid. * @param other Box to be tested * @return Result of intersection. * @see valid() method for more information on invalid bounding-boxes. */ template <typename SrcT> Aabb2<T> intersection(const Aabb2<SrcT>& other) const { Aabb2<T> ret; if (min.x > other.max.x || min.y > other.max.y || max.x < other.min.x || max.y < other.min.y) return ret; ret.min = Vector2<T>::max(min, other.min); ret.max = Vector2<T>::min(max, other.max); return ret; } /** * Gets center point of bounding-box. * @return A center point of bounding-box. */ Vector2<T> center() const { return (min + max) / 2; } /** * Gets extent of bounding-box. * @return Extent of bounding-box. */ Vector2<T> extent() const { return (max - min) / 2; } /** * Gets diagonal size of bounding-box * @return Sizes for particular dimensions. */ Vector2<T> size() const { return max - min; } /** * Gets all 8 corner-points of bounding box * @param i An index of bounding-box corner point. Valid values are 0 .. 7. * @return A position of @a i-th corner-point. * @note The order of points is as follows (where @c + denotes max-point and @c - min-point): * 1. (@c + @c +) * 2. (@c - @c +) * 3. (@c + @c -) * 4. (@c - @c -) */ Vector2<T> point(size_t i) const { ASSERT(i < 4); return Vector2<T>(i & 1 ? min.x : max.x, i & 2 ? min.y : max.y); } /** * Tests if @a rhs is equal to this bounding-box * @param rhs Right-hand side * @return True if @a rhs and this bounding-boxes are equal, otherwise false */ template <typename RhsT> bool operator==(const Aabb2<RhsT>& rhs) const { return min == rhs.min && max == rhs.max; } /** * Tests if @a rhs is not equal to this bounding-box * @param rhs Right-hand side * @return True if @a rhs and this bounding-boxes are not equal, otherwise false */ template <typename RhsT> bool operator!=(const Aabb2<RhsT>& rhs) const { return min != rhs.min || max != rhs.max; } /** * Extends this bounding-box by point @a rhs. * @param rhs A point to extend this bounding-box by * @return Reference to this */ template <typename SrcT> Aabb2<T>& operator<<(const Vector2<SrcT>& rhs) { extend(rhs); return *this; } /** * Extends this bounding-box by box @a rhs. * @param rhs A box to extend this bounding-box by * @return Reference to this */ template <typename SrcT> Aabb2<T>& operator<<(const Aabb2<SrcT>& rhs) { extend(rhs); return *this; } /** * Union of this and @a rhs bounding-boxes * @param rhs Right-hand side of union * @return A resulting bounding-box representing union */ template <typename RhsT> Aabb2<T> operator|(const Aabb2<RhsT>& rhs) const { return extended(rhs); } /** * Intersection of this and @a rhs bounding-boxed * @param rhs Right-hand side * @return Resulting bouding-box representing the intersection. */ template <typename RhsT> Aabb2<T> operator&(const Aabb2<RhsT>& rhs) const { return intersection(rhs); } /** * Outputs string representation of bounding-box @a rhs to output stream @a lhs * @param lhs Output stream to write to * @param rhs Bounding-box to write to output stream. * @return Reference to output stream @a lhs */ friend std::ostream& operator<<(std::ostream& lhs, const Aabb2<T>& rhs) { lhs << rhs.toString(); return lhs; } /** * To string operator. */ std::string toString() const { char buffer[64]; sprintf(buffer, "%f,%f,%f,%f", min.x, min.y, max.x, max.y); return buffer; } }; typedef Aabb2<int> aabb2i; typedef Aabb2<float> aabb2f; typedef Aabb2<double> aabb2r; /** * Axes-aligned bounding-box (aka AABB) class. */ template <typename T> class Aabb3 { public: /** * Position of Min corner of bounding box. */ Vector3<T> min; /** * Position of Max corner of bounding box */ Vector3<T> max; public: /** * Constructs invalid axes-aligned bounding-box. * @see valid() for explanation of invalid bounding-box usage. */ Aabb3() : min(1, 1, 1), max(-1, -1, -1) { } /** * Constructs axes-aligned bound-box containing one point @a point * @param point */ template <typename SrcT> Aabb3(const Vector3<SrcT>& point) : min(point), max(point) { } /** * Constructs axes-aligned bounding-box form two corner points (@a x0, @a y0, @a z0) * and (@a x1, @a y1, @a z1) * @param x0 X-coordinate of first point * @param y0 Y-coordinate of first point * @param z0 Z-coordinate of first point * @param x1 X-coordinate of second point * @param y1 Y-coordinate of second point * @param z1 Z-coordinate of second point */ template <typename SrcT> Aabb3(SrcT x0, SrcT y0, SrcT z0, SrcT x1, SrcT y1, SrcT z1) : min(MIN(x0, x1), MIN(y0, y1), MIN(z0, z1)), max(MAX(x0, x1), MAX(y0, y1), MAX(z0, z1)) { } /** * Constructs axes-aligned bounding-box containing point (@a x, @a y, @a z) * @param x X-coordinate of point * @param y Y-coordinate of point * @param z Z-coordinate of point */ template <typename SrcT> Aabb3(SrcT x, SrcT y, SrcT z) : min(x, y, z), max(x, y, z) { } /** * Creates copy of axis-aligned bounding-box * @param src Source bounding-box */ template <typename SrcT> Aabb3(const Aabb3<SrcT>& src) : min(src.min), max(src.max) { } /** * Assign operator * @param rhs source bounding-box * @return refenrence to this */ template <typename SrcT> Aabb3<T>& operator=(const Aabb3<SrcT>& rhs) { min = rhs.min; max = rhs.max; return *this; } /** * Checks if bounding-box is valid. Valid bounding-box has non-negative size. * If an invalid bounding-box is extended by point or another bounding-box, the target * bounding box becomes valid and contains solely the source point or bounding-box respectively. * @return True if box is valid, otherwise false */ bool valid() const { return min.x <= max.x && min.y <= max.y && min.z <= max.z; } /** * Makes this bounding-box invalid. So calling valid() gets false. * @see valid() method for more info on usage of invalid bounding-boxes. */ void invalidate() { min = Vector3<T>(1, 1, 1); max = Vector3<T>(-1, -1, -1); } /** * Extends this bounding-box by a point @a point. * @param point A point to extend bounding-box by. */ template <typename SrcT> void extend(const Vector3<SrcT>& point) { if (!valid()) { min = max = point; } else { min = Vector3<T>::min(min, point); max = Vector3<T>::max(max, point); } } /** * Extends this bounding-box by a box @a box. * @param box A box to extend this bounding-box by. */ template <typename SrcT> void extend(const Aabb3<SrcT>& box) { if (!valid()) { min = box.min; max = box.max; } else { min = Vector3<T>::min(min, box.min); max = Vector3<T>::max(max, box.max); } } /** * Gets a copy of this bounding-box extend by a point @a point. * @param point A point to extend the box by * @return Copy of extended bounding-box */ template <typename SrcT> Aabb3<T> extended(const Vector3<SrcT>& point) const { Aabb3<T> ret(*this); ret.extend(point); return ret; } /** * Gets a copy of this bounding-box extnended by box @a box. * @param box A box to extend the copy be. * @return Copy of extended bounding-box */ template <typename SrcT> Aabb3<T> extended(const Aabb3<SrcT>& box) const { Aabb3<T> ret(*this); ret.extend(box); return ret; } /** * Tests if the point @a point is within this bounding-box * @param point A point to be tested * @return True if point @a point lies within bounding-box, otherwise false. */ template <typename SrcT> bool intersects(const Vector3<SrcT>& point) const { if (min.x > point.x || min.y > point.y || min.z > point.z || point.x > max.x || point.y > max.y || point.z > max.z) return false; return true; } /** * Tests if other bounding-box intersects (even partially) with this bouding-box. * @param box A box to be tested for intersection. * @return True if there's intersection between boxes, otherwise false. */ template <typename SrcT> bool intersects(const Aabb3<SrcT>& box) const { if (min.x > box.max.x || min.y > box.max.y || min.z > box.max.z || max.x < box.min.x || max.y < box.min.y || max.z < box.min.z) return false; return true; } /** * Tests if other sphere intersects (even partially) with this bouding-box. * @param box A box to be tested for intersection. * @return True if there's intersection between boxes, otherwise false. */ bool intersects(const Sphere<T> &sphere) const { T dmin = 0; Vector3<T> center = sphere.getCenter(); Vector3<T> bmin = min; Vector3<T> bmax = max; if (center.x < bmin.x) { T d = center.x - bmin.x; dmin += d * d; } else if (center.x > bmax.x) { T d = center.x - bmax.x; dmin += d * d; } if (center.y < bmin.y) { T d = center.y - bmin.y; dmin += d * d; } else if (center.y > bmax.y) { T d = center.y - bmax.y; dmin += d * d; } if (center.z < bmin.z) { T d = center.z - bmin.z; dmin += d * d; } else if (center.z > bmax.z) { T d = center.z - bmax.z; dmin += d * d; } return dmin <= (sphere.getRadius() * sphere.getRadius()); } /** * Gets result of intersection of this bounding-box with a other bounding-box. * In case the boxes don't intersect, the returned bounding-box is invalid. * @param other Box to be tested * @return Result of intersection. * @see valid() method for more information on invalid bounding-boxes. */ template <typename SrcT> Aabb3<T> intersection(const Aabb3<SrcT>& other) const { Aabb3<T> ret; if (min.x > other.max.x || min.y > other.max.y || min.z > other.max.z || max.x < other.min.x || max.y < other.min.y || max.z < other.min.z) return ret; ret.min = Vector3<T>::max(min, other.min); ret.max = Vector3<T>::min(max, other.max); return ret; } /** * Gets center point of bounding-box. * @return A center point of bounding-box. */ Vector3<T> center() const { return (min + max) / 2; } /** * Gets extent of bounding-box. * @return Extent of bounding-box. */ Vector3<T> extent() const { return (max - min) / 2; } /** * Gets diagonal size of bounding-box * @return Sizes for particular dimensions. */ Vector3<T> size() const { return max - min; } /** * Gets all 8 corner-points of bounding box * @param i An index of bounding-box corner point. Valid values are 0 .. 7. * @return A position of @a i-th corner-point. * @note The order of points is as follows (where @c + denotes max-point and @c - min-point): * 1. (@c + @c + @c +) * 2. (@c - @c + @c +) * 3. (@c + @c - @c +) * 4. (@c - @c - @c +) * 5. (@c + @c + @c -) * 6. (@c - @c + @c -) * 7. (@c + @c - @c -) * 8. (@c - @c - @c -) */ Vector3<T> point(size_t i) const { ASSERT(i < 8); return Vector3<T>(i & 1 ? min.x : max.x, i & 2 ? min.y : max.y, i & 4 ? min.z : max.z); } /** * Gets transformed bounding-box by transform @a t * @param t A transform matrix * @return Transformed bounding-box */ Aabb3<T> transformed(const Matrix4<T>& t) const { Aabb3<T> ret; for (size_t i = 0; i < 8; i++) { const Vector4<T> p(point(i), 1); ret.extend((t * p).xyz()); } return ret; } /** * Tests if @a rhs is equal to this bounding-box * @param rhs Right-hand side * @return True if @a rhs and this bounding-boxes are equal, otherwise false */ template <typename RhsT> bool operator==(const Aabb3<RhsT>& rhs) const { return min == rhs.min && max == rhs.max; } /** * Tests if @a rhs is not equal to this bounding-box * @param rhs Right-hand side * @return True if @a rhs and this bounding-boxes are not equal, otherwise false */ template <typename RhsT> bool operator!=(const Aabb3<RhsT>& rhs) const { return min != rhs.min || max != rhs.max; } /** * Gets transformed bounding-box by transform @a rhs. * @param rhs Matrix 4x4 representing the transform * @return Transformed bounding-box */ Aabb3<T> operator*(const Matrix4<T>& rhs) const { return transformed(rhs); } /** * Apply transform @a rhs to this bounding-box * @param rhs A transform to be applied * @return Reference to this */ Aabb3<T>& operator*=(const Matrix4<T>& rhs) { *this = transformed(rhs); return *this; } /** * Extends this bounding-box by point @a rhs. * @param rhs A point to extend this bounding-box by * @return Reference to this */ template <typename SrcT> Aabb3<T>& operator<<(const Vector3<SrcT>& rhs) { extend(rhs); return *this; } /** * Extends this bounding-box by box @a rhs. * @param rhs A box to extend this bounding-box by * @return Reference to this */ template <typename SrcT> Aabb3<T>& operator<<(const Aabb3<SrcT>& rhs) { extend(rhs); return *this; } /** * Union of this and @a rhs bounding-boxes * @param rhs Right-hand side of union * @return A resulting bounding-box representing union */ template <typename RhsT> Aabb3<T> operator|(const Aabb3<RhsT>& rhs) const { return extended(rhs); } /** * Intersection of this and @a rhs bounding-boxed * @param rhs Right-hand side * @return Resulting bouding-box representing the intersection. */ template <typename RhsT> Aabb3<T> operator&(const Aabb3<RhsT>& rhs) const { return intersection(rhs); } /** * Outputs string representation of bounding-box @a rhs to output stream @a lhs * @param lhs Output stream to write to * @param rhs Bounding-box to write to output stream. * @return Reference to output stream @a lhs */ friend std::ostream& operator<<(std::ostream& lhs, const Aabb3<T>& rhs) { lhs << rhs.toString(); return lhs; } /** * To string operator. */ std::string toString() const { char buffer[96]; sprintf(buffer, "%f,%f,%f,%f,%f,%f", min.x, min.y, min.z, max.x, max.y, max.z); return buffer; } }; typedef Aabb3<int> aabb3i; typedef Aabb3<float> aabb3f; typedef Aabb3<double> aabb3r; /** * Class Sphera */ template<typename T> class Sphere { public: /** * Constructor without init */ Sphere() {} /** * Constructor inti with center and radius */ Sphere(const Vector3<T>&center, T radius) : mCenter(center), mRadius(radius) {} /** * Get the redius */ T getRadius() const { return mRadius; } /** * Set the redius */ void setRadius(float radius) { mRadius = radius; } /** * Get the center */ const Vector3<T>& getCenter() const { return mCenter; } /** * Set the center */ void setCenter(const Vector3<T>& center) { mCenter = center; } /** * Tests if other AxisAlignedBox intersects (even partially) with this sphere */ bool intersects(const Aabb3<T> &box) const { return box.intersects(*this); } /** * Returns true if the ray intersects this sphere */ bool intersects(const Ray<T> &ray) const { T t; Vector3<T> temp = ray.getOrigin() - mCenter; T a = dot(ray.getDirection(), ray.getDirection()); T b = 2.0f * dot(temp, ray.getDirection()); T c = dot(temp, temp) - mRadius * mRadius; T disc = b * b - 4.0f * a * c; if (disc < 0.0f) { return false; } else { // this probably can be optimized T e = sqrt(disc); T denom = 2.0f * a; t = (-b - e) / denom; // smaller root if (t > FLT_EPSILON) { return true; } t = (-b + e) / denom; // larger root if (t > FLT_EPSILON) { return true; } } return false; } int intersects(const Ray<T> &ray, T *intersection) const { T t; Vector3<T> temp = ray.getOrigin() - mCenter; T a = dot(ray.getDirection(), ray.getDirection()); T b = 2 * dot(temp, ray.getDirection()); T c = dot(temp, temp) - mRadius * mRadius; T disc = b * b - 4 * a * c; if (disc < (T)0) { return 0; } else { T e = sqrt(disc); T denom = (T)2 * a; t = (-b - e) / denom; // smaller root if (t > FLT_EPSILON) { *intersection = t; return 1; } t = (-b + e) / denom; // larger root if (t > FLT_EPSILON) { *intersection = t; return 1; } } return 0; } /** * Get the closest point on the ray to the Sphere. * If the ray intersects then returns the point of nearest intersection. */ Vector3<T> closestPoint(const Ray<T> &ray) const { T t; Vector3<T> diff = ray.getOrigin() - mCenter; T a = dot(ray.getDirection(), ray.getDirection()); T b = 2 * dot(diff, ray.getDirection()); T c = dot(diff, diff) - mRadius * mRadius; T disc = b * b - 4 * a * c; if (disc > 0) { T e = sqrt(disc); T denom = 2 * a; t = (-b - e) / denom; // smaller root if (t > FLT_EPSILON) return ray.calcPosition(t); t = (-b + e) / denom; // larger root if (t > FLT_EPSILON) return ray.calcPosition(t); } // doesn't intersect; closest point on line t = dot(-diff, normalize(ray.getDirection())); Vector3<T> onRay = ray.calcPosition(t); return mCenter + normalize(onRay - mCenter) * mRadius; //return ray.getDirection() * dot( ray.getDirection(), (mCenter - ray.getOrigin() ) ); } void calcProjection(T focalLength, Vector2<T> *outCenter, Vector2<T> *outAxisA, Vector2<T> *outAxisB) const { Vector3<T> o(-mCenter.x, mCenter.y, mCenter.z); T r2 = mRadius * mRadius; T z2 = o.z * o.z; T l2 = dot(o, o); if (outCenter) *outCenter = focalLength * o.z * Vector2<T>(o) / (z2 - r2); if (abs(z2 - l2) > 0.00001f) { if (outAxisA) *outAxisA = focalLength * sqrt(-r2 * (r2 - l2) / ((l2 - z2)*(r2 - z2)*(r2 - z2))) * Vector2<T>(o.x, o.y); if (outAxisB) *outAxisB = focalLength * sqrt(abs(-r2 * (r2 - l2) / ((l2 - z2)*(r2 - z2)*(r2 - l2)))) * Vector2<T>(-o.y, o.x); } else { // approximate with circle T radius = focalLength * mRadius / sqrt(z2 - r2); if (outAxisA) *outAxisA = Vector2<T>(radius, 0); if (outAxisB) *outAxisB = Vector2<T>(0, radius); } } void calcProjection(T focalLength, Vector2<T> screenSizePixels, Vector2<T> *outCenter, Vector2<T> *outAxisA, Vector2<T> *outAxisB) const { Vector2<T> toScreenPixels = [=](Vector2<T> v, const Vector2<T> &windowSize) { Vector2<T> result = v; result.x *= 1 / (windowSize.x / windowSize.y); result += Vector2<T>(0.5, 0.5); result *= windowSize; return result; }; Vector2<T> center, axisA, axisB; calcProjection(focalLength, &center, &axisA, &axisB); if (outCenter) *outCenter = toScreenPixels(center, screenSizePixels); if (outAxisA) *outAxisA = toScreenPixels(center + axisA * 0.5f, screenSizePixels) - toScreenPixels(center - axisA * 0.5f, screenSizePixels); if (outAxisB) *outAxisB = toScreenPixels(center + axisB * 0.5f, screenSizePixels) - toScreenPixels(center - axisB * 0.5f, screenSizePixels); } protected: Vector3<T> mCenter; T mRadius; }; typedef Sphere<float> spheref; typedef Sphere<double> sphere; template<typename T> class Ray { public: Ray() {} Ray(const Vector3<T> &aOrigin, const Vector3<T> &aDirection) : mOrigin(aOrigin) { setDirection(aDirection); } void setOrigin(const Vector3<T> &aOrigin) { mOrigin = aOrigin; } const Vector3<T>& getOrigin() const { return mOrigin; } void setDirection(const Vector3<T> &aDirection) { mDirection = aDirection; mInvDirection = Vector3<T>((T)1 / mDirection.x, (T)1 / mDirection.y, (T)1 / mDirection.z); mSignX = (mDirection.x < (T)0) ? 1 : 0; mSignY = (mDirection.y < (T)0) ? 1 : 0; mSignZ = (mDirection.z < (T)0) ? 1 : 0; } const Vector3<T>& getDirection() const { return mDirection; } const Vector3<T>& getInverseDirection() const { return mInvDirection; } char getSignX() const { return mSignX; } char getSignY() const { return mSignY; } char getSignZ() const { return mSignZ; } void transform(const Matrix4<T> &matrix) { mOrigin = Vector3<T>(matrix * Vector4<T>(mOrigin, 1)); setDirection(Matrix3<T>(matrix) * mDirection); } Ray<T> transformed(const Matrix4<T> &matrix) const { Ray<T> result; result.mOrigin = Vector3<T>(matrix * Vector4<T>(mOrigin, 1)); result.setDirection(Matrix3<T>(matrix) * mDirection); return result; } Vector3<T> calcPosition(T t) const { return mOrigin + mDirection * t; } bool calcTriangleIntersection(const Vector3<T> &vert0, const Vector3<T> &vert1, const Vector3<T> &vert2, T *result) const { Vector3<T> edge1, edge2, tvec, pvec, qvec; T det; T u, v; const T epsilon = T(0.000001); edge1 = vert1 - vert0; edge2 = vert2 - vert0; pvec = cross(getDirection(), edge2); det = dot(edge1, pvec); #if 0 // we don't want to backface cull if (det < epsilon) return false; tvec = getOrigin() - vert0; u = dot(tvec, pvec); if ((u < 0.0f) || (u > det)) return false; qvec = cross(tvec, edge1); v = dot(getDirection(), qvec); if (v < 0.0f || u + v > det) return false; *result = dot(edge2, qvec) / det; return true; #else if (det > -epsilon && det < epsilon) return false; T inv_det = T(1) / det; tvec = getOrigin() - vert0; u = dot(tvec, pvec) * inv_det; if (u < T(0) || u > T(1)) return false; qvec = cross(tvec, edge1); v = dot(getDirection(), qvec) * inv_det; if (v < T(0) || u + v > T(1)) return 0; *result = dot(edge2, qvec) * inv_det; return true; #endif } bool calcPlaneIntersection(const Vector3<T> &origin, const Vector3<T> &normal, T *result) const { T denom = dot(normal, getDirection()); if (denom != T(0)) { *result = dot(normal, origin - getOrigin()) / denom; return true; } return false; } protected: Vector3<T> mOrigin; Vector3<T> mDirection; // these are helpful to certain ray intersection algorithms char mSignX, mSignY, mSignZ; Vector3<T> mInvDirection; }; typedef Ray<float> rayf; typedef Ray<double> ray; } // !namespace sge #pragma pack(pop) #pragma warning(pop) #pragma warning(disable: 4251) #endif // SGE_MATH_H
[ "xiangwencheng@outlook.com" ]
xiangwencheng@outlook.com
2e1d97ab6d2bd06d742e799e5961e52efc09cb5f
2662b1a8c19fe9672f31d163bd3412a51cf0796c
/Assignments/helloGraphics.cpp
baa1efee2e1168b7345d6132d05801a45bec7ec8
[]
no_license
KSHAMIN/cgl
e049208654f77216991439b6a19f76db1dd96533
460994d29e88b38934d1d88964f9c1b6668f0404
refs/heads/master
2020-12-30T05:59:46.598117
2020-02-28T09:29:11
2020-02-28T09:29:11
238,884,575
0
0
null
null
null
null
UTF-8
C++
false
false
1,537
cpp
// C program to demonstrate // drawing a circle using // OpenGL #include<iostream> #include<GL/glut.h> #include<math.h> #define pi 3.142857 // function to initialize void myInit (void) { // making background color black as first // 3 arguments all are 0.0 glClearColor(0.0, 0.0, 0.0, 1.0); // making picture color green (in RGB mode), as middle argument is 1.0 glColor3f(1.0, 0.1, 0.6); // breadth of picture boundary is 1 pixel glPointSize(.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // setting window dimension in X- and Y- direction gluOrtho2D(-420, 420, -420, 420); } float r; void display (void) { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POINTS); float x, y, i; // iterate y up to 2*pi, i.e., 360 degree // with small increment in angle as // glVertex2i just draws a point on specified co-ordinate for ( i = -2 * pi; i < (2 * pi); i += 0.0001) { // let 200 is radius of circle and as, // circle is defined as x=r*cos(i) and y=r*sin(i) x = r * i; y = r * (cos(i) * sin(i) + sin(i) * tan(i)); glVertex2i(x, y); } glEnd(); glFlush(); } int main (int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); std::cout << "Enter Radius : "; std::cin >> r; // giving window size in X- and Y- direction glutInitWindowSize(768, 768); glutInitWindowPosition(0, 0); // Giving name to window glutCreateWindow("Circle Drawing"); myInit(); glutDisplayFunc(display); glutMainLoop(); }
[ "onkar.shr007@gmail.com" ]
onkar.shr007@gmail.com
96e59239be46f2486bb30f743c69515e2c7c70c9
88a60552472e8ded90108edbc54556ac4b56e0a5
/TcpProxySession.cpp
a6686a5edfd48a8ae1a7a4b13d1862388a6173b4
[]
no_license
aaronriekenberg/asioproxy
1f4354e68134a0ae63c87e274fa087af3d6626bb
840714fa44e3afb567e18c6c71a64dd96b76c96c
refs/heads/master
2021-01-18T19:19:27.024393
2013-09-01T11:27:01
2013-09-01T11:27:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,086
cpp
#include "BoostSystemUtil.h" #include "Log.h" #include "TcpProxySession.h" #include "ProxyOptions.h" namespace asioproxy { TcpProxySession::SharedPtr TcpProxySession::create( boost::asio::io_service& ioService) { return SharedPtr(new TcpProxySession(ioService)); } TcpProxySession::~TcpProxySession() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::~TcpProxySession " << this; } terminate(); } boost::asio::ip::tcp::socket& TcpProxySession::getClientSocket() { return m_clientSocket; } void TcpProxySession::handleClientSocketAccepted() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "handleClientSocketAccepted"; } if (ProxyOptions::getInstance().isNoDelay()) { boost::asio::ip::tcp::no_delay noDelayOption(true); m_clientSocket.set_option(noDelayOption); } std::stringstream clientToProxySS; clientToProxySS << m_clientSocket.remote_endpoint() << " -> " << m_clientSocket.local_endpoint(); m_clientToProxyString = clientToProxySS.str(); Log::getInfoInstance() << "connected client to proxy " << m_clientToProxyString; const ProxyOptions::AddressAndPort& remoteAddressPort = ProxyOptions::getInstance().getRemoteAddressPort(); Log::getInfoInstance() << "begin resolving " << std::get<0>(remoteAddressPort) << ":" << std::get<1>(remoteAddressPort); boost::asio::ip::tcp::resolver::query query(std::get<0>(remoteAddressPort), std::get<1>(remoteAddressPort)); auto sharedThis = shared_from_this(); m_resolver.async_resolve(query, [=] (const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iterator) { sharedThis->handleRemoteEndpointResolved(error, iterator); }); } TcpProxySession::TcpProxySession(boost::asio::io_service& ioService) : m_clientSocket(ioService), m_resolver(ioService), m_remoteSocket( ioService), m_connectTimeoutTimer(ioService) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::TcpProxySession " << this; } } void TcpProxySession::terminate() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::terminate"; } if ((!m_clientSocketClosed) && (!m_writingToClientSocket)) { m_clientSocket.close(); m_clientSocketClosed = true; if (!m_clientToProxyString.empty()) { Log::getInfoInstance() << "disconnect client to proxy " << m_clientToProxyString; } } if ((!m_remoteSocketClosed) && (!m_writingToRemoteSocket)) { m_remoteSocket.close(); m_remoteSocketClosed = true; if (!m_proxyToRemoteString.empty()) { Log::getInfoInstance() << "disconnect proxy to remote " << m_proxyToRemoteString; } } m_connectTimeoutTimer.cancel(); } void TcpProxySession::handleRemoteEndpointResolved( const boost::system::error_code& error, boost::asio::ip::tcp::resolver::iterator iterator) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "handleRemoteEndpointResolved"; } if (error) { const ProxyOptions::AddressAndPort& remoteAddressPort = ProxyOptions::getInstance().getRemoteAddressPort(); Log::getInfoInstance() << "failed to resolve " << std::get<0>(remoteAddressPort) << ":" << std::get<1>(remoteAddressPort); terminate(); } else { boost::asio::ip::tcp::endpoint remoteEndpoint = *iterator; Log::getInfoInstance() << "begin connect to remote " << remoteEndpoint; auto sharedThis = shared_from_this(); m_remoteSocket.async_connect(remoteEndpoint, [=] (const boost::system::error_code& error) { sharedThis->handleConnectFinished(error); }); m_connectTimeoutTimer.expires_from_now( ProxyOptions::getInstance().getConnectTimeout()); m_connectTimeoutTimer.async_wait( [=] (const boost::system::error_code& error) { sharedThis->handleConnectTimeout(); }); } } void TcpProxySession::handleConnectTimeout() { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleConnectTimeout"; } m_connectTimeoutTimerPopped = true; if (!m_connectToRemoteFinished) { Log::getInfoInstance() << "connect timeout"; terminate(); } } void TcpProxySession::handleConnectFinished( const boost::system::error_code& error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleConnectFinished"; } m_connectToRemoteFinished = true; if (m_connectTimeoutTimerPopped) { terminate(); } else if (error) { Log::getInfoInstance() << "error connecting to remote endpoint: " << BoostSystemUtil::buildErrorCodeString(error); terminate(); } else { m_connectTimeoutTimer.cancel(); // allocate buffers const size_t bufferSize = ProxyOptions::getInstance().getBufferSize(); m_dataFromClientBuffer.resize(bufferSize, 0); m_dataFromRemoteBuffer.resize(bufferSize, 0); if (ProxyOptions::getInstance().isNoDelay()) { boost::asio::ip::tcp::no_delay noDelayOption(true); m_remoteSocket.set_option(noDelayOption); } std::stringstream proxyToRemoteSS; proxyToRemoteSS << m_remoteSocket.local_endpoint() << " -> " << m_remoteSocket.remote_endpoint(); m_proxyToRemoteString = proxyToRemoteSS.str(); Log::getInfoInstance() << "connected proxy to remote " << m_proxyToRemoteString; asyncReadFromClient(); asyncReadFromRemote(); } } void TcpProxySession::asyncReadFromClient() { auto sharedThis = shared_from_this(); m_clientSocket.async_read_some(boost::asio::buffer(m_dataFromClientBuffer), [=] (const boost::system::error_code& error, size_t bytesTransferred) { sharedThis->handleClientRead(error, bytesTransferred); }); } void TcpProxySession::asyncReadFromRemote() { auto sharedThis = shared_from_this(); m_remoteSocket.async_read_some(boost::asio::buffer(m_dataFromRemoteBuffer), [=] (const boost::system::error_code& error, size_t bytesTransferred) { sharedThis->handleRemoteRead(error, bytesTransferred); }); } void TcpProxySession::handleClientRead(const boost::system::error_code& error, size_t bytesRead) { if (m_remoteSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleClientRead error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { m_writingToRemoteSocket = true; auto sharedThis = shared_from_this(); boost::asio::async_write(m_remoteSocket, boost::asio::buffer(m_dataFromClientBuffer, bytesRead), [=] (const boost::system::error_code& error, size_t bytesWritten) { sharedThis->handleRemoteWriteFinished(error); }); } } void TcpProxySession::handleRemoteRead(const boost::system::error_code& error, size_t bytesRead) { if (m_clientSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleRemoteRead error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { m_writingToClientSocket = true; auto sharedThis = shared_from_this(); boost::asio::async_write(m_clientSocket, boost::asio::buffer(m_dataFromRemoteBuffer, bytesRead), [=] (const boost::system::error_code& error, size_t bytesWritten) { sharedThis->handleClientWriteFinished(error); }); } } void TcpProxySession::handleRemoteWriteFinished( const boost::system::error_code& error) { m_writingToRemoteSocket = false; if (m_clientSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleRemoteWriteFinished error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { asyncReadFromClient(); } } void TcpProxySession::handleClientWriteFinished( const boost::system::error_code& error) { m_writingToClientSocket = false; if (m_remoteSocketClosed) { terminate(); } else if (error) { if (Log::isDebugEnabled()) { Log::getDebugInstance() << "TcpProxySession::handleClientWriteFinished error = " << BoostSystemUtil::buildErrorCodeString(error); } terminate(); } else { asyncReadFromRemote(); } } }
[ "aaron.riekenberg@gmail.com" ]
aaron.riekenberg@gmail.com
94d70b1edcb31935530a03bd584b03f359eca7f6
ab558d94f12fd5aac98beb5d917ebfeb12714c1f
/BigBang/include/layers/sigmoid_layer.h
c7f18fafb6dc5ac8e757b71eb48c0f339a3a58af
[ "Apache-2.0" ]
permissive
1icas/BigBang
d3fed782f26e5a840f561cd9f91e339f48a2d8be
c7492e201fe63cb9acc4690b38175abe30720fbd
refs/heads/master
2021-09-06T10:25:28.032614
2018-02-05T14:29:30
2018-02-05T14:29:30
107,073,492
1
1
null
null
null
null
UTF-8
C++
false
false
965
h
#ifndef SIGMOID_LAYER_H #define SIGMOID_LAYER_H #include "activation_func_layer.h" #include "layer_type_macro.h" #include "../tensor.h" namespace BigBang { template<typename dtype> class SigmoidLayer : public ActivationFuncLayer<dtype> { public: SigmoidLayer(const LayerParameter& params):ActivationFuncLayer(params){} virtual ~SigmoidLayer() {} virtual inline const char* Type() const override { return SIGMOID_LAYER_TYPE; } protected: virtual void Forward_CPU(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; virtual void Backward_CPU(const Tensor<dtype>* top, Tensor<dtype>* bottom) override; virtual void Forward_GPU(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; virtual void Backward_GPU(const Tensor<dtype>* top, Tensor<dtype>* bottom) override; virtual void Prepare(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; virtual void reshape(const Tensor<dtype>* bottom, Tensor<dtype>* top) override; }; } #endif
[ "30893898@qq.com" ]
30893898@qq.com
5b50b6919d95fd52d34821005006f0623bfef1a7
a7a369fe4a73b2ee8a043b1ff15ed56ee1b1d292
/src/server/scripts/Northrend/Nexus/EyeOfEternity/instance_eye_of_eternity.cpp
4ac5d1de4a014911d74052fb5f4b8a41be0f7607
[]
no_license
cooler-SAI/ServerMythCore
de720f8143f14fb0e36c2b7291def52f660d9e1a
bd99985adca0698b7419094726bdbce13c18740c
refs/heads/master
2020-04-04T21:27:04.974080
2015-06-22T14:06:42
2015-06-22T14:06:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,187
cpp
/* * Copyright (C) 2008 - 2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2013 Myth Project <http://mythprojectnetwork.blogspot.com/> * * Myth Project's source is based on the Trinity Project source, you can find the * link to that easily in Trinity Copyrights. Myth Project is a private community. * To get access, you either have to donate or pass a developer test. * You may not share Myth Project's sources! For personal use only. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "InstanceScript.h" #include "eye_of_eternity.h" class instance_eye_of_eternity : public InstanceMapScript { public: instance_eye_of_eternity() : InstanceMapScript("instance_eye_of_eternity", 616) { } InstanceScript* GetInstanceScript(InstanceMap* pMap) const { return new instance_eye_of_eternity_InstanceMapScript(pMap); } struct instance_eye_of_eternity_InstanceMapScript : public InstanceScript { instance_eye_of_eternity_InstanceMapScript(Map* pMap) : InstanceScript(pMap) { SetBossNumber(MAX_ENCOUNTER); vortexTriggers.clear(); portalTriggers.clear(); malygosGUID = 0; lastPortalGUID = 0; platformGUID = 0; exitPortalGUID = 0; }; bool SetBossState(uint32 type, EncounterState state) { if(!InstanceScript::SetBossState(type, state)) return false; if(type == DATA_MALYGOS_EVENT) { if(state == FAIL) { for(std::list<uint64>::const_iterator itr_trigger = portalTriggers.begin(); itr_trigger != portalTriggers.end(); ++itr_trigger) { if(Creature* trigger = instance->GetCreature(*itr_trigger)) { // just in case trigger->RemoveAllAuras(); trigger->AI()->Reset(); } } SpawnGameObject(GO_FOCUSING_IRIS, focusingIrisPosition); SpawnGameObject(GO_EXIT_PORTAL, exitPortalPosition); if(GameObject* platform = instance->GetGameObject(platformGUID)) platform->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); } else if(state == DONE) { if(Creature* malygos = instance->GetCreature(malygosGUID)) malygos->SummonCreature(NPC_ALEXSTRASZA, 829.0679f, 1244.77f, 279.7453f, 2.32f); SpawnGameObject(GO_EXIT_PORTAL, exitPortalPosition); // we make the platform appear again because at the moment we don't support looting using a vehicle if(GameObject* platform = instance->GetGameObject(platformGUID)) platform->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_DESTROYED); if(GameObject* chest = instance->GetGameObject(chestGUID)) chest->SetRespawnTime(7*DAY); } } return true; } // There is no other way afaik... void SpawnGameObject(uint32 entry, Position& pos) { GameObject* pGo = new GameObject; if(!pGo->Create(sObjectMgr->GenerateLowGuid(HIGHGUID_GAMEOBJECT),entry, instance, PHASEMASK_NORMAL, pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), 0, 0, 0, 0, 120, GO_STATE_READY)) { delete pGo; return; } instance->Add(pGo); } void OnGameObjectCreate(GameObject* pGo) { switch(pGo->GetEntry()) { case GO_NEXUS_RAID_PLATFORM: platformGUID = pGo->GetGUID(); break; case GO_FOCUSING_IRIS: pGo->GetPosition(&focusingIrisPosition); break; case GO_EXIT_PORTAL: exitPortalGUID = pGo->GetGUID(); pGo->GetPosition(&exitPortalPosition); break; case GO_ALEXSTRASZA_S_GIFT: case GO_ALEXSTRASZA_S_GIFT_2: chestGUID = pGo->GetGUID(); break; } } void OnCreatureCreate(Creature* pCreature) { switch(pCreature->GetEntry()) { case NPC_VORTEX_TRIGGER: vortexTriggers.push_back(pCreature->GetGUID()); break; case NPC_MALYGOS: malygosGUID = pCreature->GetGUID(); break; case NPC_PORTAL_TRIGGER: portalTriggers.push_back(pCreature->GetGUID()); break; } } void ProcessEvent(WorldObject* pWO, uint32 eventId) { if(eventId == EVENT_FOCUSING_IRIS) { if(GameObject* go = pWO->ToGameObject()) go->Delete(); // this is not the best way. if(Creature* malygos = instance->GetCreature(malygosGUID)) malygos->GetMotionMaster()->MovePoint(4, 770.10f, 1275.33f, 267.23f); // MOVE_INIT_PHASE_ONE if(GameObject* exitPortal = instance->GetGameObject(exitPortalGUID)) exitPortal->Delete(); } } void VortexHandling() { if(Creature* malygos = instance->GetCreature(malygosGUID)) { std::list<HostileReference*> m_threatlist = malygos->getThreatManager().getThreatList(); for(std::list<uint64>::const_iterator itr_vortex = vortexTriggers.begin(); itr_vortex != vortexTriggers.end(); ++itr_vortex) { if(m_threatlist.empty()) return; uint8 counter = 0; if(Creature* pTrigger_Creature = instance->GetCreature(*itr_vortex)) { // each trigger have to cast the spell to 5 players. for(std::list<HostileReference*>::const_iterator itr = m_threatlist.begin(); itr!= m_threatlist.end(); ++itr) { if(counter >= 5) break; if(Unit* pTarget = (*itr)->getTarget()) { Player* pPlayer = pTarget->ToPlayer(); if(!pPlayer || pPlayer->isGameMaster() || pPlayer->HasAura(SPELL_VORTEX_4)) continue; pPlayer->CastSpell(pTrigger_Creature, SPELL_VORTEX_4, true); counter++; } } } } } } void PowerSparksHandling() { bool next = (lastPortalGUID == portalTriggers.back() || !lastPortalGUID ? true : false); for(std::list<uint64>::const_iterator itr_trigger = portalTriggers.begin(); itr_trigger != portalTriggers.end(); ++itr_trigger) { if(next) { if(Creature* trigger = instance->GetCreature(*itr_trigger)) { lastPortalGUID = trigger->GetGUID(); trigger->CastSpell(trigger, SPELL_PORTAL_OPENED, true); return; } } if(*itr_trigger == lastPortalGUID) next = true; } } void SetData(uint32 data, uint32 /*value*/) { switch(data) { case DATA_VORTEX_HANDLING: VortexHandling(); break; case DATA_POWER_SPARKS_HANDLING: PowerSparksHandling(); break; } } uint64 GetData64(uint32 data) { switch(data) { case DATA_TRIGGER: return vortexTriggers.front(); case DATA_MALYGOS: return malygosGUID; case DATA_PLATFORM: return platformGUID; } return 0; } std::string GetSaveData() { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << "E E " << GetBossSaveData(); OUT_SAVE_INST_DATA_COMPLETE; return saveStream.str(); } void Load(const char* str) { if(!str) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(str); char dataHead1, dataHead2; std::istringstream loadStream(str); loadStream >> dataHead1 >> dataHead2; if(dataHead1 == 'E' && dataHead2 == 'E') { for(uint8 i = 0; i < MAX_ENCOUNTER; ++i) { uint32 tmpState; loadStream >> tmpState; if(tmpState == IN_PROGRESS || tmpState > SPECIAL) tmpState = NOT_STARTED; SetBossState(i, EncounterState(tmpState)); } } else OUT_LOAD_INST_DATA_FAIL; OUT_LOAD_INST_DATA_COMPLETE; } private: std::list<uint64> vortexTriggers; std::list<uint64> portalTriggers; uint64 malygosGUID; uint64 lastPortalGUID; uint64 platformGUID; uint64 exitPortalGUID; uint64 chestGUID; Position focusingIrisPosition; Position exitPortalPosition; }; }; void AddSC_instance_eye_of_eternity() { new instance_eye_of_eternity(); }
[ "humbertohuanuco@gmail.com" ]
humbertohuanuco@gmail.com
700d117c9f7e07e5d11aaa33b419ee6cddd99f62
d1bb6fd4b439da85af74321e3391413640fb92f0
/Homework1Q1S2/Homework1Q1S2/Rational.cpp
de3a6b4f857e753fea0a93455e268271a3d7f266
[]
no_license
YosefSchoen/ObjectOrientedProgramming
dc6138501285509cb25cff111f2b18e79753764a
f0a36c7bf3fe461ccdabf010905a40c30c41eac4
refs/heads/master
2020-07-30T21:35:49.839185
2019-09-23T13:45:03
2019-09-23T13:45:03
210,356,549
0
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
#include "Rational.h"; #include <iostream> using namespace std; Rational::Rational(int top, int bottom) { numerator = top; denominator = bottom; } void Rational::setNumerator(int top) { numerator = top; } void Rational::setDenominator(int bottom) { denominator = bottom; } int Rational::getNumerator() { return numerator; } int Rational::getDenominator() { return denominator; } void Rational::print() { cout << numerator << "/" << denominator << endl; } bool Rational::equal(Rational second) { if (numerator * second.getDenominator() == denominator * second.getNumerator()) { return true; } else { return false; } } int Rational::reduce() { if (numerator == denominator) { return 1; } else { for (int i = 2; i <= numerator; i++) { if ((numerator % i == 0) && (denominator % i == 0)) { numerator = numerator / i; denominator = denominator / i; } } } return 0; }
[ "josephaschoen@gmail.com" ]
josephaschoen@gmail.com
41b7677312fd583b5c4034129540a7b406b24f9e
6fe993c6e41af7679ab2bbaafd1b9bec5f0191e5
/src/main.cpp
d4a1816a222e5339d953f1820a544c4a80669e56
[]
no_license
pmaroti/loraTestTransmitter
c91c6c3faad540c0ff15a5fe0b2467a7518f53e4
e1f70f406cc046184f16005186b43e736f2a279b
refs/heads/master
2020-03-18T00:04:06.300115
2018-05-19T15:52:22
2018-05-19T15:52:22
134,076,069
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
cpp
/// /// Arduino SX1278_Lora /// GND----------GND (ground in) /// 3V3----------3.3V (3.3V in) /// interrupt 0 pin D2-----------DIO0 (interrupt request out) /// SS pin D10----------NSS (CS chip select in) /// SCK pin D13----------SCK (SPI clock in) /// MOSI pin D11----------MOSI (SPI Data in) /// MISO pin D12----------MISO (SPI Data out) /// #include <SPI.h> #include <RH_RF95.h> // Singleton instance of the radio driver RH_RF95 SX1278; byte counter; char counter_string[]="Counter: 00"; void setup() { Serial.begin(9600); while (!Serial) ; // Wait for serial port to be available if (!SX1278.init()) Serial.println("Notice:init failed"); Serial.println("Initialization OK"); counter = 0; } void loop() { Serial.print("Sending to SX1278_server"); itoa(counter,counter_string+9,10); Serial.println(counter_string); // Send a message to SX1278_server SX1278.send(counter_string, sizeof(counter_string)); Serial.println("mark0"); SX1278.waitPacketSent(); Serial.println("mark1"); // Now wait for a reply uint8_t buf[RH_RF95_MAX_MESSAGE_LEN]; uint8_t len = sizeof(buf); delay(1000); Serial.println("mark2"); counter++; }
[ "pmaroti@gmail.com" ]
pmaroti@gmail.com
06f218de53f4128a70879f3ee00307f0c6ee9126
735d7d9177ba60d7d94577b30ec37857d2bcd4fc
/pointers/demo3.cpp
a59714026b884fb91d638f8297243ad19c3f6c9c
[ "MIT" ]
permissive
KleeTaurus/learn-cpp
5043ddd38eaa778eabe6763c7214db62e3e2f2f2
ec872ac7ea9ee323e7afbf8f717c6120771f81d3
refs/heads/master
2020-12-02T19:19:12.585479
2017-08-12T02:56:41
2017-08-12T02:56:41
96,324,050
1
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
#include <iostream> using namespace std; int main() { int *ptr = NULL; cout << "The value of ptr is: " << ptr; return 0; }
[ "lining@luojilab.com" ]
lining@luojilab.com
6ee77165137b972c9e3b4ca71c1c1468f79af624
1b6c60b5a14f5eb7ea06676159e1a83c18cf6bb5
/kattis/Baby_bites_kattis.cpp
bb4e63cd0050e764070d38bbca67c6b65c91d205
[ "MIT" ]
permissive
NafiAsib/competitive-programming
75595c2b0984baf72a998da8b3d115bf2681e07c
3255b2fe3329543baf9e720e1ccaf08466d77303
refs/heads/master
2022-11-20T06:48:01.951206
2020-07-22T10:20:09
2020-07-22T10:20:09
240,660,207
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
#include <bits/stdc++.h> using namespace std; int main() { int i, index = 0, n, current = 1; char str[10]; bool sense = 1; cin >> n; for(i = 0; i < n; i++, current++) { cin>>str; if(str[0] == 'm') continue; index = atoi(str); if(index != current) sense = 0; } if(sense) cout<<"makes sense"<<"\n"; else cout<<"something is fishy"<<"\n"; return 0; }
[ "nafi.asib@gmail.com" ]
nafi.asib@gmail.com
206266d760d85b3d69f71d7a58e7a6ffa70a554a
2849e23dd5f004e9656c01507461b34ce47098f5
/src/MEDebug.cpp
7ac8f56761394c845c4585ce4b8c6784e7873088
[]
no_license
FrozenArcher/MakeEngine
a671556bc0fbf95b5ac911ab34994c6c8c183467
1d6a5e51ac3a81d399142af90f07eb0f6455fd84
refs/heads/master
2023-05-12T14:33:27.290970
2021-06-06T13:55:14
2021-06-06T13:55:14
374,047,309
0
0
null
null
null
null
UTF-8
C++
false
false
504
cpp
// // Created by fracher on 2021/6/5. // #include "METime.h" #include "MEBaseTypes.h" #include <iostream> using std::cout, std::endl; namespace MakeEngine { void Log(const MEString& message) { cout << "[Log] " << GetTimeNowStr() << message << endl << endl; } void LogTest(const MEString& name, bool result) { cout << "[Test] " << GetTimeNowStr() << "Running test: " << name << "\nresult: " << (result ? "passed" : "failed") << endl << endl; } }
[ "yhy242989105@hotmail.com" ]
yhy242989105@hotmail.com
cd0ec349d7b6d9beaee9cce9341498ba2583ab98
3c47ad20c580bdb5b41d46d2baebc9769831859a
/MyGameServer/tinyxml.h
a5c9c8829a1ee6539096481ab4d9dd5a56aaa6c6
[]
no_license
adofsauron/MyGameServer
f99eea6cec3b3aed3fdbad62c58d61ebfbe0ad96
0c3eed2f7135e884fcf0f1ecc1ab1c77bb4d9a09
refs/heads/master
2020-03-28T10:40:31.204918
2018-09-10T08:24:17
2018-09-10T08:24:17
148,133,018
0
0
null
null
null
null
UTF-8
C++
false
false
64,834
h
/* www.sourceforge.net/projects/tinyxml Original code by Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef TINYXML_INCLUDED #define TINYXML_INCLUDED #ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4530 ) #pragma warning( disable : 4786 ) #endif #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> // Help out __WIN__: #if defined( _DEBUG ) && !defined( DEBUG ) #define DEBUG #endif #ifdef TIXML_USE_STL #include <string> #include <iostream> #include <sstream> #define TIXML_STRING std::string #else #include "tinystr.h" #define TIXML_STRING TiXmlString #endif // Deprecated library function hell. Compilers want to use the // new safe versions. This probably doesn't fully address the problem, // but it gets closer. There are too many compilers for me to fully // test. If you get compilation troubles, undefine TIXML_SAFE #define TIXML_SAFE #ifdef TIXML_SAFE #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) // Microsoft visual studio, version 2005 and higher. #define TIXML_SNPRINTF _snprintf_s #define TIXML_SSCANF sscanf_s #elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) // Microsoft visual studio, version 6 and higher. //#pragma message( "Using _sn* functions." ) #define TIXML_SNPRINTF _snprintf #define TIXML_SSCANF sscanf #elif defined(__GNUC__) && (__GNUC__ >= 3 ) // GCC version 3 and higher.s //#warning( "Using sn* functions." ) #define TIXML_SNPRINTF snprintf #define TIXML_SSCANF sscanf #else #define TIXML_SNPRINTF snprintf #define TIXML_SSCANF sscanf #endif #endif class TiXmlDocument; class TiXmlElement; class TiXmlComment; class TiXmlUnknown; class TiXmlAttribute; class TiXmlText; class TiXmlDeclaration; class TiXmlParsingData; const int TIXML_MAJOR_VERSION = 2; const int TIXML_MINOR_VERSION = 6; const int TIXML_PATCH_VERSION = 2; /* Internal structure for tracking location of items in the XML file. */ struct TiXmlCursor { TiXmlCursor() { Clear(); } void Clear() { row = col = -1; } int row; // 0 based. int col; // 0 based. }; /** Implements the interface to the "Visitor pattern" (see the Accept() method.) If you call the Accept() method, it requires being passed a TiXmlVisitor class to handle callbacks. For nodes that contain other nodes (Document, Element) you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves are simply called with Visit(). If you return 'true' from a Visit method, recursive parsing will continue. If you return false, <b>no children of this node or its sibilings</b> will be Visited. All flavors of Visit methods have a default implementation that returns 'true' (continue visiting). You need to only override methods that are interesting to you. Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting. You should never change the document from a callback. @sa TiXmlNode::Accept() */ class TiXmlVisitor { public: virtual ~TiXmlVisitor() {} /// Visit a document. virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) { return true; } /// Visit a document. virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) { return true; } /// Visit an element. virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) { return true; } /// Visit an element. virtual bool VisitExit( const TiXmlElement& /*element*/ ) { return true; } /// Visit a declaration virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; } /// Visit a text node virtual bool Visit( const TiXmlText& /*text*/ ) { return true; } /// Visit a comment node virtual bool Visit( const TiXmlComment& /*comment*/ ) { return true; } /// Visit an unknown node virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; } }; // Only used by Attribute::Query functions enum { TIXML_SUCCESS, TIXML_NO_ATTRIBUTE, TIXML_WRONG_TYPE }; // Used by the parsing routines. enum TiXmlEncoding { TIXML_ENCODING_UNKNOWN, TIXML_ENCODING_UTF8, TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; /** TiXmlBase is a base class for every class in TinyXml. It does little except to establish that TinyXml classes can be printed and provide some utility functions. In XML, the document and elements can contain other elements and other types of nodes. @verbatim A Document can contain: Element (container or leaf) Comment (leaf) Unknown (leaf) Declaration( leaf ) An Element can contain: Element (container or leaf) Text (leaf) Attributes (not on tree) Comment (leaf) Unknown (leaf) A Decleration contains: Attributes (not on tree) @endverbatim */ class TiXmlBase { friend class TiXmlNode; friend class TiXmlElement; friend class TiXmlDocument; public: TiXmlBase() : userData(0) {} virtual ~TiXmlBase() {} /** All TinyXml classes can print themselves to a filestream or the string class (TiXmlString in non-STL mode, std::string in STL mode.) Either or both cfile and str can be null. This is a formatted print, and will insert tabs and newlines. (For an unformatted stream, use the << operator.) */ virtual void Print( FILE* cfile, int depth ) const = 0; /** The world does not agree on whether white space should be kept or not. In order to make everyone happy, these global, static functions are provided to set whether or not TinyXml will condense all white space into a single space or not. The default is to condense. Note changing this value is not thread safe. */ static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } /// Return the current white space setting. static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } /** Return the position, in the original source file, of this node or attribute. The row and column are 1-based. (That is the first row and first column is 1,1). If the returns values are 0 or less, then the parser does not have a row and column value. Generally, the row and column value will be set when the TiXmlDocument::Load(), TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set when the DOM was created from operator>>. The values reflect the initial load. Once the DOM is modified programmatically (by adding or changing nodes and attributes) the new values will NOT update to reflect changes in the document. There is a minor performance cost to computing the row and column. Computation can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. @sa TiXmlDocument::SetTabSize() */ int Row() const { return location.row + 1; } int Column() const { return location.col + 1; } ///< See Row() void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data. void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data. const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data. // Table that returs, for a given lead byte, the total number of bytes // in the UTF-8 sequence. static const int utf8ByteTable[256]; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; /** Expands entities in a string. Note this should not contian the tag's '<', '>', etc, or they will be transformed into entities! */ static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out ); enum { TIXML_NO_ERROR = 0, TIXML_ERROR, TIXML_ERROR_OPENING_FILE, TIXML_ERROR_PARSING_ELEMENT, TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, TIXML_ERROR_READING_ELEMENT_VALUE, TIXML_ERROR_READING_ATTRIBUTES, TIXML_ERROR_PARSING_EMPTY, TIXML_ERROR_READING_END_TAG, TIXML_ERROR_PARSING_UNKNOWN, TIXML_ERROR_PARSING_COMMENT, TIXML_ERROR_PARSING_DECLARATION, TIXML_ERROR_DOCUMENT_EMPTY, TIXML_ERROR_EMBEDDED_NULL, TIXML_ERROR_PARSING_CDATA, TIXML_ERROR_DOCUMENT_TOP_ONLY, TIXML_ERROR_STRING_COUNT }; protected: static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); inline static bool IsWhiteSpace( char c ) { return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); } inline static bool IsWhiteSpace( int c ) { if ( c < 256 ) return IsWhiteSpace( (char) c ); return false; // Again, only truly correct for English/Latin...but usually works. } #ifdef TIXML_USE_STL static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ); static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag ); #endif /* Reads an XML name into the string provided. Returns a pointer just past the last character of the name, or 0 if the function has an error. */ static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); /* Reads text. Returns a pointer past the given end tag. Wickedly complex options, but it keeps the (sensitive) code in one place. */ static const char* ReadText( const char* in, // where to start TIXML_STRING* text, // the string read bool ignoreWhiteSpace, // whether to keep the white space const char* endTag, // what ends this text bool ignoreCase, // whether to ignore case in the end tag TiXmlEncoding encoding ); // the current encoding // If an entity has been found, transform it into a character. static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); // Get a character, while interpreting entities. // The length can be from 0 to 4 bytes. inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) { assert( p ); if ( encoding == TIXML_ENCODING_UTF8 ) { *length = utf8ByteTable[ *((const unsigned char*)p) ]; assert( *length >= 0 && *length < 5 ); } else { *length = 1; } if ( *length == 1 ) { if ( *p == '&' ) return GetEntity( p, _value, length, encoding ); *_value = *p; return p+1; } else if ( *length ) { //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), // and the null terminator isn't needed for( int i=0; p[i] && i<*length; ++i ) { _value[i] = p[i]; } return p + (*length); } else { // Not valid text. return 0; } } // Return true if the next characters in the stream are any of the endTag sequences. // Ignore case only works for english, and should only be relied on when comparing // to English words: StringEqual( p, "version", true ) is fine. static bool StringEqual( const char* p, const char* endTag, bool ignoreCase, TiXmlEncoding encoding ); static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; TiXmlCursor location; /// Field containing a generic user pointer void* userData; // None of these methods are reliable for any language except English. // Good for approximation, not great for accuracy. static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); inline static int ToLower( int v, TiXmlEncoding encoding ) { if ( encoding == TIXML_ENCODING_UTF8 ) { if ( v < 128 ) return tolower( v ); return v; } else { return tolower( v ); } } static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); private: TiXmlBase( const TiXmlBase& ); // not implemented. void operator=( const TiXmlBase& base ); // not allowed. struct Entity { const char* str; unsigned int strLength; char chr; }; enum { NUM_ENTITY = 5, MAX_ENTITY_LENGTH = 6 }; static Entity entity[ NUM_ENTITY ]; static bool condenseWhiteSpace; }; /** The parent class for everything in the Document Object Model. (Except for attributes). Nodes have siblings, a parent, and children. A node can be in a document, or stand on its own. The type of a TiXmlNode can be queried, and it can be cast to its more defined type. */ class TiXmlNode : public TiXmlBase { friend class TiXmlDocument; friend class TiXmlElement; public: #ifdef TIXML_USE_STL /** An input stream operator, for every class. Tolerant of newlines and formatting, but doesn't expect them. */ friend std::istream& operator >> (std::istream& in, TiXmlNode& base); /** An output stream operator, for every class. Note that this outputs without any newlines or formatting, as opposed to Print(), which includes tabs and new lines. The operator<< and operator>> are not completely symmetric. Writing a node to a stream is very well defined. You'll get a nice stream of output, without any extra whitespace or newlines. But reading is not as well defined. (As it always is.) If you create a TiXmlElement (for example) and read that from an input stream, the text needs to define an element or junk will result. This is true of all input streams, but it's worth keeping in mind. A TiXmlDocument will read nodes until it reads a root element, and all the children of that root element. */ friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); /// Appends the XML node or attribute to a std::string. friend std::string& operator<< (std::string& out, const TiXmlNode& base ); #endif /** The types of XML nodes supported by TinyXml. (All the unsupported types are picked up by UNKNOWN.) */ enum NodeType { TINYXML_DOCUMENT, TINYXML_ELEMENT, TINYXML_COMMENT, TINYXML_UNKNOWN, TINYXML_TEXT, TINYXML_DECLARATION, TINYXML_TYPECOUNT }; virtual ~TiXmlNode(); /** The meaning of 'value' changes for the specific type of TiXmlNode. @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim The subclasses will wrap this function. */ const char *Value() const { return value.c_str (); } #ifdef TIXML_USE_STL /** Return Value() as a std::string. If you only use STL, this is more efficient than calling Value(). Only available in STL mode. */ const std::string& ValueStr() const { return value; } #endif const TIXML_STRING& ValueTStr() const { return value; } /** Changes the value of the node. Defined as: @verbatim Document: filename of the xml file Element: name of the element Comment: the comment text Unknown: the tag contents Text: the text string @endverbatim */ void SetValue(const char * _value) { value = _value;} #ifdef TIXML_USE_STL /// STL std::string form. void SetValue( const std::string& _value ) { value = _value; } #endif /// Delete all the children of this node. Does not affect 'this'. void Clear(); /// One step up the DOM. TiXmlNode* Parent() { return parent; } const TiXmlNode* Parent() const { return parent; } const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. TiXmlNode* FirstChild() { return firstChild; } const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. /// The first child of this node with the matching 'value'. Will be null if none found. TiXmlNode* FirstChild( const char * _value ) { // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) // call the method, cast the return back to non-const. return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value )); } const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. TiXmlNode* LastChild() { return lastChild; } const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. TiXmlNode* LastChild( const char * _value ) { return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value )); } #ifdef TIXML_USE_STL const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form. #endif /** An alternate way to walk the children of a node. One way to iterate over nodes is: @verbatim for( child = parent->FirstChild(); child; child = child->NextSibling() ) @endverbatim IterateChildren does the same thing with the syntax: @verbatim child = 0; while( child = parent->IterateChildren( child ) ) @endverbatim IterateChildren takes the previous child as input and finds the next one. If the previous child is null, it returns the first. IterateChildren will return null when done. */ const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; TiXmlNode* IterateChildren( const TiXmlNode* previous ) { return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) ); } /// This flavor of IterateChildren searches for children with a particular 'value' const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) { return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) ); } #ifdef TIXML_USE_STL const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. #endif /** Add a new node related to this. Adds a child past the LastChild. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child past the LastChild. NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions. @sa InsertEndChild */ TiXmlNode* LinkEndChild( TiXmlNode* addThis ); /** Add a new node related to this. Adds a child before the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); /** Add a new node related to this. Adds a child after the specified child. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); /** Replace a child of this node. Returns a pointer to the new object or NULL if an error occured. */ TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); /// Delete a child of this node. bool RemoveChild( TiXmlNode* removeThis ); /// Navigate to a sibling node. const TiXmlNode* PreviousSibling() const { return prev; } TiXmlNode* PreviousSibling() { return prev; } /// Navigate to a sibling node. const TiXmlNode* PreviousSibling( const char * ) const; TiXmlNode* PreviousSibling( const char *_prev ) { return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) ); } #ifdef TIXML_USE_STL const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. #endif /// Navigate to a sibling node. const TiXmlNode* NextSibling() const { return next; } TiXmlNode* NextSibling() { return next; } /// Navigate to a sibling node with the given 'value'. const TiXmlNode* NextSibling( const char * ) const; TiXmlNode* NextSibling( const char* _next ) { return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) ); } /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement() const; TiXmlElement* NextSiblingElement() { return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() ); } /** Convenience function to get through elements. Calls NextSibling and ToElement. Will skip all non-Element nodes. Returns 0 if there is not another element. */ const TiXmlElement* NextSiblingElement( const char * ) const; TiXmlElement* NextSiblingElement( const char *_next ) { return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) ); } #ifdef TIXML_USE_STL const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. #endif /// Convenience function to get through elements. const TiXmlElement* FirstChildElement() const; TiXmlElement* FirstChildElement() { return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() ); } /// Convenience function to get through elements. const TiXmlElement* FirstChildElement( const char * _value ) const; TiXmlElement* FirstChildElement( const char * _value ) { return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) ); } #ifdef TIXML_USE_STL const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. #endif /** Query the type (as an enumerated value, above) of this node. The possible types are: TINYXML_DOCUMENT, TINYXML_ELEMENT, TINYXML_COMMENT, TINYXML_UNKNOWN, TINYXML_TEXT, and TINYXML_DECLARATION. */ int Type() const { return type; } /** Return a pointer to the Document this node lives in. Returns null if not in a document. */ const TiXmlDocument* GetDocument() const; TiXmlDocument* GetDocument() { return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() ); } /// Returns true if this node has no children. bool NoChildren() const { return !firstChild; } virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. /** Create an exact duplicate of this node and return it. The memory must be deleted by the caller. */ virtual TiXmlNode* Clone() const = 0; /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the XML tree will be conditionally visited and the host will be called back via the TiXmlVisitor interface. This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse the XML for the callbacks, so the performance of TinyXML is unchanged by using this interface versus any other.) The interface has been based on ideas from: - http://www.saxproject.org/ - http://c2.com/cgi/wiki?HierarchicalVisitorPattern Which are both good references for "visiting". An example of using Accept(): @verbatim TiXmlPrinter printer; tinyxmlDoc.Accept( &printer ); const char* xmlcstr = printer.CStr(); @endverbatim */ virtual bool Accept( TiXmlVisitor* visitor ) const = 0; protected: TiXmlNode( NodeType _type ); // Copy to the allocated object. Shared functionality between Clone, Copy constructor, // and the assignment operator. void CopyTo( TiXmlNode* target ) const; #ifdef TIXML_USE_STL // The real work of the input operator. virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0; #endif // Figure out what is at *p, and parse it. Returns null if it is not an xml node. TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); TiXmlNode* parent; NodeType type; TiXmlNode* firstChild; TiXmlNode* lastChild; TIXML_STRING value; TiXmlNode* prev; TiXmlNode* next; private: TiXmlNode( const TiXmlNode& ); // not implemented. void operator=( const TiXmlNode& base ); // not allowed. }; /** An attribute is a name-value pair. Elements have an arbitrary number of attributes, each with a unique name. @note The attributes are not TiXmlNodes, since they are not part of the tinyXML document object model. There are other suggested ways to look at this problem. */ class TiXmlAttribute : public TiXmlBase { friend class TiXmlAttributeSet; public: /// Construct an empty attribute. TiXmlAttribute() : TiXmlBase() { document = 0; prev = next = 0; } #ifdef TIXML_USE_STL /// std::string constructor. TiXmlAttribute( const std::string& _name, const std::string& _value ) { name = _name; value = _value; document = 0; prev = next = 0; } #endif /// Construct an attribute with a name and value. TiXmlAttribute( const char * _name, const char * _value ) { name = _name; value = _value; document = 0; prev = next = 0; } const char* Name() const { return name.c_str(); } ///< Return the name of this attribute. const char* Value() const { return value.c_str(); } ///< Return the value of this attribute. #ifdef TIXML_USE_STL const std::string& ValueStr() const { return value; } ///< Return the value of this attribute. #endif int IntValue() const; ///< Return the value of this attribute, converted to an integer. double DoubleValue() const; ///< Return the value of this attribute, converted to a double. // Get the tinyxml string representation const TIXML_STRING& NameTStr() const { return name; } /** QueryIntValue examines the value string. It is an alternative to the IntValue() method with richer error checking. If the value is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. A specialized but useful call. Note that for success it returns 0, which is the opposite of almost all other TinyXml calls. */ int QueryIntValue( int* _value ) const; /// QueryDoubleValue examines the value string. See QueryIntValue(). int QueryDoubleValue( double* _value ) const; void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. void SetValue( const char* _value ) { value = _value; } ///< Set the value. void SetIntValue( int _value ); ///< Set the value from an integer. void SetDoubleValue( double _value ); ///< Set the value from a double. #ifdef TIXML_USE_STL /// STL std::string form. void SetName( const std::string& _name ) { name = _name; } /// STL std::string form. void SetValue( const std::string& _value ) { value = _value; } #endif /// Get the next sibling attribute in the DOM. Returns null at end. const TiXmlAttribute* Next() const; TiXmlAttribute* Next() { return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() ); } /// Get the previous sibling attribute in the DOM. Returns null at beginning. const TiXmlAttribute* Previous() const; TiXmlAttribute* Previous() { return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() ); } bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } /* Attribute parsing starts: first letter of the name returns: the next char after the value end quote */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); // Prints this Attribute to a FILE stream. virtual void Print( FILE* cfile, int depth ) const { Print( cfile, depth, 0 ); } void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; // [internal use] // Set the document pointer so the attribute can report errors. void SetDocument( TiXmlDocument* doc ) { document = doc; } private: TiXmlAttribute( const TiXmlAttribute& ); // not implemented. void operator=( const TiXmlAttribute& base ); // not allowed. TiXmlDocument* document; // A pointer back to a document, for error reporting. TIXML_STRING name; TIXML_STRING value; TiXmlAttribute* prev; TiXmlAttribute* next; }; /* A class used to manage a group of attributes. It is only used internally, both by the ELEMENT and the DECLARATION. The set can be changed transparent to the Element and Declaration classes that use it, but NOT transparent to the Attribute which has to implement a next() and previous() method. Which makes it a bit problematic and prevents the use of STL. This version is implemented with circular lists because: - I like circular lists - it demonstrates some independence from the (typical) doubly linked list. */ class TiXmlAttributeSet { public: TiXmlAttributeSet(); ~TiXmlAttributeSet(); void Add( TiXmlAttribute* attribute ); void Remove( TiXmlAttribute* attribute ); const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } TiXmlAttribute* Find( const char* _name ) const; TiXmlAttribute* FindOrCreate( const char* _name ); # ifdef TIXML_USE_STL TiXmlAttribute* Find( const std::string& _name ) const; TiXmlAttribute* FindOrCreate( const std::string& _name ); # endif private: //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), //*ME: this class must be also use a hidden/disabled copy-constructor !!! TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) TiXmlAttribute sentinel; }; /** The element is a container class. It has a value, the element name, and can contain other elements, text, comments, and unknowns. Elements also contain an arbitrary number of attributes. */ class TiXmlElement : public TiXmlNode { public: /// Construct an element. TiXmlElement (const char * in_value); #ifdef TIXML_USE_STL /// std::string constructor. TiXmlElement( const std::string& _value ); #endif TiXmlElement( const TiXmlElement& ); TiXmlElement& operator=( const TiXmlElement& base ); virtual ~TiXmlElement(); /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. */ const char* Attribute( const char* name ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an integer, the integer value will be put in the return 'i', if 'i' is non-null. */ const char* Attribute( const char* name, int* i ) const; /** Given an attribute name, Attribute() returns the value for the attribute of that name, or null if none exists. If the attribute exists and can be converted to an double, the double value will be put in the return 'd', if 'd' is non-null. */ const char* Attribute( const char* name, double* d ) const; /** QueryIntAttribute examines the attribute - it is an alternative to the Attribute() method with richer error checking. If the attribute is an integer, it is stored in 'value' and the call returns TIXML_SUCCESS. If it is not an integer, it returns TIXML_WRONG_TYPE. If the attribute does not exist, then TIXML_NO_ATTRIBUTE is returned. */ int QueryIntAttribute( const char* name, int* _value ) const; /// QueryUnsignedAttribute examines the attribute - see QueryIntAttribute(). int QueryUnsignedAttribute( const char* name, unsigned* _value ) const; /** QueryBoolAttribute examines the attribute - see QueryIntAttribute(). Note that '1', 'true', or 'yes' are considered true, while '0', 'false' and 'no' are considered false. */ int QueryBoolAttribute( const char* name, bool* _value ) const; /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). int QueryDoubleAttribute( const char* name, double* _value ) const; /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). int QueryFloatAttribute( const char* name, float* _value ) const { double d; int result = QueryDoubleAttribute( name, &d ); if ( result == TIXML_SUCCESS ) { *_value = (float)d; } return result; } #ifdef TIXML_USE_STL /// QueryStringAttribute examines the attribute - see QueryIntAttribute(). int QueryStringAttribute( const char* name, std::string* _value ) const { const char* cstr = Attribute( name ); if ( cstr ) { *_value = std::string( cstr ); return TIXML_SUCCESS; } return TIXML_NO_ATTRIBUTE; } /** Template form of the attribute query which will try to read the attribute into the specified type. Very easy, very powerful, but be careful to make sure to call this with the correct type. NOTE: This method doesn't work correctly for 'string' types that contain spaces. @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE */ template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; std::stringstream sstream( node->ValueStr() ); sstream >> *outValue; if ( !sstream.fail() ) return TIXML_SUCCESS; return TIXML_WRONG_TYPE; } int QueryValueAttribute( const std::string& name, std::string* outValue ) const { const TiXmlAttribute* node = attributeSet.Find( name ); if ( !node ) return TIXML_NO_ATTRIBUTE; *outValue = node->ValueStr(); return TIXML_SUCCESS; } #endif /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char* name, const char * _value ); #ifdef TIXML_USE_STL const std::string* Attribute( const std::string& name ) const; const std::string* Attribute( const std::string& name, int* i ) const; const std::string* Attribute( const std::string& name, double* d ) const; int QueryIntAttribute( const std::string& name, int* _value ) const; int QueryDoubleAttribute( const std::string& name, double* _value ) const; /// STL std::string form. void SetAttribute( const std::string& name, const std::string& _value ); ///< STL std::string form. void SetAttribute( const std::string& name, int _value ); ///< STL std::string form. void SetDoubleAttribute( const std::string& name, double value ); #endif /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetAttribute( const char * name, int value ); /** Sets an attribute of name to a given value. The attribute will be created if it does not exist, or changed if it does. */ void SetDoubleAttribute( const char * name, double value ); /** Deletes an attribute with the given name. */ void RemoveAttribute( const char * name ); #ifdef TIXML_USE_STL void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. #endif const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } /** Convenience function for easy access to the text inside an element. Although easy and concise, GetText() is limited compared to getting the TiXmlText child and accessing it directly. If the first child of 'this' is a TiXmlText, the GetText() returns the character string of the Text node, else null is returned. This is a convenient method for getting the text of simple contained text: @verbatim <foo>This is text</foo> const char* str = fooElement->GetText(); @endverbatim 'str' will be a pointer to "This is text". Note that this function can be misleading. If the element foo was created from this XML: @verbatim <foo><b>This is text</b></foo> @endverbatim then the value of str would be null. The first child node isn't a text node, it is another element. From this XML: @verbatim <foo>This is <b>text</b></foo> @endverbatim GetText() will return "This is ". WARNING: GetText() accesses a child node - don't become confused with the similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are safe type casts on the referenced node. */ const char* GetText() const; /// Creates a new Element and returns it - the returned element is a copy. virtual TiXmlNode* Clone() const; // Print the Element to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; /* Attribtue parsing starts: next char past '<' returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. /** Walk the XML tree visiting this node and all of its children. */ virtual bool Accept( TiXmlVisitor* visitor ) const; protected: void CopyTo( TiXmlElement* target ) const; void ClearThis(); // like clear, but initializes 'this' object as well // Used to be public [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); #endif /* [internal use] Reads the "value" of the element -- another element, or text. This should terminate with the current end tag. */ const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); private: TiXmlAttributeSet attributeSet; }; /** An XML comment. */ class TiXmlComment : public TiXmlNode { public: /// Constructs an empty comment. TiXmlComment() : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {} /// Construct a comment from text. TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) { SetValue( _value ); } TiXmlComment( const TiXmlComment& ); TiXmlComment& operator=( const TiXmlComment& base ); virtual ~TiXmlComment() {} /// Returns a copy of this Comment. virtual TiXmlNode* Clone() const; // Write this Comment to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; /* Attribtue parsing starts: at the ! of the !-- returns: next char past '>' */ virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. /** Walk the XML tree visiting this node and all of its children. */ virtual bool Accept( TiXmlVisitor* visitor ) const; protected: void CopyTo( TiXmlComment* target ) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); #endif // virtual void StreamOut( TIXML_OSTREAM * out ) const; private: }; /** XML text. A text node can have 2 ways to output the next. "normal" output and CDATA. It will default to the mode it was parsed from the XML file and you generally want to leave it alone, but you can change the output mode with SetCDATA() and query it with CDATA(). */ class TiXmlText : public TiXmlNode { friend class TiXmlElement; public: /** Constructor for text element. By default, it is treated as normal, encoded text. If you want it be output as a CDATA text element, set the parameter _cdata to 'true' */ TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) { SetValue( initValue ); cdata = false; } virtual ~TiXmlText() {} #ifdef TIXML_USE_STL /// Constructor. TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT) { SetValue( initValue ); cdata = false; } #endif TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TINYXML_TEXT ) { copy.CopyTo( this ); } TiXmlText& operator=( const TiXmlText& base ) { base.CopyTo( this ); return *this; } // Write this text object to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; /// Queries whether this represents text using a CDATA section. bool CDATA() const { return cdata; } /// Turns on or off a CDATA representation of text. void SetCDATA( bool _cdata ) { cdata = _cdata; } virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. /** Walk the XML tree visiting this node and all of its children. */ virtual bool Accept( TiXmlVisitor* content ) const; protected : /// [internal use] Creates a new Element and returns it. virtual TiXmlNode* Clone() const; void CopyTo( TiXmlText* target ) const; bool Blank() const; // returns true if all white space and new lines // [internal use] #ifdef TIXML_USE_STL virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); #endif private: bool cdata; // true if this should be input and output as a CDATA style text element }; /** In correct XML the declaration is the first entry in the file. @verbatim <?xml version="1.0" standalone="yes"?> @endverbatim TinyXml will happily read or write files without a declaration, however. There are 3 possible attributes to the declaration: version, encoding, and standalone. Note: In this version of the code, the attributes are handled as special cases, not generic attributes, simply because there can only be at most 3 and they are always the same. */ class TiXmlDeclaration : public TiXmlNode { public: /// Construct an empty declaration. TiXmlDeclaration() : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) {} #ifdef TIXML_USE_STL /// Constructor. TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ); #endif /// Construct. TiXmlDeclaration( const char* _version, const char* _encoding, const char* _standalone ); TiXmlDeclaration( const TiXmlDeclaration& copy ); TiXmlDeclaration& operator=( const TiXmlDeclaration& copy ); virtual ~TiXmlDeclaration() {} /// Version. Will return an empty string if none was found. const char *Version() const { return version.c_str (); } /// Encoding. Will return an empty string if none was found. const char *Encoding() const { return encoding.c_str (); } /// Is this a standalone document? const char *Standalone() const { return standalone.c_str (); } /// Creates a copy of this Declaration and returns it. virtual TiXmlNode* Clone() const; // Print this declaration to a FILE stream. virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; virtual void Print( FILE* cfile, int depth ) const { Print( cfile, depth, 0 ); } virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. /** Walk the XML tree visiting this node and all of its children. */ virtual bool Accept( TiXmlVisitor* visitor ) const; protected: void CopyTo( TiXmlDeclaration* target ) const; // used to be public #ifdef TIXML_USE_STL virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); #endif private: TIXML_STRING version; TIXML_STRING encoding; TIXML_STRING standalone; }; /** Any tag that tinyXml doesn't recognize is saved as an unknown. It is a tag of text, but should not be modified. It will be written back to the XML, unchanged, when the file is saved. DTD tags get thrown into TiXmlUnknowns. */ class TiXmlUnknown : public TiXmlNode { public: TiXmlUnknown() : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) {} virtual ~TiXmlUnknown() {} TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) { copy.CopyTo( this ); } TiXmlUnknown& operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); return *this; } /// Creates a copy of this Unknown and returns it. virtual TiXmlNode* Clone() const; // Print this Unknown to a FILE stream. virtual void Print( FILE* cfile, int depth ) const; virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. /** Walk the XML tree visiting this node and all of its children. */ virtual bool Accept( TiXmlVisitor* content ) const; protected: void CopyTo( TiXmlUnknown* target ) const; #ifdef TIXML_USE_STL virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); #endif private: }; /** Always the top level node. A document binds together all the XML pieces. It can be saved, loaded, and printed to the screen. The 'value' of a document node is the xml file name. */ class TiXmlDocument : public TiXmlNode { public: /// Create an empty document, that has no name. TiXmlDocument(); /// Create a document with a name. The name of the document is also the filename of the xml. TiXmlDocument( const char * documentName ); #ifdef TIXML_USE_STL /// Constructor. TiXmlDocument( const std::string& documentName ); #endif TiXmlDocument( const TiXmlDocument& copy ); TiXmlDocument& operator=( const TiXmlDocument& copy ); virtual ~TiXmlDocument() {} /** Load a file using the current document value. Returns true if successful. Will delete any existing document data before loading. */ bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /// Save a file using the current document value. Returns true if successful. bool SaveFile() const; /// Load a file using the given filename. Returns true if successful. bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /// Save a file using the given filename. Returns true if successful. bool SaveFile( const char * filename ) const; /** Load a file using the given FILE*. Returns true if successful. Note that this method doesn't stream - the entire object pointed at by the FILE* will be interpreted as an XML file. TinyXML doesn't stream in XML from the current file location. Streaming may be added in the future. */ bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /// Save a file using the given FILE*. Returns true if successful. bool SaveFile( FILE* ) const; #ifdef TIXML_USE_STL bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. { return LoadFile( filename.c_str(), encoding ); } bool SaveFile( const std::string& filename ) const ///< STL std::string version. { return SaveFile( filename.c_str() ); } #endif /** Parse the given null terminated block of xml data. Passing in an encoding to this method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml to use that encoding, regardless of what TinyXml might otherwise try to detect. */ virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); /** Get the root element -- the only top level element -- of the document. In well formed XML, there should only be one. TinyXml is tolerant of multiple elements at the document level. */ const TiXmlElement* RootElement() const { return FirstChildElement(); } TiXmlElement* RootElement() { return FirstChildElement(); } /** If an error occurs, Error will be set to true. Also, - The ErrorId() will contain the integer identifier of the error (not generally useful) - The ErrorDesc() method will return the name of the error. (very useful) - The ErrorRow() and ErrorCol() will return the location of the error (if known) */ bool Error() const { return error; } /// Contains a textual (english) description of the error if one occurs. const char * ErrorDesc() const { return errorDesc.c_str (); } /** Generally, you probably want the error string ( ErrorDesc() ). But if you prefer the ErrorId, this function will fetch it. */ int ErrorId() const { return errorId; } /** Returns the location (if known) of the error. The first column is column 1, and the first row is row 1. A value of 0 means the row and column wasn't applicable (memory errors, for example, have no row/column) or the parser lost the error. (An error in the error reporting, in that case.) @sa SetTabSize, Row, Column */ int ErrorRow() const { return errorLocation.row+1; } int ErrorCol() const { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) to report the correct values for row and column. It does not change the output or input in any way. By calling this method, with a tab size greater than 0, the row and column of each node and attribute is stored when the file is loaded. Very useful for tracking the DOM back in to the source file. The tab size is required for calculating the location of nodes. If not set, the default of 4 is used. The tabsize is set per document. Setting the tabsize to 0 disables row/column tracking. Note that row and column tracking is not supported when using operator>>. The tab size needs to be enabled before the parse or load. Correct usage: @verbatim TiXmlDocument doc; doc.SetTabSize( 8 ); doc.Load( "myfile.xml" ); @endverbatim @sa Row, Column */ void SetTabSize( int _tabsize ) { tabsize = _tabsize; } int TabSize() const { return tabsize; } /** If you have handled the error, it can be reset with this call. The error state is automatically cleared if you Parse a new XML block. */ void ClearError() { error = false; errorId = 0; errorDesc = ""; errorLocation.row = errorLocation.col = 0; //errorLocation.last = 0; } /** Write the document to standard out using formatted printing ("pretty print"). */ void Print() const { Print( stdout, 0 ); } /* Write the document to a string using formatted printing ("pretty print"). This will allocate a character array (new char[]) and return it as a pointer. The calling code pust call delete[] on the return char* to avoid a memory leak. */ //char* PrintToMemory() const; /// Print this Document to a FILE stream. virtual void Print( FILE* cfile, int depth = 0 ) const; // [internal use] void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. /** Walk the XML tree visiting this node and all of its children. */ virtual bool Accept( TiXmlVisitor* content ) const; protected : // [internal use] virtual TiXmlNode* Clone() const; #ifdef TIXML_USE_STL virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); #endif private: void CopyTo( TiXmlDocument* target ) const; bool error; int errorId; TIXML_STRING errorDesc; int tabsize; TiXmlCursor errorLocation; bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. }; /** A TiXmlHandle is a class that wraps a node pointer with null checks; this is an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml DOM structure. It is a separate utility class. Take an example: @verbatim <Document> <Element attributeA = "valueA"> <Child attributeB = "value1" /> <Child attributeB = "value2" /> </Element> <Document> @endverbatim Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very easy to write a *lot* of code that looks like: @verbatim TiXmlElement* root = document.FirstChildElement( "Document" ); if ( root ) { TiXmlElement* element = root->FirstChildElement( "Element" ); if ( element ) { TiXmlElement* child = element->FirstChildElement( "Child" ); if ( child ) { TiXmlElement* child2 = child->NextSiblingElement( "Child" ); if ( child2 ) { // Finally do something useful. @endverbatim And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity of such code. A TiXmlHandle checks for null pointers so it is perfectly safe and correct to use: @verbatim TiXmlHandle docHandle( &document ); TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement(); if ( child2 ) { // do something useful @endverbatim Which is MUCH more concise and useful. It is also safe to copy handles - internally they are nothing more than node pointers. @verbatim TiXmlHandle handleCopy = handle; @endverbatim What they should not be used for is iteration: @verbatim int i=0; while ( true ) { TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement(); if ( !child ) break; // do something ++i; } @endverbatim It seems reasonable, but it is in fact two embedded while loops. The Child method is a linear walk to find the element, so this code would iterate much more than it needs to. Instead, prefer: @verbatim TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).ToElement(); for( child; child; child=child->NextSiblingElement() ) { // do something } @endverbatim */ class TiXmlHandle { public: /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. TiXmlHandle( TiXmlNode* _node ) { this->node = _node; } /// Copy constructor TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } TiXmlHandle operator=( const TiXmlHandle& ref ) { if ( &ref != this ) this->node = ref.node; return *this; } /// Return a handle to the first child node. TiXmlHandle FirstChild() const; /// Return a handle to the first child node with the given name. TiXmlHandle FirstChild( const char * value ) const; /// Return a handle to the first child element. TiXmlHandle FirstChildElement() const; /// Return a handle to the first child element with the given name. TiXmlHandle FirstChildElement( const char * value ) const; /** Return a handle to the "index" child with the given name. The first child is 0, the second 1, etc. */ TiXmlHandle Child( const char* value, int index ) const; /** Return a handle to the "index" child. The first child is 0, the second 1, etc. */ TiXmlHandle Child( int index ) const; /** Return a handle to the "index" child element with the given name. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( const char* value, int index ) const; /** Return a handle to the "index" child element. The first child element is 0, the second 1, etc. Note that only TiXmlElements are indexed: other types are not counted. */ TiXmlHandle ChildElement( int index ) const; #ifdef TIXML_USE_STL TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } #endif /** Return the handle as a TiXmlNode. This may return null. */ TiXmlNode* ToNode() const { return node; } /** Return the handle as a TiXmlElement. This may return null. */ TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } /** Return the handle as a TiXmlText. This may return null. */ TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } /** Return the handle as a TiXmlUnknown. This may return null. */ TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } /** @deprecated use ToNode. Return the handle as a TiXmlNode. This may return null. */ TiXmlNode* Node() const { return ToNode(); } /** @deprecated use ToElement. Return the handle as a TiXmlElement. This may return null. */ TiXmlElement* Element() const { return ToElement(); } /** @deprecated use ToText() Return the handle as a TiXmlText. This may return null. */ TiXmlText* Text() const { return ToText(); } /** @deprecated use ToUnknown() Return the handle as a TiXmlUnknown. This may return null. */ TiXmlUnknown* Unknown() const { return ToUnknown(); } private: TiXmlNode* node; }; /** Print to memory functionality. The TiXmlPrinter is useful when you need to: -# Print to memory (especially in non-STL mode) -# Control formatting (line endings, etc.) When constructed, the TiXmlPrinter is in its default "pretty printing" mode. Before calling Accept() you can call methods to control the printing of the XML document. After TiXmlNode::Accept() is called, the printed document can be accessed via the CStr(), Str(), and Size() methods. TiXmlPrinter uses the Visitor API. @verbatim TiXmlPrinter printer; printer.SetIndent( "\t" ); doc.Accept( &printer ); fprintf( stdout, "%s", printer.CStr() ); @endverbatim */ class TiXmlPrinter : public TiXmlVisitor { public: TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ), buffer(), indent( " " ), lineBreak( "\n" ) {} virtual bool VisitEnter( const TiXmlDocument& doc ); virtual bool VisitExit( const TiXmlDocument& doc ); virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ); virtual bool VisitExit( const TiXmlElement& element ); virtual bool Visit( const TiXmlDeclaration& declaration ); virtual bool Visit( const TiXmlText& text ); virtual bool Visit( const TiXmlComment& comment ); virtual bool Visit( const TiXmlUnknown& unknown ); /** Set the indent characters for printing. By default 4 spaces but tab (\t) is also useful, or null/empty string for no indentation. */ void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; } /// Query the indention string. const char* Indent() { return indent.c_str(); } /** Set the line breaking string. By default set to newline (\n). Some operating systems prefer other characters, or can be set to the null/empty string for no indenation. */ void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; } /// Query the current line breaking string. const char* LineBreak() { return lineBreak.c_str(); } /** Switch over to "stream printing" which is the most dense formatting without linebreaks. Common when the XML is needed for network transmission. */ void SetStreamPrinting() { indent = ""; lineBreak = ""; } /// Return the result. const char* CStr() { return buffer.c_str(); } /// Return the length of the result string. size_t Size() { return buffer.size(); } #ifdef TIXML_USE_STL /// Return the result. const std::string& Str() { return buffer; } #endif private: void DoIndent() { for( int i=0; i<depth; ++i ) buffer += indent; } void DoLineBreak() { buffer += lineBreak; } int depth; bool simpleTextPrint; TIXML_STRING buffer; TIXML_STRING indent; TIXML_STRING lineBreak; }; #ifdef _MSC_VER #pragma warning( pop ) #endif #endif
[ "root@localhost.localdomain" ]
root@localhost.localdomain
1b5479c9bca6e9ef628ba3441d63cd107bb82757
27974ef06083b306028ade82a6c174377ab649fd
/period/freshman/contest/Week 3/I.cpp
8308a258ebbb6bcbd8f58d18455cdb4cd3ad740f
[]
no_license
lightyears1998/a-gzhu-coder
6ba7fe23f663ee538c162927cfecb57e20bc0dbc
b882a2e8395155db0a57d59e7c5899386c5eb717
refs/heads/master
2021-06-05T05:33:14.988053
2020-05-23T12:52:57
2020-05-23T12:52:57
100,114,337
14
2
null
null
null
null
UTF-8
C++
false
false
299
cpp
#include <bits/stdc++.h> using namespace std; int main() { string s; while (getline(cin, s)) { if (s == "#") break; int sum = 0; for (unsigned i=0; i<s.size(); ++i) { if (isalpha(s[i])) sum += (i+1)*(s[i]-'A'+1); else continue; } cout << sum << endl; } }
[ "lightyears1998@hotmail.com" ]
lightyears1998@hotmail.com
e86075a33bbc78bb3f75b685101273ff2f283314
2576dfefe11dc4eb2588bf7872ebecbc64823833
/include/SPcSteppingMessenger.hh
dc8ab87cabac977294075a8442c495110fcd96c9
[]
no_license
jilic/spacal
8278df8b41f3b7efe65c398622ee49bcc207bf92
413750533857563c9d627666684ed622aac76a1d
refs/heads/master
2021-01-01T05:18:20.425457
2015-02-18T22:41:19
2015-02-18T22:41:19
32,726,429
0
0
null
null
null
null
UTF-8
C++
false
false
640
hh
/* @author Jelena Ilic @mail jelenailic.sk@gmail.com @date Summer 2014 */ #ifndef SPcSteppingMessenger_h #define SPcSteppingMessenger_h 1 #include "G4UImessenger.hh" #include "globals.hh" class SPcSteppingAction; class G4UIcmdWithAnInteger; class G4UIcmdWithABool; class G4UIcmdWithADoubleAndUnit; class SPcSteppingMessenger: public G4UImessenger { public: SPcSteppingMessenger(SPcSteppingAction*); virtual ~SPcSteppingMessenger(); virtual void SetNewValue(G4UIcommand*, G4String); private: SPcSteppingAction* fstep; G4UIcmdWithABool* trackOpticalCommand; G4UIcmdWithADoubleAndUnit* fcutOffCmd; }; #endif
[ "jelenailic.sk@7ba4f6a3-0c5a-dc19-1ee9-c1316467136b" ]
jelenailic.sk@7ba4f6a3-0c5a-dc19-1ee9-c1316467136b
f25229c9f157262511e392464824f7ace0ffd36e
2ccb99e0b35b58622c5a0be2a698ebda3ab29dec
/gfx/skia/skia/src/effects/SkLightingImageFilter.cpp
f701b4c8945952f619404479d11d226574b51bc9
[ "BSD-3-Clause" ]
permissive
roytam1/palemoon27
f436d4a3688fd14ea5423cbcaf16c4539b88781f
685d46ffdaee14705ea40e7ac57c4c11e8f31cd0
refs/heads/master
2023-08-20T10:11:13.367377
2023-08-17T07:28:43
2023-08-17T07:28:43
142,234,965
61
16
NOASSERTION
2022-03-30T07:54:03
2018-07-25T02:10:02
null
UTF-8
C++
false
false
87,541
cpp
/* * Copyright 2012 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkLightingImageFilter.h" #include "SkBitmap.h" #include "SkColorPriv.h" #include "SkDevice.h" #include "SkPoint3.h" #include "SkReadBuffer.h" #include "SkTypes.h" #include "SkWriteBuffer.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrDrawContext.h" #include "GrFragmentProcessor.h" #include "GrInvariantOutput.h" #include "GrPaint.h" #include "SkGr.h" #include "effects/GrSingleTextureEffect.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramDataManager.h" #include "glsl/GrGLSLUniformHandler.h" class GrGLDiffuseLightingEffect; class GrGLSpecularLightingEffect; // For brevity typedef GrGLSLProgramDataManager::UniformHandle UniformHandle; #endif namespace { const SkScalar gOneThird = SkIntToScalar(1) / 3; const SkScalar gTwoThirds = SkIntToScalar(2) / 3; const SkScalar gOneHalf = 0.5f; const SkScalar gOneQuarter = 0.25f; #if SK_SUPPORT_GPU void setUniformPoint3(const GrGLSLProgramDataManager& pdman, UniformHandle uni, const SkPoint3& point) { GR_STATIC_ASSERT(sizeof(SkPoint3) == 3 * sizeof(float)); pdman.set3fv(uni, 1, &point.fX); } void setUniformNormal3(const GrGLSLProgramDataManager& pdman, UniformHandle uni, const SkPoint3& point) { setUniformPoint3(pdman, uni, point); } #endif // Shift matrix components to the left, as we advance pixels to the right. inline void shiftMatrixLeft(int m[9]) { m[0] = m[1]; m[3] = m[4]; m[6] = m[7]; m[1] = m[2]; m[4] = m[5]; m[7] = m[8]; } static inline void fast_normalize(SkPoint3* vector) { // add a tiny bit so we don't have to worry about divide-by-zero SkScalar magSq = vector->dot(*vector) + SK_ScalarNearlyZero; SkScalar scale = sk_float_rsqrt(magSq); vector->fX *= scale; vector->fY *= scale; vector->fZ *= scale; } class DiffuseLightingType { public: DiffuseLightingType(SkScalar kd) : fKD(kd) {} SkPMColor light(const SkPoint3& normal, const SkPoint3& surfaceTolight, const SkPoint3& lightColor) const { SkScalar colorScale = SkScalarMul(fKD, normal.dot(surfaceTolight)); colorScale = SkScalarClampMax(colorScale, SK_Scalar1); SkPoint3 color = lightColor.makeScale(colorScale); return SkPackARGB32(255, SkClampMax(SkScalarRoundToInt(color.fX), 255), SkClampMax(SkScalarRoundToInt(color.fY), 255), SkClampMax(SkScalarRoundToInt(color.fZ), 255)); } private: SkScalar fKD; }; static SkScalar max_component(const SkPoint3& p) { return p.x() > p.y() ? (p.x() > p.z() ? p.x() : p.z()) : (p.y() > p.z() ? p.y() : p.z()); } class SpecularLightingType { public: SpecularLightingType(SkScalar ks, SkScalar shininess) : fKS(ks), fShininess(shininess) {} SkPMColor light(const SkPoint3& normal, const SkPoint3& surfaceTolight, const SkPoint3& lightColor) const { SkPoint3 halfDir(surfaceTolight); halfDir.fZ += SK_Scalar1; // eye position is always (0, 0, 1) fast_normalize(&halfDir); SkScalar colorScale = SkScalarMul(fKS, SkScalarPow(normal.dot(halfDir), fShininess)); colorScale = SkScalarClampMax(colorScale, SK_Scalar1); SkPoint3 color = lightColor.makeScale(colorScale); return SkPackARGB32(SkClampMax(SkScalarRoundToInt(max_component(color)), 255), SkClampMax(SkScalarRoundToInt(color.fX), 255), SkClampMax(SkScalarRoundToInt(color.fY), 255), SkClampMax(SkScalarRoundToInt(color.fZ), 255)); } private: SkScalar fKS; SkScalar fShininess; }; inline SkScalar sobel(int a, int b, int c, int d, int e, int f, SkScalar scale) { return SkScalarMul(SkIntToScalar(-a + b - 2 * c + 2 * d -e + f), scale); } inline SkPoint3 pointToNormal(SkScalar x, SkScalar y, SkScalar surfaceScale) { SkPoint3 vector = SkPoint3::Make(SkScalarMul(-x, surfaceScale), SkScalarMul(-y, surfaceScale), SK_Scalar1); fast_normalize(&vector); return vector; } inline SkPoint3 topLeftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(0, 0, m[4], m[5], m[7], m[8], gTwoThirds), sobel(0, 0, m[4], m[7], m[5], m[8], gTwoThirds), surfaceScale); } inline SkPoint3 topNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel( 0, 0, m[3], m[5], m[6], m[8], gOneThird), sobel(m[3], m[6], m[4], m[7], m[5], m[8], gOneHalf), surfaceScale); } inline SkPoint3 topRightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel( 0, 0, m[3], m[4], m[6], m[7], gTwoThirds), sobel(m[3], m[6], m[4], m[7], 0, 0, gTwoThirds), surfaceScale); } inline SkPoint3 leftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[1], m[2], m[4], m[5], m[7], m[8], gOneHalf), sobel( 0, 0, m[1], m[7], m[2], m[8], gOneThird), surfaceScale); } inline SkPoint3 interiorNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[2], m[3], m[5], m[6], m[8], gOneQuarter), sobel(m[0], m[6], m[1], m[7], m[2], m[8], gOneQuarter), surfaceScale); } inline SkPoint3 rightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[1], m[3], m[4], m[6], m[7], gOneHalf), sobel(m[0], m[6], m[1], m[7], 0, 0, gOneThird), surfaceScale); } inline SkPoint3 bottomLeftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[1], m[2], m[4], m[5], 0, 0, gTwoThirds), sobel( 0, 0, m[1], m[4], m[2], m[5], gTwoThirds), surfaceScale); } inline SkPoint3 bottomNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[2], m[3], m[5], 0, 0, gOneThird), sobel(m[0], m[3], m[1], m[4], m[2], m[5], gOneHalf), surfaceScale); } inline SkPoint3 bottomRightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[1], m[3], m[4], 0, 0, gTwoThirds), sobel(m[0], m[3], m[1], m[4], 0, 0, gTwoThirds), surfaceScale); } template <class LightingType, class LightType> void lightBitmap(const LightingType& lightingType, const SkImageFilterLight* light, const SkBitmap& src, SkBitmap* dst, SkScalar surfaceScale, const SkIRect& bounds) { SkASSERT(dst->width() == bounds.width() && dst->height() == bounds.height()); const LightType* l = static_cast<const LightType*>(light); int left = bounds.left(), right = bounds.right(); int bottom = bounds.bottom(); int y = bounds.top(); SkPMColor* dptr = dst->getAddr32(0, 0); { int x = left; const SkPMColor* row1 = src.getAddr32(x, y); const SkPMColor* row2 = src.getAddr32(x, y + 1); int m[9]; m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); m[7] = SkGetPackedA32(*row2++); m[8] = SkGetPackedA32(*row2++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topLeftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[5] = SkGetPackedA32(*row1++); m[8] = SkGetPackedA32(*row2++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topRightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } for (++y; y < bottom - 1; ++y) { int x = left; const SkPMColor* row0 = src.getAddr32(x, y - 1); const SkPMColor* row1 = src.getAddr32(x, y); const SkPMColor* row2 = src.getAddr32(x, y + 1); int m[9]; m[1] = SkGetPackedA32(*row0++); m[2] = SkGetPackedA32(*row0++); m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); m[7] = SkGetPackedA32(*row2++); m[8] = SkGetPackedA32(*row2++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(leftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[2] = SkGetPackedA32(*row0++); m[5] = SkGetPackedA32(*row1++); m[8] = SkGetPackedA32(*row2++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(interiorNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(rightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } { int x = left; const SkPMColor* row0 = src.getAddr32(x, bottom - 2); const SkPMColor* row1 = src.getAddr32(x, bottom - 1); int m[9]; m[1] = SkGetPackedA32(*row0++); m[2] = SkGetPackedA32(*row0++); m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomLeftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[2] = SkGetPackedA32(*row0++); m[5] = SkGetPackedA32(*row1++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomRightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } } SkPoint3 readPoint3(SkReadBuffer& buffer) { SkPoint3 point; point.fX = buffer.readScalar(); point.fY = buffer.readScalar(); point.fZ = buffer.readScalar(); buffer.validate(SkScalarIsFinite(point.fX) && SkScalarIsFinite(point.fY) && SkScalarIsFinite(point.fZ)); return point; }; void writePoint3(const SkPoint3& point, SkWriteBuffer& buffer) { buffer.writeScalar(point.fX); buffer.writeScalar(point.fY); buffer.writeScalar(point.fZ); }; enum BoundaryMode { kTopLeft_BoundaryMode, kTop_BoundaryMode, kTopRight_BoundaryMode, kLeft_BoundaryMode, kInterior_BoundaryMode, kRight_BoundaryMode, kBottomLeft_BoundaryMode, kBottom_BoundaryMode, kBottomRight_BoundaryMode, kBoundaryModeCount, }; class SkLightingImageFilterInternal : public SkLightingImageFilter { protected: SkLightingImageFilterInternal(SkImageFilterLight* light, SkScalar surfaceScale, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect) {} #if SK_SUPPORT_GPU bool canFilterImageGPU() const override { return true; } bool filterImageGPU(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; virtual GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode boundaryMode) const = 0; #endif private: #if SK_SUPPORT_GPU void drawRect(GrDrawContext* drawContext, GrTexture* src, const SkMatrix& matrix, const GrClip& clip, const SkRect& dstRect, BoundaryMode boundaryMode, const SkIRect& bounds) const; #endif typedef SkLightingImageFilter INHERITED; }; #if SK_SUPPORT_GPU void SkLightingImageFilterInternal::drawRect(GrDrawContext* drawContext, GrTexture* src, const SkMatrix& matrix, const GrClip& clip, const SkRect& dstRect, BoundaryMode boundaryMode, const SkIRect& bounds) const { SkRect srcRect = dstRect.makeOffset(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y())); GrPaint paint; GrFragmentProcessor* fp = this->getFragmentProcessor(src, matrix, bounds, boundaryMode); paint.addColorFragmentProcessor(fp)->unref(); paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode); drawContext->fillRectToRect(clip, paint, SkMatrix::I(), dstRect, srcRect); } bool SkLightingImageFilterInternal::filterImageGPU(Proxy* proxy, const SkBitmap& src, const Context& ctx, SkBitmap* result, SkIPoint* offset) const { SkBitmap input = src; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInputGPU(0, proxy, src, ctx, &input, &srcOffset)) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, input, &srcOffset, &bounds, &input)) { return false; } SkRect dstRect = SkRect::MakeWH(SkIntToScalar(bounds.width()), SkIntToScalar(bounds.height())); GrTexture* srcTexture = input.getTexture(); GrContext* context = srcTexture->getContext(); GrSurfaceDesc desc; desc.fFlags = kRenderTarget_GrSurfaceFlag, desc.fWidth = bounds.width(); desc.fHeight = bounds.height(); desc.fConfig = kRGBA_8888_GrPixelConfig; SkAutoTUnref<GrTexture> dst(context->textureProvider()->createApproxTexture(desc)); if (!dst) { return false; } // setup new clip GrClip clip(dstRect); offset->fX = bounds.left(); offset->fY = bounds.top(); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top())); bounds.offset(-srcOffset); SkRect topLeft = SkRect::MakeXYWH(0, 0, 1, 1); SkRect top = SkRect::MakeXYWH(1, 0, dstRect.width() - 2, 1); SkRect topRight = SkRect::MakeXYWH(dstRect.width() - 1, 0, 1, 1); SkRect left = SkRect::MakeXYWH(0, 1, 1, dstRect.height() - 2); SkRect interior = dstRect.makeInset(1, 1); SkRect right = SkRect::MakeXYWH(dstRect.width() - 1, 1, 1, dstRect.height() - 2); SkRect bottomLeft = SkRect::MakeXYWH(0, dstRect.height() - 1, 1, 1); SkRect bottom = SkRect::MakeXYWH(1, dstRect.height() - 1, dstRect.width() - 2, 1); SkRect bottomRight = SkRect::MakeXYWH(dstRect.width() - 1, dstRect.height() - 1, 1, 1); SkAutoTUnref<GrDrawContext> drawContext(context->drawContext(dst->asRenderTarget())); if (!drawContext) { return false; } this->drawRect(drawContext, srcTexture, matrix, clip, topLeft, kTopLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, top, kTop_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, topRight, kTopRight_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, left, kLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, interior, kInterior_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, right, kRight_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottomLeft, kBottomLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottom, kBottom_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottomRight, kBottomRight_BoundaryMode, bounds); GrWrapTextureInBitmap(dst, bounds.width(), bounds.height(), false, result); return true; } #endif class SkDiffuseLightingImageFilter : public SkLightingImageFilterInternal { public: static SkImageFilter* Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter*, const CropRect*); SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkDiffuseLightingImageFilter) SkScalar kd() const { return fKD; } protected: SkDiffuseLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect); void flatten(SkWriteBuffer& buffer) const override; bool onFilterImage(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; #if SK_SUPPORT_GPU GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode) const override; #endif private: friend class SkLightingImageFilter; typedef SkLightingImageFilterInternal INHERITED; SkScalar fKD; }; class SkSpecularLightingImageFilter : public SkLightingImageFilterInternal { public: static SkImageFilter* Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter*, const CropRect*); SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkSpecularLightingImageFilter) SkScalar ks() const { return fKS; } SkScalar shininess() const { return fShininess; } protected: SkSpecularLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect*); void flatten(SkWriteBuffer& buffer) const override; bool onFilterImage(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; #if SK_SUPPORT_GPU GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode) const override; #endif private: SkScalar fKS; SkScalar fShininess; friend class SkLightingImageFilter; typedef SkLightingImageFilterInternal INHERITED; }; #if SK_SUPPORT_GPU class GrLightingEffect : public GrSingleTextureEffect { public: GrLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, BoundaryMode boundaryMode); ~GrLightingEffect() override; const SkImageFilterLight* light() const { return fLight; } SkScalar surfaceScale() const { return fSurfaceScale; } const SkMatrix& filterMatrix() const { return fFilterMatrix; } BoundaryMode boundaryMode() const { return fBoundaryMode; } protected: bool onIsEqual(const GrFragmentProcessor&) const override; void onComputeInvariantOutput(GrInvariantOutput* inout) const override { // lighting shaders are complicated. We just throw up our hands. inout->mulByUnknownFourComponents(); } private: const SkImageFilterLight* fLight; SkScalar fSurfaceScale; SkMatrix fFilterMatrix; BoundaryMode fBoundaryMode; typedef GrSingleTextureEffect INHERITED; }; class GrDiffuseLightingEffect : public GrLightingEffect { public: static GrFragmentProcessor* Create(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode) { return new GrDiffuseLightingEffect(texture, light, surfaceScale, matrix, kd, boundaryMode); } const char* name() const override { return "DiffuseLighting"; } SkScalar kd() const { return fKD; } private: GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override; bool onIsEqual(const GrFragmentProcessor&) const override; GrDiffuseLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode); GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrLightingEffect INHERITED; SkScalar fKD; }; class GrSpecularLightingEffect : public GrLightingEffect { public: static GrFragmentProcessor* Create(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode) { return new GrSpecularLightingEffect(texture, light, surfaceScale, matrix, ks, shininess, boundaryMode); } const char* name() const override { return "SpecularLighting"; } GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; SkScalar ks() const { return fKS; } SkScalar shininess() const { return fShininess; } private: void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override; bool onIsEqual(const GrFragmentProcessor&) const override; GrSpecularLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode); GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrLightingEffect INHERITED; SkScalar fKS; SkScalar fShininess; }; /////////////////////////////////////////////////////////////////////////////// class GrGLLight { public: virtual ~GrGLLight() {} /** * This is called by GrGLLightingEffect::emitCode() before either of the two virtual functions * below. It adds a vec3f uniform visible in the FS that represents the constant light color. */ void emitLightColorUniform(GrGLSLUniformHandler*); /** * These two functions are called from GrGLLightingEffect's emitCode() function. * emitSurfaceToLight places an expression in param out that is the vector from the surface to * the light. The expression will be used in the FS. emitLightColor writes an expression into * the FS that is the color of the light. Either function may add functions and/or uniforms to * the FS. The default of emitLightColor appends the name of the constant light color uniform * and so this function only needs to be overridden if the light color varies spatially. */ virtual void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) = 0; virtual void emitLightColor(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char *surfaceToLight); // This is called from GrGLLightingEffect's setData(). Subclasses of GrGLLight must call // INHERITED::setData(). virtual void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const; protected: /** * Gets the constant light color uniform. Subclasses can use this in their emitLightColor * function. */ UniformHandle lightColorUni() const { return fColorUni; } private: UniformHandle fColorUni; typedef SkRefCnt INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class GrGLDistantLight : public GrGLLight { public: virtual ~GrGLDistantLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; private: typedef GrGLLight INHERITED; UniformHandle fDirectionUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLPointLight : public GrGLLight { public: virtual ~GrGLPointLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; private: typedef GrGLLight INHERITED; UniformHandle fLocationUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLSpotLight : public GrGLLight { public: virtual ~GrGLSpotLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; void emitLightColor(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char *surfaceToLight) override; private: typedef GrGLLight INHERITED; SkString fLightColorFunc; UniformHandle fLocationUni; UniformHandle fExponentUni; UniformHandle fCosOuterConeAngleUni; UniformHandle fCosInnerConeAngleUni; UniformHandle fConeScaleUni; UniformHandle fSUni; }; #else class GrGLLight; #endif }; /////////////////////////////////////////////////////////////////////////////// class SkImageFilterLight : public SkRefCnt { public: enum LightType { kDistant_LightType, kPoint_LightType, kSpot_LightType, }; virtual LightType type() const = 0; const SkPoint3& color() const { return fColor; } virtual GrGLLight* createGLLight() const = 0; virtual bool isEqual(const SkImageFilterLight& other) const { return fColor == other.fColor; } // Called to know whether the generated GrGLLight will require access to the fragment position. virtual bool requiresFragmentPosition() const = 0; virtual SkImageFilterLight* transform(const SkMatrix& matrix) const = 0; // Defined below SkLight's subclasses. void flattenLight(SkWriteBuffer& buffer) const; static SkImageFilterLight* UnflattenLight(SkReadBuffer& buffer); protected: SkImageFilterLight(SkColor color) { fColor = SkPoint3::Make(SkIntToScalar(SkColorGetR(color)), SkIntToScalar(SkColorGetG(color)), SkIntToScalar(SkColorGetB(color))); } SkImageFilterLight(const SkPoint3& color) : fColor(color) {} SkImageFilterLight(SkReadBuffer& buffer) { fColor = readPoint3(buffer); } virtual void onFlattenLight(SkWriteBuffer& buffer) const = 0; private: typedef SkRefCnt INHERITED; SkPoint3 fColor; }; /////////////////////////////////////////////////////////////////////////////// class SkDistantLight : public SkImageFilterLight { public: SkDistantLight(const SkPoint3& direction, SkColor color) : INHERITED(color), fDirection(direction) { } SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { return fDirection; }; const SkPoint3& lightColor(const SkPoint3&) const { return this->color(); } LightType type() const override { return kDistant_LightType; } const SkPoint3& direction() const { return fDirection; } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLDistantLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return false; } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kDistant_LightType) { return false; } const SkDistantLight& o = static_cast<const SkDistantLight&>(other); return INHERITED::isEqual(other) && fDirection == o.fDirection; } SkDistantLight(SkReadBuffer& buffer) : INHERITED(buffer) { fDirection = readPoint3(buffer); } protected: SkDistantLight(const SkPoint3& direction, const SkPoint3& color) : INHERITED(color), fDirection(direction) { } SkImageFilterLight* transform(const SkMatrix& matrix) const override { return new SkDistantLight(direction(), color()); } void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fDirection, buffer); } private: SkPoint3 fDirection; typedef SkImageFilterLight INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class SkPointLight : public SkImageFilterLight { public: SkPointLight(const SkPoint3& location, SkColor color) : INHERITED(color), fLocation(location) {} SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { SkPoint3 direction = SkPoint3::Make(fLocation.fX - SkIntToScalar(x), fLocation.fY - SkIntToScalar(y), fLocation.fZ - SkScalarMul(SkIntToScalar(z), surfaceScale)); fast_normalize(&direction); return direction; }; const SkPoint3& lightColor(const SkPoint3&) const { return this->color(); } LightType type() const override { return kPoint_LightType; } const SkPoint3& location() const { return fLocation; } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLPointLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return true; } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kPoint_LightType) { return false; } const SkPointLight& o = static_cast<const SkPointLight&>(other); return INHERITED::isEqual(other) && fLocation == o.fLocation; } SkImageFilterLight* transform(const SkMatrix& matrix) const override { SkPoint location2 = SkPoint::Make(fLocation.fX, fLocation.fY); matrix.mapPoints(&location2, 1); // Use X scale and Y scale on Z and average the result SkPoint locationZ = SkPoint::Make(fLocation.fZ, fLocation.fZ); matrix.mapVectors(&locationZ, 1); SkPoint3 location = SkPoint3::Make(location2.fX, location2.fY, SkScalarAve(locationZ.fX, locationZ.fY)); return new SkPointLight(location, color()); } SkPointLight(SkReadBuffer& buffer) : INHERITED(buffer) { fLocation = readPoint3(buffer); } protected: SkPointLight(const SkPoint3& location, const SkPoint3& color) : INHERITED(color), fLocation(location) {} void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fLocation, buffer); } private: SkPoint3 fLocation; typedef SkImageFilterLight INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class SkSpotLight : public SkImageFilterLight { public: SkSpotLight(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor color) : INHERITED(color), fLocation(location), fTarget(target), fSpecularExponent(SkScalarPin(specularExponent, kSpecularExponentMin, kSpecularExponentMax)) { fS = target - location; fast_normalize(&fS); fCosOuterConeAngle = SkScalarCos(SkDegreesToRadians(cutoffAngle)); const SkScalar antiAliasThreshold = 0.016f; fCosInnerConeAngle = fCosOuterConeAngle + antiAliasThreshold; fConeScale = SkScalarInvert(antiAliasThreshold); } SkImageFilterLight* transform(const SkMatrix& matrix) const override { SkPoint location2 = SkPoint::Make(fLocation.fX, fLocation.fY); matrix.mapPoints(&location2, 1); // Use X scale and Y scale on Z and average the result SkPoint locationZ = SkPoint::Make(fLocation.fZ, fLocation.fZ); matrix.mapVectors(&locationZ, 1); SkPoint3 location = SkPoint3::Make(location2.fX, location2.fY, SkScalarAve(locationZ.fX, locationZ.fY)); SkPoint target2 = SkPoint::Make(fTarget.fX, fTarget.fY); matrix.mapPoints(&target2, 1); SkPoint targetZ = SkPoint::Make(fTarget.fZ, fTarget.fZ); matrix.mapVectors(&targetZ, 1); SkPoint3 target = SkPoint3::Make(target2.fX, target2.fY, SkScalarAve(targetZ.fX, targetZ.fY)); SkPoint3 s = target - location; fast_normalize(&s); return new SkSpotLight(location, target, fSpecularExponent, fCosOuterConeAngle, fCosInnerConeAngle, fConeScale, s, color()); } SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { SkPoint3 direction = SkPoint3::Make(fLocation.fX - SkIntToScalar(x), fLocation.fY - SkIntToScalar(y), fLocation.fZ - SkScalarMul(SkIntToScalar(z), surfaceScale)); fast_normalize(&direction); return direction; }; SkPoint3 lightColor(const SkPoint3& surfaceToLight) const { SkScalar cosAngle = -surfaceToLight.dot(fS); SkScalar scale = 0; if (cosAngle >= fCosOuterConeAngle) { scale = SkScalarPow(cosAngle, fSpecularExponent); if (cosAngle < fCosInnerConeAngle) { scale = SkScalarMul(scale, cosAngle - fCosOuterConeAngle); scale *= fConeScale; } } return this->color().makeScale(scale); } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLSpotLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return true; } LightType type() const override { return kSpot_LightType; } const SkPoint3& location() const { return fLocation; } const SkPoint3& target() const { return fTarget; } SkScalar specularExponent() const { return fSpecularExponent; } SkScalar cosInnerConeAngle() const { return fCosInnerConeAngle; } SkScalar cosOuterConeAngle() const { return fCosOuterConeAngle; } SkScalar coneScale() const { return fConeScale; } const SkPoint3& s() const { return fS; } SkSpotLight(SkReadBuffer& buffer) : INHERITED(buffer) { fLocation = readPoint3(buffer); fTarget = readPoint3(buffer); fSpecularExponent = buffer.readScalar(); fCosOuterConeAngle = buffer.readScalar(); fCosInnerConeAngle = buffer.readScalar(); fConeScale = buffer.readScalar(); fS = readPoint3(buffer); buffer.validate(SkScalarIsFinite(fSpecularExponent) && SkScalarIsFinite(fCosOuterConeAngle) && SkScalarIsFinite(fCosInnerConeAngle) && SkScalarIsFinite(fConeScale)); } protected: SkSpotLight(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cosOuterConeAngle, SkScalar cosInnerConeAngle, SkScalar coneScale, const SkPoint3& s, const SkPoint3& color) : INHERITED(color), fLocation(location), fTarget(target), fSpecularExponent(specularExponent), fCosOuterConeAngle(cosOuterConeAngle), fCosInnerConeAngle(cosInnerConeAngle), fConeScale(coneScale), fS(s) { } void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fLocation, buffer); writePoint3(fTarget, buffer); buffer.writeScalar(fSpecularExponent); buffer.writeScalar(fCosOuterConeAngle); buffer.writeScalar(fCosInnerConeAngle); buffer.writeScalar(fConeScale); writePoint3(fS, buffer); } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kSpot_LightType) { return false; } const SkSpotLight& o = static_cast<const SkSpotLight&>(other); return INHERITED::isEqual(other) && fLocation == o.fLocation && fTarget == o.fTarget && fSpecularExponent == o.fSpecularExponent && fCosOuterConeAngle == o.fCosOuterConeAngle; } private: static const SkScalar kSpecularExponentMin; static const SkScalar kSpecularExponentMax; SkPoint3 fLocation; SkPoint3 fTarget; SkScalar fSpecularExponent; SkScalar fCosOuterConeAngle; SkScalar fCosInnerConeAngle; SkScalar fConeScale; SkPoint3 fS; typedef SkImageFilterLight INHERITED; }; // According to the spec, the specular term should be in the range [1, 128] : // http://www.w3.org/TR/SVG/filters.html#feSpecularLightingSpecularExponentAttribute const SkScalar SkSpotLight::kSpecularExponentMin = 1.0f; const SkScalar SkSpotLight::kSpecularExponentMax = 128.0f; /////////////////////////////////////////////////////////////////////////////// void SkImageFilterLight::flattenLight(SkWriteBuffer& buffer) const { // Write type first, then baseclass, then subclass. buffer.writeInt(this->type()); writePoint3(fColor, buffer); this->onFlattenLight(buffer); } /*static*/ SkImageFilterLight* SkImageFilterLight::UnflattenLight(SkReadBuffer& buffer) { // Read type first. const SkImageFilterLight::LightType type = (SkImageFilterLight::LightType)buffer.readInt(); switch (type) { // Each of these constructors must first call SkLight's, so we'll read the baseclass // then subclass, same order as flattenLight. case SkImageFilterLight::kDistant_LightType: return new SkDistantLight(buffer); case SkImageFilterLight::kPoint_LightType: return new SkPointLight(buffer); case SkImageFilterLight::kSpot_LightType: return new SkSpotLight(buffer); default: SkDEBUGFAIL("Unknown LightType."); buffer.validate(false); return nullptr; } } /////////////////////////////////////////////////////////////////////////////// SkLightingImageFilter::SkLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkImageFilter* input, const CropRect* cropRect) : INHERITED(1, &input, cropRect) , fLight(SkRef(light)) , fSurfaceScale(surfaceScale / 255) {} SkImageFilter* SkLightingImageFilter::CreateDistantLitDiffuse(const SkPoint3& direction, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkDistantLight(direction, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreatePointLitDiffuse(const SkPoint3& location, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkPointLight(location, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateSpotLitDiffuse(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light( new SkSpotLight(location, target, specularExponent, cutoffAngle, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateDistantLitSpecular(const SkPoint3& direction, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkDistantLight(direction, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreatePointLitSpecular(const SkPoint3& location, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkPointLight(location, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateSpotLitSpecular(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light( new SkSpotLight(location, target, specularExponent, cutoffAngle, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkLightingImageFilter::~SkLightingImageFilter() {} void SkLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); fLight->flattenLight(buffer); buffer.writeScalar(fSurfaceScale * 255); } /////////////////////////////////////////////////////////////////////////////// SkImageFilter* SkDiffuseLightingImageFilter::Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { if (nullptr == light) { return nullptr; } if (!SkScalarIsFinite(surfaceScale) || !SkScalarIsFinite(kd)) { return nullptr; } // According to the spec, kd can be any non-negative number : // http://www.w3.org/TR/SVG/filters.html#feDiffuseLightingElement if (kd < 0) { return nullptr; } return new SkDiffuseLightingImageFilter(light, surfaceScale, kd, input, cropRect); } SkDiffuseLightingImageFilter::SkDiffuseLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect), fKD(kd) { } SkFlattenable* SkDiffuseLightingImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); SkAutoTUnref<SkImageFilterLight> light(SkImageFilterLight::UnflattenLight(buffer)); SkScalar surfaceScale = buffer.readScalar(); SkScalar kd = buffer.readScalar(); return Create(light, surfaceScale, kd, common.getInput(0), &common.cropRect()); } void SkDiffuseLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fKD); } bool SkDiffuseLightingImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInput(0, proxy, source, ctx, &src, &srcOffset)) { return false; } if (src.colorType() != kN32_SkColorType) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, src, &srcOffset, &bounds, &src)) { return false; } if (bounds.width() < 2 || bounds.height() < 2) { return false; } SkAutoLockPixels alp(src); if (!src.getPixels()) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (!device) { return false; } *dst = device->accessBitmap(false); SkAutoLockPixels alp_dst(*dst); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-srcOffset.x()), SkIntToScalar(-srcOffset.y())); SkAutoTUnref<SkImageFilterLight> transformedLight(light()->transform(matrix)); DiffuseLightingType lightingType(fKD); offset->fX = bounds.left(); offset->fY = bounds.top(); bounds.offset(-srcOffset); switch (transformedLight->type()) { case SkImageFilterLight::kDistant_LightType: lightBitmap<DiffuseLightingType, SkDistantLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kPoint_LightType: lightBitmap<DiffuseLightingType, SkPointLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kSpot_LightType: lightBitmap<DiffuseLightingType, SkSpotLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; } return true; } #ifndef SK_IGNORE_TO_STRING void SkDiffuseLightingImageFilter::toString(SkString* str) const { str->appendf("SkDiffuseLightingImageFilter: ("); str->appendf("kD: %f\n", fKD); str->append(")"); } #endif #if SK_SUPPORT_GPU GrFragmentProcessor* SkDiffuseLightingImageFilter::getFragmentProcessor( GrTexture* texture, const SkMatrix& matrix, const SkIRect&, BoundaryMode boundaryMode ) const { SkScalar scale = SkScalarMul(this->surfaceScale(), SkIntToScalar(255)); return GrDiffuseLightingEffect::Create(texture, this->light(), scale, matrix, this->kd(), boundaryMode); } #endif /////////////////////////////////////////////////////////////////////////////// SkImageFilter* SkSpecularLightingImageFilter::Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect* cropRect) { if (nullptr == light) { return nullptr; } if (!SkScalarIsFinite(surfaceScale) || !SkScalarIsFinite(ks) || !SkScalarIsFinite(shininess)) { return nullptr; } // According to the spec, ks can be any non-negative number : // http://www.w3.org/TR/SVG/filters.html#feSpecularLightingElement if (ks < 0) { return nullptr; } return new SkSpecularLightingImageFilter(light, surfaceScale, ks, shininess, input, cropRect); } SkSpecularLightingImageFilter::SkSpecularLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect), fKS(ks), fShininess(shininess) { } SkFlattenable* SkSpecularLightingImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); SkAutoTUnref<SkImageFilterLight> light(SkImageFilterLight::UnflattenLight(buffer)); SkScalar surfaceScale = buffer.readScalar(); SkScalar ks = buffer.readScalar(); SkScalar shine = buffer.readScalar(); return Create(light, surfaceScale, ks, shine, common.getInput(0), &common.cropRect()); } void SkSpecularLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fKS); buffer.writeScalar(fShininess); } bool SkSpecularLightingImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInput(0, proxy, source, ctx, &src, &srcOffset)) { return false; } if (src.colorType() != kN32_SkColorType) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, src, &srcOffset, &bounds, &src)) { return false; } if (bounds.width() < 2 || bounds.height() < 2) { return false; } SkAutoLockPixels alp(src); if (!src.getPixels()) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (!device) { return false; } *dst = device->accessBitmap(false); SkAutoLockPixels alp_dst(*dst); SpecularLightingType lightingType(fKS, fShininess); offset->fX = bounds.left(); offset->fY = bounds.top(); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-srcOffset.x()), SkIntToScalar(-srcOffset.y())); SkAutoTUnref<SkImageFilterLight> transformedLight(light()->transform(matrix)); bounds.offset(-srcOffset); switch (transformedLight->type()) { case SkImageFilterLight::kDistant_LightType: lightBitmap<SpecularLightingType, SkDistantLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kPoint_LightType: lightBitmap<SpecularLightingType, SkPointLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kSpot_LightType: lightBitmap<SpecularLightingType, SkSpotLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; } return true; } #ifndef SK_IGNORE_TO_STRING void SkSpecularLightingImageFilter::toString(SkString* str) const { str->appendf("SkSpecularLightingImageFilter: ("); str->appendf("kS: %f shininess: %f", fKS, fShininess); str->append(")"); } #endif #if SK_SUPPORT_GPU GrFragmentProcessor* SkSpecularLightingImageFilter::getFragmentProcessor( GrTexture* texture, const SkMatrix& matrix, const SkIRect&, BoundaryMode boundaryMode) const { SkScalar scale = SkScalarMul(this->surfaceScale(), SkIntToScalar(255)); return GrSpecularLightingEffect::Create(texture, this->light(), scale, matrix, this->ks(), this->shininess(), boundaryMode); } #endif /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU namespace { SkPoint3 random_point3(SkRandom* random) { return SkPoint3::Make(SkScalarToFloat(random->nextSScalar1()), SkScalarToFloat(random->nextSScalar1()), SkScalarToFloat(random->nextSScalar1())); } SkImageFilterLight* create_random_light(SkRandom* random) { int type = random->nextULessThan(3); switch (type) { case 0: { return new SkDistantLight(random_point3(random), random->nextU()); } case 1: { return new SkPointLight(random_point3(random), random->nextU()); } case 2: { return new SkSpotLight(random_point3(random), random_point3(random), random->nextUScalar1(), random->nextUScalar1(), random->nextU()); } default: SkFAIL("Unexpected value."); return nullptr; } } SkString emitNormalFunc(BoundaryMode mode, const char* pointToNormalName, const char* sobelFuncName) { SkString result; switch (mode) { case kTopLeft_BoundaryMode: result.printf("\treturn %s(%s(0.0, 0.0, m[4], m[5], m[7], m[8], %g),\n" "\t %s(0.0, 0.0, m[4], m[7], m[5], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kTop_BoundaryMode: result.printf("\treturn %s(%s(0.0, 0.0, m[3], m[5], m[6], m[8], %g),\n" "\t %s(0.0, 0.0, m[4], m[7], m[5], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneThird, sobelFuncName, gOneHalf); break; case kTopRight_BoundaryMode: result.printf("\treturn %s(%s( 0.0, 0.0, m[3], m[4], m[6], m[7], %g),\n" "\t %s(m[3], m[6], m[4], m[7], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kLeft_BoundaryMode: result.printf("\treturn %s(%s(m[1], m[2], m[4], m[5], m[7], m[8], %g),\n" "\t %s( 0.0, 0.0, m[1], m[7], m[2], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneHalf, sobelFuncName, gOneThird); break; case kInterior_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[2], m[3], m[5], m[6], m[8], %g),\n" "\t %s(m[0], m[6], m[1], m[7], m[2], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneQuarter, sobelFuncName, gOneQuarter); break; case kRight_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[1], m[3], m[4], m[6], m[7], %g),\n" "\t %s(m[0], m[6], m[1], m[7], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneHalf, sobelFuncName, gOneThird); break; case kBottomLeft_BoundaryMode: result.printf("\treturn %s(%s(m[1], m[2], m[4], m[5], 0.0, 0.0, %g),\n" "\t %s( 0.0, 0.0, m[1], m[4], m[2], m[5], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kBottom_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[2], m[3], m[5], 0.0, 0.0, %g),\n" "\t %s(m[0], m[3], m[1], m[4], m[2], m[5], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneThird, sobelFuncName, gOneHalf); break; case kBottomRight_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[1], m[3], m[4], 0.0, 0.0, %g),\n" "\t %s(m[0], m[3], m[1], m[4], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; default: SkASSERT(false); break; } return result; } } class GrGLLightingEffect : public GrGLSLFragmentProcessor { public: GrGLLightingEffect(const GrProcessor&); virtual ~GrGLLightingEffect(); void emitCode(EmitArgs&) override; static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder* b); protected: /** * Subclasses of GrGLLightingEffect must call INHERITED::onSetData(); */ void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; virtual void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) = 0; private: typedef GrGLSLFragmentProcessor INHERITED; UniformHandle fImageIncrementUni; UniformHandle fSurfaceScaleUni; GrGLLight* fLight; BoundaryMode fBoundaryMode; }; /////////////////////////////////////////////////////////////////////////////// class GrGLDiffuseLightingEffect : public GrGLLightingEffect { public: GrGLDiffuseLightingEffect(const GrProcessor&); void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) override; protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: typedef GrGLLightingEffect INHERITED; UniformHandle fKDUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLSpecularLightingEffect : public GrGLLightingEffect { public: GrGLSpecularLightingEffect(const GrProcessor&); void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) override; protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: typedef GrGLLightingEffect INHERITED; UniformHandle fKSUni; UniformHandle fShininessUni; }; /////////////////////////////////////////////////////////////////////////////// GrLightingEffect::GrLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, BoundaryMode boundaryMode) : INHERITED(texture, GrCoordTransform::MakeDivByTextureWHMatrix(texture)) , fLight(light) , fSurfaceScale(surfaceScale) , fFilterMatrix(matrix) , fBoundaryMode(boundaryMode) { fLight->ref(); if (light->requiresFragmentPosition()) { this->setWillReadFragmentPosition(); } } GrLightingEffect::~GrLightingEffect() { fLight->unref(); } bool GrLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrLightingEffect& s = sBase.cast<GrLightingEffect>(); return fLight->isEqual(*s.fLight) && fSurfaceScale == s.fSurfaceScale && fBoundaryMode == s.fBoundaryMode; } /////////////////////////////////////////////////////////////////////////////// GrDiffuseLightingEffect::GrDiffuseLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode) : INHERITED(texture, light, surfaceScale, matrix, boundaryMode), fKD(kd) { this->initClassID<GrDiffuseLightingEffect>(); } bool GrDiffuseLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrDiffuseLightingEffect& s = sBase.cast<GrDiffuseLightingEffect>(); return INHERITED::onIsEqual(sBase) && this->kd() == s.kd(); } void GrDiffuseLightingEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GrGLDiffuseLightingEffect::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrDiffuseLightingEffect::onCreateGLSLInstance() const { return new GrGLDiffuseLightingEffect(*this); } GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrDiffuseLightingEffect); const GrFragmentProcessor* GrDiffuseLightingEffect::TestCreate(GrProcessorTestData* d) { SkScalar surfaceScale = d->fRandom->nextSScalar1(); SkScalar kd = d->fRandom->nextUScalar1(); SkAutoTUnref<SkImageFilterLight> light(create_random_light(d->fRandom)); SkMatrix matrix; for (int i = 0; i < 9; i++) { matrix[i] = d->fRandom->nextUScalar1(); } BoundaryMode mode = static_cast<BoundaryMode>(d->fRandom->nextU() % kBoundaryModeCount); return GrDiffuseLightingEffect::Create(d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx], light, surfaceScale, matrix, kd, mode); } /////////////////////////////////////////////////////////////////////////////// GrGLLightingEffect::GrGLLightingEffect(const GrProcessor& fp) { const GrLightingEffect& m = fp.cast<GrLightingEffect>(); fLight = m.light()->createGLLight(); fBoundaryMode = m.boundaryMode(); } GrGLLightingEffect::~GrGLLightingEffect() { delete fLight; } void GrGLLightingEffect::emitCode(EmitArgs& args) { GrGLSLUniformHandler* uniformHandler = args.fUniformHandler; fImageIncrementUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec2f_GrSLType, kDefault_GrSLPrecision, "ImageIncrement"); fSurfaceScaleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "SurfaceScale"); fLight->emitLightColorUniform(uniformHandler); GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder; SkString lightFunc; this->emitLightFunc(uniformHandler, fragBuilder, &lightFunc); static const GrGLSLShaderVar gSobelArgs[] = { GrGLSLShaderVar("a", kFloat_GrSLType), GrGLSLShaderVar("b", kFloat_GrSLType), GrGLSLShaderVar("c", kFloat_GrSLType), GrGLSLShaderVar("d", kFloat_GrSLType), GrGLSLShaderVar("e", kFloat_GrSLType), GrGLSLShaderVar("f", kFloat_GrSLType), GrGLSLShaderVar("scale", kFloat_GrSLType), }; SkString sobelFuncName; SkString coords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 0); fragBuilder->emitFunction(kFloat_GrSLType, "sobel", SK_ARRAY_COUNT(gSobelArgs), gSobelArgs, "\treturn (-a + b - 2.0 * c + 2.0 * d -e + f) * scale;\n", &sobelFuncName); static const GrGLSLShaderVar gPointToNormalArgs[] = { GrGLSLShaderVar("x", kFloat_GrSLType), GrGLSLShaderVar("y", kFloat_GrSLType), GrGLSLShaderVar("scale", kFloat_GrSLType), }; SkString pointToNormalName; fragBuilder->emitFunction(kVec3f_GrSLType, "pointToNormal", SK_ARRAY_COUNT(gPointToNormalArgs), gPointToNormalArgs, "\treturn normalize(vec3(-x * scale, -y * scale, 1));\n", &pointToNormalName); static const GrGLSLShaderVar gInteriorNormalArgs[] = { GrGLSLShaderVar("m", kFloat_GrSLType, 9), GrGLSLShaderVar("surfaceScale", kFloat_GrSLType), }; SkString normalBody = emitNormalFunc(fBoundaryMode, pointToNormalName.c_str(), sobelFuncName.c_str()); SkString normalName; fragBuilder->emitFunction(kVec3f_GrSLType, "normal", SK_ARRAY_COUNT(gInteriorNormalArgs), gInteriorNormalArgs, normalBody.c_str(), &normalName); fragBuilder->codeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str()); fragBuilder->codeAppend("\t\tfloat m[9];\n"); const char* imgInc = uniformHandler->getUniformCStr(fImageIncrementUni); const char* surfScale = uniformHandler->getUniformCStr(fSurfaceScaleUni); int index = 0; for (int dy = 1; dy >= -1; dy--) { for (int dx = -1; dx <= 1; dx++) { SkString texCoords; texCoords.appendf("coord + vec2(%d, %d) * %s", dx, dy, imgInc); fragBuilder->codeAppendf("\t\tm[%d] = ", index++); fragBuilder->appendTextureLookup(args.fSamplers[0], texCoords.c_str()); fragBuilder->codeAppend(".a;\n"); } } fragBuilder->codeAppend("\t\tvec3 surfaceToLight = "); SkString arg; arg.appendf("%s * m[4]", surfScale); fLight->emitSurfaceToLight(uniformHandler, fragBuilder, arg.c_str()); fragBuilder->codeAppend(";\n"); fragBuilder->codeAppendf("\t\t%s = %s(%s(m, %s), surfaceToLight, ", args.fOutputColor, lightFunc.c_str(), normalName.c_str(), surfScale); fLight->emitLightColor(uniformHandler, fragBuilder, "surfaceToLight"); fragBuilder->codeAppend(");\n"); SkString modulate; GrGLSLMulVarBy4f(&modulate, args.fOutputColor, args.fInputColor); fragBuilder->codeAppend(modulate.c_str()); } void GrGLLightingEffect::GenKey(const GrProcessor& proc, const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) { const GrLightingEffect& lighting = proc.cast<GrLightingEffect>(); b->add32(lighting.boundaryMode() << 2 | lighting.light()->type()); } void GrGLLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { const GrLightingEffect& lighting = proc.cast<GrLightingEffect>(); GrTexture* texture = lighting.texture(0); float ySign = texture->origin() == kTopLeft_GrSurfaceOrigin ? -1.0f : 1.0f; pdman.set2f(fImageIncrementUni, 1.0f / texture->width(), ySign / texture->height()); pdman.set1f(fSurfaceScaleUni, lighting.surfaceScale()); SkAutoTUnref<SkImageFilterLight> transformedLight( lighting.light()->transform(lighting.filterMatrix())); fLight->setData(pdman, transformedLight); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// GrGLDiffuseLightingEffect::GrGLDiffuseLightingEffect(const GrProcessor& proc) : INHERITED(proc) { } void GrGLDiffuseLightingEffect::emitLightFunc(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, SkString* funcName) { const char* kd; fKDUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "KD", &kd); static const GrGLSLShaderVar gLightArgs[] = { GrGLSLShaderVar("normal", kVec3f_GrSLType), GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType), GrGLSLShaderVar("lightColor", kVec3f_GrSLType) }; SkString lightBody; lightBody.appendf("\tfloat colorScale = %s * dot(normal, surfaceToLight);\n", kd); lightBody.appendf("\treturn vec4(lightColor * clamp(colorScale, 0.0, 1.0), 1.0);\n"); fragBuilder->emitFunction(kVec4f_GrSLType, "light", SK_ARRAY_COUNT(gLightArgs), gLightArgs, lightBody.c_str(), funcName); } void GrGLDiffuseLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { INHERITED::onSetData(pdman, proc); const GrDiffuseLightingEffect& diffuse = proc.cast<GrDiffuseLightingEffect>(); pdman.set1f(fKDUni, diffuse.kd()); } /////////////////////////////////////////////////////////////////////////////// GrSpecularLightingEffect::GrSpecularLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode) : INHERITED(texture, light, surfaceScale, matrix, boundaryMode) , fKS(ks) , fShininess(shininess) { this->initClassID<GrSpecularLightingEffect>(); } bool GrSpecularLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrSpecularLightingEffect& s = sBase.cast<GrSpecularLightingEffect>(); return INHERITED::onIsEqual(sBase) && this->ks() == s.ks() && this->shininess() == s.shininess(); } void GrSpecularLightingEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GrGLSpecularLightingEffect::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrSpecularLightingEffect::onCreateGLSLInstance() const { return new GrGLSpecularLightingEffect(*this); } GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSpecularLightingEffect); const GrFragmentProcessor* GrSpecularLightingEffect::TestCreate(GrProcessorTestData* d) { SkScalar surfaceScale = d->fRandom->nextSScalar1(); SkScalar ks = d->fRandom->nextUScalar1(); SkScalar shininess = d->fRandom->nextUScalar1(); SkAutoTUnref<SkImageFilterLight> light(create_random_light(d->fRandom)); SkMatrix matrix; for (int i = 0; i < 9; i++) { matrix[i] = d->fRandom->nextUScalar1(); } BoundaryMode mode = static_cast<BoundaryMode>(d->fRandom->nextU() % kBoundaryModeCount); return GrSpecularLightingEffect::Create(d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx], light, surfaceScale, matrix, ks, shininess, mode); } /////////////////////////////////////////////////////////////////////////////// GrGLSpecularLightingEffect::GrGLSpecularLightingEffect(const GrProcessor& proc) : INHERITED(proc) { } void GrGLSpecularLightingEffect::emitLightFunc(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, SkString* funcName) { const char* ks; const char* shininess; fKSUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "KS", &ks); fShininessUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "Shininess", &shininess); static const GrGLSLShaderVar gLightArgs[] = { GrGLSLShaderVar("normal", kVec3f_GrSLType), GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType), GrGLSLShaderVar("lightColor", kVec3f_GrSLType) }; SkString lightBody; lightBody.appendf("\tvec3 halfDir = vec3(normalize(surfaceToLight + vec3(0, 0, 1)));\n"); lightBody.appendf("\tfloat colorScale = %s * pow(dot(normal, halfDir), %s);\n", ks, shininess); lightBody.appendf("\tvec3 color = lightColor * clamp(colorScale, 0.0, 1.0);\n"); lightBody.appendf("\treturn vec4(color, max(max(color.r, color.g), color.b));\n"); fragBuilder->emitFunction(kVec4f_GrSLType, "light", SK_ARRAY_COUNT(gLightArgs), gLightArgs, lightBody.c_str(), funcName); } void GrGLSpecularLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& effect) { INHERITED::onSetData(pdman, effect); const GrSpecularLightingEffect& spec = effect.cast<GrSpecularLightingEffect>(); pdman.set1f(fKSUni, spec.ks()); pdman.set1f(fShininessUni, spec.shininess()); } /////////////////////////////////////////////////////////////////////////////// void GrGLLight::emitLightColorUniform(GrGLSLUniformHandler* uniformHandler) { fColorUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightColor"); } void GrGLLight::emitLightColor(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char *surfaceToLight) { fragBuilder->codeAppend(uniformHandler->getUniformCStr(this->lightColorUni())); } void GrGLLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { setUniformPoint3(pdman, fColorUni, light->color().makeScale(SkScalarInvert(SkIntToScalar(255)))); } /////////////////////////////////////////////////////////////////////////////// void GrGLDistantLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kDistant_LightType); const SkDistantLight* distantLight = static_cast<const SkDistantLight*>(light); setUniformNormal3(pdman, fDirectionUni, distantLight->direction()); } void GrGLDistantLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* dir; fDirectionUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightDirection", &dir); fragBuilder->codeAppend(dir); } /////////////////////////////////////////////////////////////////////////////// void GrGLPointLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kPoint_LightType); const SkPointLight* pointLight = static_cast<const SkPointLight*>(light); setUniformPoint3(pdman, fLocationUni, pointLight->location()); } void GrGLPointLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* loc; fLocationUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightLocation", &loc); fragBuilder->codeAppendf("normalize(%s - vec3(%s.xy, %s))", loc, fragBuilder->fragmentPosition(), z); } /////////////////////////////////////////////////////////////////////////////// void GrGLSpotLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kSpot_LightType); const SkSpotLight* spotLight = static_cast<const SkSpotLight *>(light); setUniformPoint3(pdman, fLocationUni, spotLight->location()); pdman.set1f(fExponentUni, spotLight->specularExponent()); pdman.set1f(fCosInnerConeAngleUni, spotLight->cosInnerConeAngle()); pdman.set1f(fCosOuterConeAngleUni, spotLight->cosOuterConeAngle()); pdman.set1f(fConeScaleUni, spotLight->coneScale()); setUniformNormal3(pdman, fSUni, spotLight->s()); } void GrGLSpotLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* location; fLocationUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightLocation", &location); fragBuilder->codeAppendf("normalize(%s - vec3(%s.xy, %s))", location, fragBuilder->fragmentPosition(), z); } void GrGLSpotLight::emitLightColor(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char *surfaceToLight) { const char* color = uniformHandler->getUniformCStr(this->lightColorUni()); // created by parent class. const char* exponent; const char* cosInner; const char* cosOuter; const char* coneScale; const char* s; fExponentUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "Exponent", &exponent); fCosInnerConeAngleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "CosInnerConeAngle", &cosInner); fCosOuterConeAngleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "CosOuterConeAngle", &cosOuter); fConeScaleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "ConeScale", &coneScale); fSUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "S", &s); static const GrGLSLShaderVar gLightColorArgs[] = { GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType) }; SkString lightColorBody; lightColorBody.appendf("\tfloat cosAngle = -dot(surfaceToLight, %s);\n", s); lightColorBody.appendf("\tif (cosAngle < %s) {\n", cosOuter); lightColorBody.appendf("\t\treturn vec3(0);\n"); lightColorBody.appendf("\t}\n"); lightColorBody.appendf("\tfloat scale = pow(cosAngle, %s);\n", exponent); lightColorBody.appendf("\tif (cosAngle < %s) {\n", cosInner); lightColorBody.appendf("\t\treturn %s * scale * (cosAngle - %s) * %s;\n", color, cosOuter, coneScale); lightColorBody.appendf("\t}\n"); lightColorBody.appendf("\treturn %s;\n", color); fragBuilder->emitFunction(kVec3f_GrSLType, "lightColor", SK_ARRAY_COUNT(gLightColorArgs), gLightColorArgs, lightColorBody.c_str(), &fLightColorFunc); fragBuilder->codeAppendf("%s(%s)", fLightColorFunc.c_str(), surfaceToLight); } #endif SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkDiffuseLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSpecularLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
[ "roytam@gmail.com" ]
roytam@gmail.com
43c66bd5d3a0d11b3eeee4e5e08fcfc4bb1122e4
3c378513afb8e6c2680715c91c31845b67e71885
/include/SIMD_KScheme_2Bit_CU.hpp
9c1861d14dd2662d6beb90ffe6ffe46e1a233875
[]
no_license
yingfeng/integer_encoding_library_sparklezzz
582f21140a0c6cccae692f8e92464b8a1f093674
8ba46561cde38920674f4789f4f413ceed45ef6b
refs/heads/master
2021-01-17T12:26:12.838738
2015-01-14T13:37:40
2015-01-14T13:37:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,447
hpp
/* * SIMD_KScheme_2Bit_CU.hpp * * SIMD_KScheme_2Bit_Complete Unary * * Created on: 2013-3-2 * Author: zxd */ #ifndef SIMD_KSCHEME_2BIT_CU_HPP_ #define SIMD_KSCHEME_2BIT_CU_HPP_ #ifdef USE_SSE_INSTRUCTION #include <stdint.h> #include <cmath> #include <assert.h> #include <string.h> #include "Compressor.hpp" #include "VarByte.hpp" #include <iostream> #include "simd_kscheme_2bit_cu_unpack.hpp" using namespace std; namespace paradise { namespace index { class SIMD_KScheme_2Bit_CU: public Compressor { public: SIMD_KScheme_2Bit_CU() { } virtual ~SIMD_KScheme_2Bit_CU() { } public: virtual int encodeUint32(char* des, const uint32_t* src, uint32_t encodeNum); virtual int decodeUint32(uint32_t* des, const char* src, uint32_t decodeNum); virtual int encodeUint16(char* des, const uint16_t* src, uint32_t encodeNum); virtual int decodeUint16(uint16_t* des, const char* src, uint32_t decodeNum); virtual int encodeUint8(char* des, const uint8_t* src, uint32_t encodeNum); virtual int decodeUint8(uint8_t* des, const char* src, uint32_t decodeNum); virtual std::string getCompressorName() { return "SIMD_KScheme_2Bit_CU"; } virtual Compressor* clone(); private: template<typename T> int encode(char* des, const T* src, uint32_t length); template<typename T> int decode(T* des, const char* src, uint32_t length); template<typename T> int encodeBlock(char* des, const T* src, uint32_t size); template<typename T> int decodeBlock(T* des, const char* src, uint32_t size); }; template<typename T> int SIMD_KScheme_2Bit_CU::encode(char* des, const T* src, uint32_t encodeNum) { if (encodeNum < 4) { return VarByte::encode(des, src, encodeNum); } int compLen = 0; int left = encodeNum % 4; if (left > 0) { compLen = encodeBlock(des, src, encodeNum - left); compLen += VarByte::encode(des + compLen, src + encodeNum - left, left); } else { compLen = encodeBlock(des, src, encodeNum); } return compLen; } template<typename T> int SIMD_KScheme_2Bit_CU::decode(T* des, const char* src, uint32_t decodeNum) { if (decodeNum < 4) { return VarByte::decode(des, src, decodeNum); } int decodeLen = 0; int left = decodeNum % 4; if (left > 0) { decodeLen = decodeBlock(des, src, decodeNum - left); decodeLen += VarByte::decode(des + decodeNum - left, src + decodeLen, left); } else { decodeLen = decodeBlock(des, src, decodeNum); } return decodeLen; } template<typename T> int SIMD_KScheme_2Bit_CU::encodeBlock(char* des, const T* src, uint32_t encodeNum) { const static uint16_t unary_code[17] = {-1, 0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, // INVALID, 0, 01, 011, 0111, 01111, 011111, 0111111, 01111111 0xff, 0x1ff, 0x3ff, 0x7ff, 0xfff, // 011111111,... 0x1fff, 0x3fff, 0x7fff}; uint32_t quadEncodeNum = encodeNum / 4; uint16_t *tmpModeSegBeg = new uint16_t[quadEncodeNum]; //max control bit for one int: 4 uint16_t *tmpModeSegIdx = tmpModeSegBeg; memset(tmpModeSegBeg, 0, quadEncodeNum * sizeof(uint16_t)); char *desBeg = des; uint32_t *desInt = (uint32_t*)des; char *dataSegBeg = des + 4; //leave first 4 byte to record the begin position of data segment uint32_t *dataSegPosInt = (uint32_t*)dataSegBeg; __asm__ volatile("prefetchnta %0"::"m" (src[0])); __asm__("pxor %%xmm0,%%xmm0\n":::); int k = 0; uint32_t curBitOffset = 0; //range from 0 to 4 uint32_t controlBitOffset = 0; //range from 0 to 7 for (uint32_t i=0; i<encodeNum; i+=4) { // step1: get quad max int T quadMaxInt = src[0]; for (uint32_t j=1; j<4; j++) { quadMaxInt |= src[j]; } // step2: get bytes needed for quad max int if (quadMaxInt == 0) quadMaxInt ++; char twoBitCount = 0; while (quadMaxInt > 0) { quadMaxInt >>= 2; twoBitCount ++; } // step3: record the unary descriptor if (controlBitOffset + twoBitCount > 16) { //start new mode and new data seg // pad the descriptor with all 1 uint16_t pad = (0xffff >> controlBitOffset) << controlBitOffset; *tmpModeSegIdx |= pad; tmpModeSegIdx ++; controlBitOffset = controlBitOffset + twoBitCount - 16; *tmpModeSegIdx |= unary_code[controlBitOffset]; } else { *tmpModeSegIdx |= unary_code[twoBitCount] << controlBitOffset; controlBitOffset += twoBitCount; } // step4: encode group of 4 ints uint32_t bitLeftInUInt = 32 - curBitOffset; uint32_t bitCount = twoBitCount * 2; if (bitLeftInUInt < bitCount) { //new data should cross uint boundary // write data with effective bit length of the max val //for (uint32_t k=0; k<4; k++) { // *(dataSegPosInt + k) |= (src[k] & byte_mask_map[byteLeftInUInt]) << (curByteOffset<<3); //} __asm__("movdqu %1,%%xmm3\n" //src[0]->xmm0 "movdqa %%xmm3,%%xmm4\n" //backup for next codeword "movd %2,%%xmm1\n" //shiftLeft->xmm1 "pslld %%xmm1,%%xmm3\n" //shift left->xmm0 "psrld %%xmm2,%%xmm0\n" //shift right->xmm "por %%xmm3,%%xmm0\n" "movdqu %%xmm0,%0\n" //write back codeword :"=m" (dataSegPosInt[0]) :"m" (src[0]),"m" (curBitOffset) :"memory"); //start a new group and left val dataSegPosInt += 4; uint32_t bitUnwritten = bitCount - bitLeftInUInt; //for (uint32_t k=0; k<4; k++) { // *(dataSegPosInt + k) = (src[k] >> (byteLeftInUInt<<3)) & byte_mask_map[byteUnwritten] ; //} uint32_t shiftLeft = 32 - bitCount; uint32_t shiftRight = 32 - bitUnwritten; __asm__("movdqa %%xmm4,%%xmm0\n" "movd %0,%%xmm1\n" //shiftLeft->xmm1 "movd %1,%%xmm2\n" //shiftRight->xmm2 "pslld %%xmm1,%%xmm0\n" //shift left->xmm0 "psrld %%xmm2,%%xmm0\n" //shift right->xmm0 ::"m" (shiftLeft),"m" (shiftRight) :"memory"); curBitOffset = bitUnwritten; } else { // write data with effective bit length of the max val //for (uint32_t k=0; k<4; k++) { // *(dataSegPosInt + k) |= (src[k] & byte_mask_map[byteCount]) << (curByteOffset<<3); //} uint32_t shiftLeft = 32 - bitCount; uint32_t shiftRight = shiftLeft - curBitOffset; __asm__ volatile("prefetchnta %0"::"m" (src[0])); __asm__("movdqu %0,%%xmm3\n" //src[0]->xmm3 "movd %1,%%xmm1\n" //shiftLeft->xmm1 "movd %2,%%xmm2\n" //shiftRight->xmm2 "pslld %%xmm1,%%xmm3\n" //shift left->xmm0 "psrld %%xmm2,%%xmm3\n" //shift right->xmm0 "por %%xmm3,%%xmm0\n" ::"m" (src[0]),"m" (shiftLeft),"m" (shiftRight) :"memory"); curBitOffset += bitCount; } src += 4; } __asm__("movdqu %%xmm0,%0\n" :"=m" (dataSegPosInt[0]) ::"memory"); // pad the descriptor uint16_t pad = (0xffff >> controlBitOffset) << controlBitOffset; *tmpModeSegIdx |= pad; tmpModeSegIdx ++; dataSegPosInt += 4; // record the start offset of mode segment *desInt = 4 + ((char*)dataSegPosInt - dataSegBeg); // append the mode seg to the end of data seg char *modeSegBeg = (char*)dataSegPosInt; uint32_t modeSegSize = (tmpModeSegIdx - tmpModeSegBeg) * sizeof(uint16_t); memcpy(modeSegBeg, tmpModeSegBeg, modeSegSize); delete [] tmpModeSegBeg; return (modeSegBeg - desBeg) + modeSegSize; } template<typename T> int SIMD_KScheme_2Bit_CU::decodeBlock(T* des, const char* src, uint32_t decodeNum) { const uint32_t *srcInt = (const uint32_t*)src; uint32_t modeSegOffset = *srcInt; const uint8_t *dataSegPos = (uint8_t*)src + 4; const uint8_t *modeSegBeg = (uint8_t*)(src + modeSegOffset); //note that we still use 8 bit for mode seg here! const uint8_t *modeSegPos = modeSegBeg; const uint32_t *wordPos = (const uint32_t*)dataSegPos; simd_kscheme_2bit_cu_unpack_prepare<T>(); uint32_t decoded = 0; uint32_t groupFullBitOffset = 0; while (decoded < decodeNum) { // get a valid unary descriptor const SIMDK2CUUnpackInfo &unpackInfo = SIMDK2CUUnpackInfoArr[*modeSegPos]; unpackInfo.m_subFunc((uint32_t*)des, wordPos); modeSegPos ++; des += unpackInfo.m_intNum; decoded += unpackInfo.m_intNum; wordPos += ((groupFullBitOffset + 16) >> 5) << 2; groupFullBitOffset = (groupFullBitOffset + 16) & 0x1f; } uint32_t modeSegSize = modeSegPos - modeSegBeg; if (modeSegSize % 2 != 0) //note that the original unit of mode seg is 16 bit modeSegPos ++; if (groupFullBitOffset != 0) wordPos += 4; return (char*)modeSegPos - src; } } } #endif #endif /* SIMD_KSCHEME_2BIT_CU_HPP_ */
[ "xdzhang@yahoo-inc.com" ]
xdzhang@yahoo-inc.com
1d412be22cb408024611a815c947ed1dd3e42ac5
dd95d7ea86fcd4f27664653205df0d2005665f2b
/shared/configeditor/include/Trigger.h
b82db6fa3165459ee317fe374fef801d744cfef4
[]
no_license
sawmic/GIMX
ab7437b70e2094399624e93c493dd550144828ce
96cb9d155123a4c1657c4b2f177725395bbafd9e
refs/heads/master
2021-01-12T21:53:13.514674
2014-02-01T14:01:48
2014-02-01T14:01:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,125
h
/* Copyright (c) 2011 Mathieu Laurendeau <mat.lau@laposte.net> License: GPLv3 */ #ifndef TRIGGER_H #define TRIGGER_H #include <Device.h> #include <Event.h> class Trigger { public: Trigger(); Trigger(string dtype, string did, string dname, string eid, string switchback, unsigned short delay); virtual ~Trigger(); Trigger(const Trigger& other); Trigger& operator=(const Trigger& other); bool operator==(const Trigger &other) const; Device* GetDevice() { return &m_Device; } void SetDevice(Device val) { m_Device = val; } Event* GetEvent() { return &m_Event; } void SetEvent(Event val) { m_Event = val; } string GetSwitchBack() { return m_SwitchBack; } void SetSwitchBack(string val) { m_SwitchBack = val; } unsigned short GetDelay() { return m_Delay; } void SetDelay(unsigned short val) { m_Delay = val; } protected: private: Device m_Device; Event m_Event; string m_SwitchBack; unsigned short m_Delay; }; #endif // TRIGGER_H
[ "mat.lau@laposte.net" ]
mat.lau@laposte.net
e0942620c15caf086988b0a8d199e5c3eadaa27f
7ebae5ec0378642a1d2c181184460e76c73debbd
/UVA Online Judge/694/694/694.cpp
81d5786ad415701534d07d0812344b7a36947434
[]
no_license
tonyli00000/Competition-Code
a4352b6b6835819a0f19f7f5cc67e46d2a200906
7f5767e3cb997fd15ae6f72145bcb8394f50975f
refs/heads/master
2020-06-17T23:04:10.367762
2019-12-28T22:08:25
2019-12-28T22:08:25
196,091,038
0
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include <iostream> #include <string> #include <sstream> #include <iomanip> #include <math.h> #include <queue> #include <stack> #include <vector> #include <map> #include <set> #include <functional> #include <algorithm> using namespace std; int main() { long long a, l,temp,tc=0; while (cin >> a >> l){ if (a < 0 && l < 0)break; long long ct = 1; temp = a; while (true){ if (a == 1)break; if (a % 2 == 0){ a = a / 2; ct++; } else{ a = 3 * a + 1; if (a > l)break; ct++; } } cout << "Case "<<++tc<<": A = "<<temp << ", limit = " << l << ", number of terms = " << ct << "\n"; } return 0; }
[ "tonyli2002@live.com" ]
tonyli2002@live.com
34ec8217a7118d234a343ffebfbdbf93eb84e999
9e86596a4c9dbedaa8aa08923c14cd39da2455e2
/src/operator/cudnn_activation-inl.h
99bbfe93e871dfee942a2c5e0a4f5f3be400bc5e
[ "Apache-2.0" ]
permissive
XinliangZhu/mxnet
0796c687618f84462ec4a57a2d1b44a1570ed68d
016e049fee799bbc1bb0c1e3e3d3ff858603840b
refs/heads/master
2021-01-22T13:12:25.265640
2015-10-19T00:34:16
2015-10-19T00:34:16
44,504,570
1
0
null
2015-10-19T01:33:19
2015-10-19T01:33:19
null
UTF-8
C++
false
false
5,431
h
/*! * Copyright (c) 2015 by Contributors * \file cudnn_activation-inl.h * \brief * \author Bing Xu */ #ifndef MXNET_OPERATOR_CUDNN_ACTIVATION_INL_H_ #define MXNET_OPERATOR_CUDNN_ACTIVATION_INL_H_ #include <algorithm> #include <vector> #include "./activation-inl.h" namespace mxnet { namespace op { class CuDNNActivationOp : public Operator { public: explicit CuDNNActivationOp(ActivationParam param) { param_ = param; init_cudnn_ = false; dtype_ = CUDNN_DATA_FLOAT; switch (param_.act_type) { case kReLU: mode_ = CUDNN_ACTIVATION_RELU; break; case kSigmoid: mode_ = CUDNN_ACTIVATION_SIGMOID; break; case kTanh: mode_ = CUDNN_ACTIVATION_TANH; break; default: LOG(FATAL) << "Not implmented"; break; } } ~CuDNNActivationOp() { CHECK_EQ(cudnnDestroyTensorDescriptor(shape_desc_), CUDNN_STATUS_SUCCESS); } virtual void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data, const std::vector<TBlob> &aux_args) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(in_data.size(), 1); CHECK_EQ(out_data.size(), 1); Stream<gpu> *s = ctx.get_stream<gpu>(); Tensor<gpu, 4> data; Tensor<gpu, 4> out; if (in_data[kData].ndim() == 2) { uint32_t ds[] = {in_data[kData].shape_[0], in_data[kData].shape_[1], 1, 1}; TShape dshape(ds, ds + 4); data = in_data[kData].get_with_shape<gpu, 4, real_t>(dshape, s); out = out_data[kOut].get_with_shape<gpu, 4, real_t>(dshape, s); } else { data = in_data[kData].get<gpu, 4, real_t>(s); out = out_data[kOut].get<gpu, 4, real_t>(s); } float alpha = 1.0f; float beta = 0.0f; CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle); if (!init_cudnn_) { init_cudnn_ = true; CHECK_EQ(cudnnCreateTensorDescriptor(&shape_desc_), CUDNN_STATUS_SUCCESS); CHECK_EQ(cudnnSetTensor4dDescriptor(shape_desc_, CUDNN_TENSOR_NCHW, dtype_, data.shape_[0], data.shape_[1], data.shape_[2], data.shape_[3]), CUDNN_STATUS_SUCCESS); } CHECK_EQ(cudnnActivationForward(s->dnn_handle_, mode_, &alpha, shape_desc_, data.dptr_, &beta, shape_desc_, out.dptr_), CUDNN_STATUS_SUCCESS); } virtual void Backward(const OpContext &ctx, const std::vector<TBlob> &out_grad, const std::vector<TBlob> &in_data, const std::vector<TBlob> &out_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad, const std::vector<TBlob> &aux_args) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(out_grad.size(), 1); CHECK_EQ(in_data.size(), 1); CHECK_EQ(out_data.size(), 1); CHECK_EQ(req.size(), 1); CHECK_EQ(in_grad.size(), 1); float alpha = 1.0f; float beta = 0.0f; Stream<gpu> *s = ctx.get_stream<gpu>(); Tensor<gpu, 4> grad; Tensor<gpu, 4> data; Tensor<gpu, 4> output_data; Tensor<gpu, 4> input_grad; if (in_data[kData].ndim() == 2) { uint32_t ds[] = {in_data[kData].shape_[0], in_data[kData].shape_[1], 1, 1}; TShape dshape(ds, ds + 4); data = in_data[kData].get_with_shape<gpu, 4, real_t>(dshape, s); grad = out_grad[kOut].get_with_shape<gpu, 4, real_t>(dshape, s); output_data = out_data[kOut].get_with_shape<gpu, 4, real_t>(dshape, s); input_grad = in_grad[kData].get_with_shape<gpu, 4, real_t>(dshape, s); } else { data = in_data[kData].get<gpu, 4, real_t>(s); output_data = out_data[kOut].get<gpu, 4, real_t>(s); grad = out_grad[kOut].get<gpu, 4, real_t>(s); input_grad = in_grad[kData].get<gpu, 4, real_t>(s); } CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle); CHECK_EQ(cudnnActivationBackward(s->dnn_handle_, mode_, &alpha, shape_desc_, output_data.dptr_, shape_desc_, grad.dptr_, shape_desc_, data.dptr_, &beta, shape_desc_, input_grad.dptr_), CUDNN_STATUS_SUCCESS); } private: bool init_cudnn_; cudnnDataType_t dtype_; cudnnActivationMode_t mode_; cudnnTensorDescriptor_t shape_desc_; ActivationParam param_; }; // class CuDNNActivationOp } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_CUDNN_ACTIVATION_INL_H_
[ "antinucleon@gmail.com" ]
antinucleon@gmail.com
1d631d863a8c88dd89e41fe7b10a94dfbfe1117f
4b0444102ea9917d581cb837740a2942bf655759
/MMVII/src/Bench/BenchGlob.cpp
47779606786b169938dbda6aac6c7ab73f753a5a
[ "LicenseRef-scancode-cecill-b-en" ]
permissive
gaoshuai/micmac
d415e447bbf28abfefcefaae8a4afee13dac2446
8ab820797de7d2c80490e1291c3a3b8ee6a226a3
refs/heads/master
2020-06-11T01:11:12.127351
2019-06-25T15:55:51
2019-06-25T15:55:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,526
cpp
#include "include/MMVII_all.h" #include <cmath> /** \file BenchGlob.cpp \brief Main bench For now bench are relatively simples and executed in the same process, it's than probable that when MMVII grow, more complex bench will be done by sub process specialized. */ namespace MMVII { #if (THE_MACRO_MMVII_SYS == MMVII_SYS_L) void Bench_0000_SysDepString() { std::string aPath0 = "MMVII"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath0,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath0,false)=="MMVII","File Bench_0000_SysDepString"); std::string aPath1 = "af.tif"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath1,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath1,false)=="af.tif","File Bench_0000_SysDepString"); std::string aPath2 = "./toto.txt"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath2,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath2,false)=="toto.txt","File Bench_0000_SysDepString"); std::string aPath3 = "/a/bb/cc/"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath3,false)==aPath3,"Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath3,false)=="","File Bench_0000_SysDepString"); std::string aPath4 = "/a/bb/cc/tutu"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath4,false)==aPath3,"Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath4,false)=="tutu","File Bench_0000_SysDepString"); std::string aPath5 = "NONE"; MMVII_INTERNAL_ASSERT_bench(DirOfPath (aPath5,false)=="./","Dir Bench_0000_SysDepString"); MMVII_INTERNAL_ASSERT_bench(FileOfPath(aPath5,false)=="NONE","File Bench_0000_SysDepString"); } #else void Bench_0000_SysDepString() { } #endif void Bench_0000_Memory() { cMemState aSt = cMemManager::CurState(); int aNb=5; // short * aPtr = static_cast<short *> (cMemManager::Calloc(sizeof(short),aNb)); /// short * aPtr = MemManagerAlloc<short>(aNb); short * aPtr = cMemManager::Alloc<short>(aNb); for (int aK=0; aK<aNb ; aK++) aPtr[aK] = 10 + 234 * aK; // Plein de test d'alteration if (0) aPtr[-1] =9; if (0) aPtr[aNb+6] =9; if (0) aPtr[aNb] =9; if (0) aPtr[aNb+1] =9; // Plante si on teste avant liberation if (0) cMemManager::CheckRestoration(aSt); cMemManager::Free(aPtr); cMemManager::CheckRestoration(aSt); } void Bench_0000_Param() { int a,b; cCollecSpecArg2007 aCol; aCol << Arg2007(a,"UnA") << AOpt2007(b,"b","UnB") ; aCol[0]->InitParam("111"); aCol[1]->InitParam("222"); MMVII_INTERNAL_ASSERT_bench(a==111,"Bench_0000_Param"); MMVII_INTERNAL_ASSERT_bench(b==222,"Bench_0000_Param"); } /*************************************************************/ /* */ /* cAppli_MMVII_Bench */ /* */ /*************************************************************/ /// entry point for all unary test /** This class contain all the unary test to check the validaty of command / classes / function relatively to their specs. For now its essentially a serie of function that are called linearly. When the test become long to execute, it may evolve with option allowing to do only some specific bench. */ class cAppli_MMVII_Bench : public cMMVII_Appli { public : cAppli_MMVII_Bench(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec); void Bench_0000_String(); void BenchFiles(); ///< A Bench on creation/deletion/existence of files int Exe() override; cCollecSpecArg2007 & ArgObl(cCollecSpecArg2007 & anArgObl) override ; cCollecSpecArg2007 & ArgOpt(cCollecSpecArg2007 & anArgOpt) override ; std::string mTest; int mNumBugRecall; }; cCollecSpecArg2007 & cAppli_MMVII_Bench::ArgObl(cCollecSpecArg2007 & anArgObl) { return anArgObl << Arg2007(mTest,"Unused, to check reentrance" ) ; } cCollecSpecArg2007 & cAppli_MMVII_Bench::ArgOpt(cCollecSpecArg2007 & anArgOpt) { return anArgOpt << AOpt2007(mNumBugRecall,"NBR","Num to Generate a Bug in Recall") ; } void cAppli_MMVII_Bench::Bench_0000_String() { // Bench elem sur la fonction SplitString std::vector<std::string> aSplit; SplitString(aSplit,"@ @AA BB@CC DD @ "," @"); MMVII_INTERNAL_ASSERT_bench(aSplit.size()==6,"Size in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(0)=="","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(1)=="AA","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(2)=="BB","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(3)=="CC","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(4)=="DD","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(aSplit.at(5)=="","SplitString in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("AA.tif")=="AA", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA.tif")=="tif","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA.tif",'t')=="if","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("a.b.c",'.',true,true)=="a.b", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("a.b.c",'.',true,false)=="a", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("a.b.c",'.',true,true)=="c", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("a.b.c",'.',true,false)=="b.c", "Prefix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA.",'.')=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench( Prefix("AA.",'.')=="AA","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix(".AA",'.')=="AA","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench( Prefix(".AA",'.')=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA",'.',true,true)=="AA","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("AA",'.',true,true)=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Postfix("AA",'.',true,false)=="","Postfix in Bench_0000_String"); MMVII_INTERNAL_ASSERT_bench(Prefix("AA",'.',true,false)=="AA","Postfix in Bench_0000_String"); } // std::string & aBefore,std::string & aAfter,const std::string & aStr,char aSep,bool SVP=false,bool PrivPref=true); cAppli_MMVII_Bench::cAppli_MMVII_Bench (const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) : cMMVII_Appli (aVArgs,aSpec), mNumBugRecall (-1) { MMVII_INTERNAL_ASSERT_always ( The_MMVII_DebugLevel >= The_MMVII_DebugLevel_InternalError_tiny, "MMVII Bench requires highest level of debug" ); // The_MMVII_DebugLevel = The_MMVII_DebugLevel_InternalError_weak; } static void CreateFile(const std::string & aNameFile) { cMMVII_Ofs aFile(aNameFile,false); int anI=44; aFile.Write(anI); } void cAppli_MMVII_Bench::BenchFiles() { const std::string & aTDir = TmpDirTestMMVII(); std::string aNameFile = aTDir+"toto.txt"; // Dir should be empty MMVII_INTERNAL_ASSERT_always(!ExistFile(aNameFile),"BenchFiles"); CreateFile(aNameFile); // File should now exist MMVII_INTERNAL_ASSERT_always(ExistFile(aNameFile),"BenchFiles"); // CreateFile(aTDir+"a/b/c/toto.txt"); Do not work directly CreateDirectories(aTDir+"a/b/c/",false); CreateFile(aTDir+"a/b/c/toto.txt"); // Now it works RemoveRecurs(TmpDirTestMMVII(),true,false); } void BenchFilterLinear(); int cAppli_MMVII_Bench::Exe() { // Begin with purging directory CreateDirectories(TmpDirTestMMVII(),true ); RemoveRecurs(TmpDirTestMMVII(),true,false); // On teste les macro d'assertion MMVII_INTERNAL_ASSERT_bench((1+1)==2,"Theoreme fondamental de l'arithmetique"); // La on a verifie que ca marchait pas // MMVII_INTERNAL_ASSERT_all((1+1)==3,"Theoreme pas tres fondamental de l'arithmetique"); BenchRecall(mNumBugRecall); BenchDenseMatrix0(); BenchGlobImage(); Bench_Nums(); BenchFiles(); Bench_0000_SysDepString(); Bench_0000_String(); Bench_0000_Memory(); Bench_0000_Ptxd(); Bench_0000_Param(); BenchSerialization(mDirTestMMVII+"Tmp/",mDirTestMMVII+"Input/"); BenchSet(mDirTestMMVII); BenchSelector(mDirTestMMVII); BenchEditSet(); BenchEditRel(); BenchEnum(); Bench_Random(); Bench_Duration(); BenchStrIO(); BenchFilterLinear(); // We clean the temporary files created RemoveRecurs(TmpDirTestMMVII(),true,false); // TestTimeV1V2(); => Valide ratio ~= 1 return EXIT_SUCCESS; } tMMVII_UnikPApli Alloc_MMVII_Bench(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) { return tMMVII_UnikPApli(new cAppli_MMVII_Bench(aVArgs,aSpec)); } cSpecMMVII_Appli TheSpecBench ( "Bench", Alloc_MMVII_Bench, "This command execute (many) self verification on MicMac-V2 behaviour", {eApF::Test}, {eApDT::None}, {eApDT::Console}, __FILE__ ); /* ========================================================= */ /* */ /* cAppli_MMRecall */ /* */ /* ========================================================= */ /** A class to test mecanism of MMVII recall itself */ class cAppli_MMRecall : public cMMVII_Appli { public : static const int NbMaxArg=2; cAppli_MMRecall(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec); int Exe() override; cCollecSpecArg2007 & ArgObl(cCollecSpecArg2007 & anArgObl) override; cCollecSpecArg2007 & ArgOpt(cCollecSpecArg2007 & anArgOpt) override; int mNum; ///< kind of idea of the call int mLev0; ///< to have the right depth we must know level of std::string mAM[NbMaxArg]; std::string mAO[NbMaxArg]; bool mRecalInSameProcess; int mNumBug; ///< Generate bug 4 this num }; cAppli_MMRecall::cAppli_MMRecall(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) : cMMVII_Appli (aVArgs,aSpec), mLev0 (0), mRecalInSameProcess (true), mNumBug (-1) { } int cAppli_MMRecall::Exe() { std::string aDirT = TmpDirTestMMVII() ; // Purge TMP if (mLevelCall == mLev0) { RemovePatternFile(aDirT+".*",true); } // to create a file with Num in name { std::string aNameF = aDirT + ToStr(mNum) + ".txt"; cMMVII_Ofs (aNameF,false); } MMVII_INTERNAL_ASSERT_always(mNum!=mNumBug,"Bug generate by user in cAppli_MMRecall"); // Break recursion if (mLevelCall-mLev0 >= NbMaxArg) return EXIT_SUCCESS; // Recursive call to two son N-> 2N, 2N+1, it's the standard binary tree like in heap, this make it bijective { std::vector<std::string> aLVal; aLVal.push_back(ToStr(2*mNum)); aLVal.push_back(ToStr(2*mNum+1)); cColStrAOpt aSub; eTyModeRecall aMRec = mRecalInSameProcess ? eTyModeRecall::eTMR_Inside : eTyModeRecall::eTMR_Serial; ExeMultiAutoRecallMMVII("0",aLVal ,aSub,aMRec); } // Test that we have exactly the expected file (e.g. 1,2, ... 31 ) and purge if (mLevelCall == mLev0) { tNameSet aSet1 = SetNameFromPat(aDirT+".*"); MMVII_INTERNAL_ASSERT_bench(aSet1.size()== ((2<<NbMaxArg) -1),"Sz set in cAppli_MMRecall"); tNameSet aSet2 ; for (int aK=1 ; aK<(2<<NbMaxArg) ; aK++) aSet2.Add( ToStr(aK) + ".txt"); MMVII_INTERNAL_ASSERT_bench(aSet1.Equal(aSet2),"Sz set in cAppli_MMRecall"); RemovePatternFile(aDirT+".*",true); } return EXIT_SUCCESS; } cCollecSpecArg2007 & cAppli_MMRecall::ArgObl(cCollecSpecArg2007 & anArgObl) { return anArgObl << Arg2007(mNum,"Num" ) << Arg2007(mAM[0],"Mandatory arg0" ) << Arg2007(mAM[1],"Mandatory arg1" ) // << Arg2007(mAM[2],"Mandatory arg2" ) // << Arg2007(mAM[3],"Mandatory arg3" ) ; } cCollecSpecArg2007 & cAppli_MMRecall::ArgOpt(cCollecSpecArg2007 & anArgOpt) { return anArgOpt << AOpt2007(mAO[0],"A0","Optional Arg 0") << AOpt2007(mAO[1],"A1","Optional Arg 1") // << AOpt2007(mAO[2],"A2","Optional Arg 2") // << AOpt2007(mAO[3],"A3","Optional Arg 3") << AOpt2007(mLev0,"Lev0","Level of first call") << AOpt2007(mRecalInSameProcess,"RISP","Recall in same process") << AOpt2007(mNumBug,"NumBug","Num 4 generating purpose scratch") ; } tMMVII_UnikPApli Alloc_TestRecall(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) { return tMMVII_UnikPApli(new cAppli_MMRecall(aVArgs,aSpec)); } cSpecMMVII_Appli TheSpecTestRecall ( "TestRecall", Alloc_TestRecall, "Use in Bench to Test Recall of MMVII by itself ", {eApF::Test}, {eApDT::None}, {eApDT::Console}, __FILE__ ); void OneBenchRecall(bool InSameP,int aNumBug) { cMMVII_Appli & anAp = cMMVII_Appli::CurrentAppli(); anAp.StrObl() << "1"; for (int aK=0 ; aK< cAppli_MMRecall::NbMaxArg; aK++) anAp.StrObl() << ToStr(10*aK); anAp.ExeCallMMVII ( TheSpecTestRecall, anAp.StrObl() , anAp.StrOpt() << t2S("Lev0",ToStr(1+anAp.LevelCall())) << t2S("RISP",ToStr(InSameP)) << t2S("NumBug",ToStr(aNumBug)) ); } void BenchRecall(int aNum) { OneBenchRecall(true,-1); OneBenchRecall(false,aNum); } /* ========================================================= */ /* */ /* cAppli_MPDTest */ /* */ /* ========================================================= */ /// A class to make quick and dirty test /** The code in this class will evolve quickly, it has no perenity, if a test become important it must be put in bench */ class cAppli_MPDTest : public cMMVII_Appli { public : cAppli_MPDTest(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec); int Exe() override; cCollecSpecArg2007 & ArgObl(cCollecSpecArg2007 & anArgObl) override {return anArgObl;} cCollecSpecArg2007 & ArgOpt(cCollecSpecArg2007 & anArgOpt) override {return anArgOpt;} }; cAppli_MPDTest:: cAppli_MPDTest(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) : cMMVII_Appli (aVArgs,aSpec) { } void TestArg0(const std::vector<int> & aV0) { for (auto I : aV0){I++; StdOut() << "I=" << I << "\n"; } } std::string BUD(const std::string & aDir); void TestBooostIter(); class cTestShared { public : cTestShared() {StdOut() << "CREATE cTestShared "<< this << "\n";;} ~cTestShared() {StdOut() << "XXXXXX cTestShared "<< this << "\n";;} static void Test() { cTestShared anOb; // std::shared_ptr<cTestShared> aT(&anOb); std::shared_ptr<cTestShared> aT(new cTestShared); } }; /* class cMultipleOfs : public std::ostream { public : cMultipleOfs(std::ostream & aos1,std::ostream & aos2) : mOs1 (aos1), mOs2 (aos2) { } std::ostream & mOs1; std::ostream & mOs2; template <class Type> cMultipleOfs & operator << (const Type & aVal) { mOs1 << aVal; mOs2 << aVal; return *this; } }; class cMultipleOfs : public std::ostream { public : cMultipleOfs() { } void Add(std::ostream & aOfs) {mVOfs.push_back(&aOfs);} std::vector<std::ostream *> mVOfs; template <class Type> cMultipleOfs & operator << (const Type & aVal) { for (const auto & Ofs : mVOfs) *Ofs << aVal; return *this; } }; */ void TestVectBool() { StdOut() << "BEGIN TBOOL \n"; getchar(); for (int aK=0 ; aK<5000 ; aK++) { std::vector<bool> * aV = new std::vector<bool>; for (int aK=0 ; aK<1000000 ; aK++) aV->push_back(true); } StdOut() << "END TBOOL \n"; getchar(); for (int aK=0 ; aK<5000 ; aK++) { std::vector<tU_INT1> * aV = new std::vector<tU_INT1>; for (int aK=0 ; aK<1000000 ; aK++) aV->push_back(1); } StdOut() << "END TBYTE \n"; getchar(); } bool F(const std::string & aMes) {std::cout <<"FFFFF=" << aMes << "\n"; return true;} #define UN 1 #define DEUX 2 // #include <limits> int cAppli_MPDTest::Exe() { if ((UN>DEUX) && F("aaaa")) { F("bbbb"); } F("ccccc"); /* cSparseVect<float> aSV; for (const auto & aP : aSV) { std::cout << aP.mI << "\n"; } */ /* cIm2D<tU_INT1> aIm(cPt2di(3,3)); aIm.DIm().SetV(cPt2di(0,0),13); // aIm.DIm().SetV(cPt2di(0,0),1000); // aIm.DIm().SetV(cPt2di(-1,0),1); // new cIm2D<tU_INT1>(cPt2di(3,3)); cDataIm2D<tU_INT1> & aDIm = aIm.DIm(); tU_INT1* aPtr = aDIm.RawDataLin(); StdOut() << "aIm=" << int(aPtr[0]) << "\n"; aPtr[0] = 14; StdOut() << "aIm=" << (int)aDIm.GetV(cPt2di(0,0)) << "\n"; // aPtr[-1] = 0; */ /* TestVectBool(); cMMVII_Ofs aOs1("toto1.txt"); cMMVII_Ofs aOs2("toto2.txt"); cMultipleOfs amOs; // (aOs1.Ofs(),aOs2.Ofs()); amOs.Add(aOs1.Ofs()); amOs.Add(aOs2.Ofs()); amOs << "1+1=" << 1+1 << "\n"; cMMVII_Ofs aFile("toto.txt"); std::ostream & anOFS = aFile.Ofs(); anOFS << "TEST OFFFSSSSSSSSSSSS\n"; */ return EXIT_SUCCESS; } tMMVII_UnikPApli Alloc_MPDTest(const std::vector<std::string> & aVArgs,const cSpecMMVII_Appli & aSpec) { return tMMVII_UnikPApli(new cAppli_MPDTest(aVArgs,aSpec)); } cSpecMMVII_Appli TheSpecMPDTest ( "MPDTest", Alloc_MPDTest, "This used a an entry point to all quick and dirty test by MPD ...", {eApF::Test}, {eApDT::None}, {eApDT::Console}, __FILE__ ); };
[ "marc.pierrot-deseilligny@ensg.eu" ]
marc.pierrot-deseilligny@ensg.eu
3a5e762d936f74010952e29c6e10da5236678d0f
6ed1c7d1f2aa137ce2ab879a4a5ddecb8e1790f5
/mltplinh/mltplinh.cpp
bd41514ed22337fb716b52da9d671491dcb50aab
[]
no_license
ruudkoot/Ammeraal
49eeb4a9731ff75fec6740224e2b24ef5a24da8a
535b0c4782bb181dc059ca427bb3cbc3174b9278
refs/heads/master
2023-05-11T15:46:18.480055
2020-09-07T18:44:09
2020-09-07T18:44:09
291,448,052
0
0
null
null
null
null
UTF-8
C++
false
false
895
cpp
// mltplinh.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> using namespace std; class p1 { public: p1(int n = 1) : n1(n) { cout << "p1(" << n << ")" << endl; } ~p1() { cout << "~p1()" << endl; } private: int n1; }; class p2 { public: p2(float x = 2.0f) : x2(x) { cout << "p2(" << x << ")" << endl; } ~p2() { cout << "~p2()" << endl; } private: float x2; }; class c : public p1, public p2 { public: c(bool b = true, int n = 3, float x = 4.0f) : p1(n), p2(x), bb(b) { cout << "c(" << b << "," << n << "," << x << ")" << endl; } ~c() { cout << "~c()" << endl; } private: bool bb; }; int main() { c cc(false); cout << sizeof p1 << endl; cout << sizeof p2 << endl; cout << sizeof c << endl; return 0; }
[ "inbox@ruudkoot.nl" ]
inbox@ruudkoot.nl
9baa977d091165ec1ec51a58a2f93a2a314c935e
cb39c039f974ce7362769d61fedc2f28f3b206e3
/source/NeutronSystem/Window.h
ecc73318aa2f63c6b38ee5c8bdd0ab701ef89f09
[]
no_license
yuen33/Neutron
87c95b59d451fadcee6b6f1c745a5dd605512c01
581d1a3c64745129a70f412a8d5d4fa1e7689cd7
refs/heads/master
2020-04-11T07:21:07.246738
2015-08-20T00:23:33
2015-08-20T00:23:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,879
h
#pragma once #include "ProcessingUnit.h" #include "NeutronFoundation/String.h" #include "Pin.h" #if defined NEUTRON_WINDOWS_DESKTOP #include <dxgi.h> #endif using Neutron::Container::String; namespace Neutron { namespace Engine { #if defined NEUTRON_WINDOWS_DESKTOP class NEUTRON_CORE Window : public ProcessingUnit { protected: static LRESULT wndproc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ); LRESULT msgproc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ); HWND hWnd; HINSTANCE hInstance; int width; int height; String title; boolean fullscreen; IDXGISwapChain* swapchain; // control flag boolean active; boolean updateFlag; boolean done; public: static ProcessingUnitPtr create( Device* owner ); Window( Device* owner ); virtual ~Window(); virtual boolean init( int width, int height, const char* title, bool fullscreen ); virtual void release(); virtual void onActive( bool active ); virtual void onPaint(); virtual void onEnterSizeMove(); virtual void onSize(); virtual void onExitSizeMove(); virtual void onSetCursor(); virtual void onChar( wchar code ); virtual void onRawInput( HRAWINPUT rawInput ); virtual void onClose(); virtual void onDestroy(); virtual boolean updateUnit(); virtual void update(); virtual void swap(); void run(); inline void stop() { done = true; } inline boolean isDone() const { return done; } inline int getWidth() const { return width; } inline int getHeight() const { return height; } inline const char* getTitle() const { return title.getCStr(); } inline boolean isFullscreen() const { return fullscreen; } inline const void* getHandle() const { return hWnd; } inline void setSwapChain( IDXGISwapChain* sc ) { swapchain = sc; } }; #endif } }
[ "drvkize@gmail.com" ]
drvkize@gmail.com
b7e5151e5071c02a986c8585d5e15258faecaa30
337e275fb67b008ca92bf8a3162e88653bc8198d
/Tools/qbfpvf_proto/verify.cpp
fbc78f7c35c084336411723221ae8bceab5555eb
[]
no_license
arey0pushpa/qbf-cert
2956e10192b9622b81c58492c97efd7ef6bd893f
a0f9c77edb9cd09a16261447146e0a1f494bae55
refs/heads/master
2021-09-16T02:07:02.322911
2021-08-01T21:55:32
2021-08-01T21:55:32
199,707,111
0
0
null
null
null
null
UTF-8
C++
false
false
20,258
cpp
#include "common.h" #include "lexer.h" bool cfg_gc = true; // Do garbage collection class Variable { private: lit_int_t v; public: inline explicit Variable(lit_int_t _v) : v(_v) { assert (v>=0); }; inline size_t idx() const {return static_cast<size_t>(v);}; inline string str() const {return to_string(v);} inline lit_int_t raw() const {return v; } inline bool operator ==(Variable const&var) const {return v==var.v;}; inline bool operator !=(Variable const&var) const {return v!=var.v;}; inline bool in_bounds(size_t num_vars) const {return idx()<=num_vars; } inline bool is_valid() const {return v!=0;} public: static Variable const invalid; }; Variable const Variable::invalid = Variable(0); class Literal { private: lit_int_t l; public: inline Literal() : l(0) {}; inline explicit Literal(lit_int_t _l) : l(_l) {}; inline explicit Literal(Variable const&v) : l(v.raw()) {} inline bool is_valid() const {return l!=0;} inline string str() const {return std::to_string(l);} inline lit_int_t raw() const {return l;} inline bool operator ==(Literal const&lit) const {return l==lit.l;}; inline bool operator !=(Literal const&lit) const {return l!=lit.l;}; // inline bool operator <(Literal const&lit) const {return abs(l) < abs(lit.l); }; inline Literal neg() const { assert(is_valid()); return Literal(-l);} inline Literal operator -() const {return neg();} Variable var() const {return Variable(abs(l));} static Literal const invalid; inline bool in_bounds(size_t num_vars) const {return var().in_bounds(num_vars); } }; Literal const Literal::invalid = Literal(0); enum class Quant { ALL, EX }; // Map from everything that can be converted to size_t. // T must default-initialize to T::invalid, and have an is_valid() method inline size_t to_size_t(size_t x) {return x;} inline size_t to_size_t(Variable v) {return v.idx();} template<typename K,typename V> class Basic_Int_Cnv_Map { private: vector<V> map; public: inline V lookup(K key) const { size_t i = to_size_t(key); if (i<map.size()) return map[i]; else return V(); } inline V& define(K key) { size_t i = to_size_t(key); if (!(i<map.size())) map.resize(i+1); return map[i]; } inline K next_key() const {return K(map.size());} inline K define_next(V const &v) { K res = K(map.size()); map.push_back(v); return res; } inline void print_stats(string name) { log(name+": " + pretty_vector_stats(map)); } public: typedef typename vector<V>::iterator iterator; typedef typename vector<V>::const_iterator const_iterator; iterator begin() {return map.begin();} iterator end() {return map.end();} const_iterator begin() const {return map.begin();} const_iterator end() const {return map.end();} }; template<typename K,typename V> class Int_Cnv_Map : public Basic_Int_Cnv_Map<K,V> { public: inline bool contains(K k) const { return (this->lookup(k).is_valid()); } inline V const& the_lookup(K k) const { assert(contains(k)); return this->lookup(k); } inline V& the_lookup(K k) { assert(contains(k)); return this->define(k); } inline void remove(K k) { the_lookup(k) = V(); } inline void remove_if_ex(K k) { if (contains(k)) remove(k); } }; template<typename T> class Basic_Varmap : public Basic_Int_Cnv_Map<Variable,T> {}; template<typename T> class Varmap : public Int_Cnv_Map<Variable,T> {}; template<typename T, T invalid_val> class Wrap_Invalid { private: T x = invalid_val; public: inline Wrap_Invalid() : x(invalid_val) {} inline Wrap_Invalid(T _x) : x(_x) {} inline operator T() const {return x;} inline bool is_valid() const {return x!=invalid_val;} }; template<typename T, T invalid_val> class Wrap_Invalid_Expl { private: T x = invalid_val; public: inline Wrap_Invalid_Expl() : x(invalid_val) {} explicit inline Wrap_Invalid_Expl(T _x) : x(_x) {} explicit inline operator T() const {return x;} inline bool is_valid() const {return x!=invalid_val;} }; class ClauseDB { private: // Quantifiers Varmap<Wrap_Invalid<size_t,0>> varpos; // Counting starts at 1, zero for invalid variable size_t cur_pos = 1; Basic_Varmap<Quant> varq; // Quantifier of variable Variable max_var = Variable::invalid; public: inline size_t get_pos(Variable v) { return varpos.the_lookup(v); } inline bool is_valid(Variable v) { return varpos.contains(v); } inline Quant get_q(Variable v) { assert(is_valid(v)); return varq.lookup(v); } inline Quant get_q(Literal l) { return get_q(l.var()); } inline void add_var(Quant q, Variable v) { if (varpos.contains(v)) error("Duplicate variable declaration " + v.str()); varpos.define(v) = cur_pos++; varq.define(v) = q; if (v.idx()>max_var.idx()) max_var=v; } Variable get_maxvar() { return max_var; } // Literals are ordered by variable position inline bool less_lit(Literal l1, Literal l2) { return get_pos(l1.var()) < get_pos(l2.var()); } public: typedef Wrap_Invalid_Expl<size_t,0> ClauseId; typedef Wrap_Invalid_Expl<size_t,SIZE_MAX> Clause_Iterator; private: // Clauses vector<Literal> db; // The clause database Int_Cnv_Map<ClauseId,Clause_Iterator> idmap; // Map from clause IDs to start positions in database. size_t last_clause_start = SIZE_MAX; Quant reduceq = Quant::EX; // Quantifier on which reduction can be performed bool initialized=false; bool contains_empty_flag = false; // True if this contains the empty clause size_t db_max = 0; size_t active_clauses = 0; // Number of active clauses size_t db_clauses = 0; // Number of clauses in DB size_t stat_num_gcs = 0; public: // Create clause inline void start_clause() { assert(initialized); assert(last_clause_start == SIZE_MAX); last_clause_start = db.size(); } // returns argument. Makes for more elegant parsing loops. inline Literal add_lit(Literal l) { assert(initialized); assert(last_clause_start!= SIZE_MAX); if (l.is_valid()) db.push_back(l); // Ignore final 0, will be added by commit-clause db_max = max(db_max,db.capacity()); return l; } inline void discard_clause() { assert(initialized); assert(last_clause_start!= SIZE_MAX); assert(last_clause_start <= db.size()); db.resize(last_clause_start); last_clause_start = SIZE_MAX; } // Note: If clause is not sorted, sort must be true. inline ClauseId commit_clause(bool sort, bool reduce=true) { assert(initialized); assert(last_clause_start!= SIZE_MAX); assert(last_clause_start <= db.size()); if (sort) { std::sort(db.begin() + last_clause_start, db.end(),[this](Literal a, Literal b){return less_lit(a,b);}); } if (reduce) { // Find new ending position size_t i = db.size(); while (i>last_clause_start && get_q(db[i-1]) == reduceq) --i; db.resize(i); } if (last_clause_start==db.size()) contains_empty_flag=true; // Append terminator 0 db.push_back(Literal::invalid); db_max = max(db_max,db.capacity()); ClauseId res = idmap.define_next(Clause_Iterator(last_clause_start)); last_clause_start = SIZE_MAX; ++active_clauses; ++db_clauses; return res; } inline ClauseId cur_id() {return idmap.next_key();} inline void remove(ClauseId cid) { idmap.remove(cid); assert(active_clauses); --active_clauses; // Trigger garbage collection when too empty (e.g. more than half of the clauses deleted). Arbitrary threshold of 1000 to avoid frequent smallish GCs. if (cfg_gc && db_clauses / 2 > active_clauses && db_clauses>1000) compact(); /* TODO * Counting literals (i.e. db storage space) may be more precise, but requires a num-literals field, or literal counting on removal) * Literal count of clause may be given as hint, as it will be known from previous resolution step anyway! */ } inline Clause_Iterator lookup(ClauseId cid) { if (!idmap.contains(cid)) error("Invalid clause/cube id: " + to_string((size_t)cid)); return idmap.the_lookup(cid); } inline Literal ci_peek(Clause_Iterator it) { assert((size_t)it < db.size()); return db[(size_t)it]; } inline bool ci_at_end(Clause_Iterator it) { return !ci_peek(it).is_valid(); } inline Literal ci_next(Clause_Iterator &it) { Literal res=ci_peek(it); it=Clause_Iterator((size_t)it + 1); return res; } inline bool contains_empty() {return contains_empty_flag;} ClauseId resolution(ClauseId cid1, ClauseId cid2) { auto ci1 = lookup(cid1); auto ci2 = lookup(cid2); start_clause(); /* Merge, eliminating duplicates, and allowing one resolution. * * This assumes that the clauses are sorted (which is an invariant for all clauses in the db) */ bool seen_res_lit=false; while (!ci_at_end(ci1) && !ci_at_end(ci2)) { Literal l1 = ci_peek(ci1); Literal l2 = ci_peek(ci2); if (less_lit(l1,l2)) { // l1 < l2 add_lit(l1); ci_next(ci1); } else if (l1 == l2) { add_lit(l1); ci_next(ci1); ci_next(ci2); } else if (l1 == -l2) { if (seen_res_lit) error("Resolution yields tautology: literal " + l1.str()); ci_next(ci1); ci_next(ci2); seen_res_lit=true; } else { add_lit(l2); ci_next(ci2); } } // Handle rest while (!ci_at_end(ci1)) add_lit(ci_next(ci1)); while (!ci_at_end(ci2)) add_lit(ci_next(ci2)); if (!seen_res_lit) error("No resolution"); // We make this an error, though it would be sound to simply combine two clauses without resolution // Commit clause. Reduce. Sorting not required, b/c already sorted due to merge of sorted clauses. return commit_clause(false,true); } private: // Garbage collection void compact() { // Iterate over ID map // Assume/assert clause positions are in ascending order // Copy CDB backwards and adjust addresses assert(active_clauses <= db_clauses); size_t dsti = 0; // New current position in DB // clog<<"GC "<<active_clauses<<" "<<db_clauses<<endl; #ifndef NDEBUG size_t new_active = 0; #endif for (auto it = idmap.begin(); it!=idmap.end(); ++it) { if (it->is_valid()) { size_t srci = (size_t)(*it); size_t new_addr = dsti; assert(srci >= dsti); while (true) { assert(srci < db.size()); Literal l=db[srci]; db[dsti]=l; ++srci; ++dsti; if (!l.is_valid()) break; } *it = Clause_Iterator(new_addr); #ifndef NDEBUG ++new_active; #endif } } assert(new_active == active_clauses); db_clauses = active_clauses; assert(dsti<=db.size()); db.resize(dsti); // db.shrink_to_fit(); // Currently, we don't free the memory, as it may be used by new clauses ++stat_num_gcs; } public: ClauseDB() {} void initialize(Quant _reduceq) { assert(!initialized); reduceq = _reduceq; // Clause-ID 0 does not exist. We just add an invalid ID here. [[maybe_unused]]ClauseId id0 = idmap.define_next(Clause_Iterator()); assert((size_t)id0 == 0); initialized=true; } void print_stats() { varpos.print_stats("varpos map"); varq.print_stats("varq map"); idmap.print_stats("id map"); log("max clause db: " + pretty_size(db_max * sizeof(Literal))); log("number of gcs: " + to_string(stat_num_gcs)); } }; inline size_t to_size_t(ClauseDB::ClauseId cid) {return (size_t)cid;} /* * Parallel Valuation. Uses bit-vectors to store multiple valuations in parallel. * Bit-vectors fit into machine-words here. */ class ParValuation { public: typedef uint64_t mask_t; private: static_assert(numeric_limits<mask_t>::is_integer,""); static_assert(!numeric_limits<mask_t>::is_signed,""); static const size_t bit_width = sizeof(mask_t)*8; static const mask_t max_mask = ((mask_t)1)<<(bit_width-1); private: mask_t cur_mask=1; // Bit that is currently added. 0 when full. private: size_t n = 0; mask_t *base = NULL; mask_t *m = NULL; ParValuation(ParValuation const &) = delete; ParValuation &operator=(ParValuation const &) = delete; private: inline bool in_range(Literal l) {return (size_t)(abs(l.raw())) <= n;} public: void clear() { assert(m); fill(base,base+(2*n+1),0); cur_mask=1; } void init(size_t _n) { assert(!m && _n>0); n=_n; base = new mask_t[2*n+1]; m = base + n; clear(); log("Using deferred initial cube checking, bit_width = " + to_string(bit_width)); } void init(Variable max_var) { init(max_var.idx()); } ParValuation() {} ParValuation(size_t _n) { init(_n); } ~ParValuation() { if (base) delete [] base;} // Getting and setting literals inline void set(Literal l) { assert(m); assert(in_range(l)); auto li = l.raw(); assert((m[-li]&cur_mask) == 0); m[li]|=cur_mask; } inline mask_t get(Literal l) { assert(m && in_range(l)); auto i = l.raw(); return m[i]; } // Management of remaining slots inline bool is_full() { return cur_mask == 0; } inline bool is_empty() { return cur_mask==1; } inline void next_slot() { assert(!is_full()); cur_mask<<=1; } // All used bits inline mask_t bits() { return cur_mask-1; } public: void print_stats() { log("Par-Valuation: " + pretty_size((2*n+1)*sizeof(mask_t))); } }; class Initial_Cube_Checker { private: vector<Literal> clauses; ParValuation val; // ClauseDB &db; public: // inline Initial_Cube_Checker(ClauseDB &_db) : db(_db) {} // Disabled, as this causes funny double-exceptions when error is thrown in flush_checks() // inline ~Initial_Cube_Checker() { // flush_checks(); // } // Must be called before cubes can be checked. Literals can be added earlier. inline void init(Variable max_var) { val.init(max_var); } // Add literals and 0s of formula's clauses inline Literal add_fml_lit(Literal l) {clauses.push_back(l); return l;} // Add next literal of a cube inline void add_cube_lit(Literal l) { assert(!val.is_full()); val.set(l); } // Declare current cube as finished (and get ready for next one) inline void commit_cube() { val.next_slot(); if (val.is_full()) flush_checks(); } // inline void check_cube(ClauseDB::Clause_Iterator cid) { // if (val.is_full()) flush_checks(); // assert(!val.is_full()); // // // Initialize this slot of parallel valuation with cube's literals // clog<<"icube "<<endl; // for (;!db.ci_at_end(cid);db.ci_next(cid)) { // clog<<db.ci_peek(cid).str()<<" "; // val.set(db.ci_peek(cid)); // } // clog<<"0"<<endl; // // val.next_slot(); // } inline void flush_checks() { if (val.is_empty()) return; // Nothing to check ParValuation::mask_t bits = val.bits(); // The outer loops iterates over the clauses, consuming the final zero in each increment step for (auto it = clauses.begin(); it!=clauses.end();++it) { ParValuation::mask_t m=0; // Accumulate valuation over literals of clause while (it->is_valid()) { m|=val.get(*it); ++it; assert(it!=clauses.end()); } // Check if (m != bits) { // clog<<m<<" != "<<bits<<endl; error("Initial cube check failed"); } } // Everything checked. Flush. val.clear(); } void print_stats() { log("ICC formula clauses: " + pretty_vector_stats(clauses)); } }; class Verifier { private: MMap_Range fml_range; MMap_Range prf_range; Lexer plx; ClauseDB db; Initial_Cube_Checker icc; size_t prf_first_id = 0; bool sat_mode = false; bool verified = false; public: Verifier(string dimacs_file, string proof_file) : fml_range(dimacs_file), prf_range(proof_file), plx(prf_range), db(), icc() { } inline bool is_sat() {assert(verified); return sat_mode;} // Parsing private: void parse_prf_header() { plx.eol(); plx.keyword("p"); plx.keyword("redcqrp"); prf_first_id = plx.unsafe_id_int(); plx.eol(); plx.keyword("r"); { string s = plx.word(); if (s=="SAT") sat_mode=true; else if (s=="UNSAT") sat_mode=false; else error("Unknown mode: " + s); plx.eol(); } // Initialize db db.initialize(sat_mode? Quant::EX : Quant::ALL); } static inline Literal parse_literal(Lexer &lx) { return Literal(lx.lit_int()); } static inline Literal parse_unsafe_literal(Lexer &lx) { return Literal(lx.unsafe_lit_int()); } void parse_formula() { Lexer lx(fml_range); // Header (Everything ignored) lx.eol(); lx.keyword("p"); lx.keyword("cnf"); lx.id_int(); lx.id_int(); lx.eol(); // Variable declarations while (true) { // Parse quantifier, break if no more quantifiers Quant q; if (lx.peek()=='e') q=Quant::EX; else if (lx.peek()=='a') q=Quant::ALL; else break; lx.next(); lx.eow(); // Parse variable list { lit_int_t v; while (true) { v = lx.var_int(); if (v==0) break; db.add_var(q,Variable(v)); } } lx.eol(); } if (sat_mode) icc.init(db.get_maxvar()); // Clauses while (!lx.is_eof()) { if (sat_mode) { // Parse formula clauses to their own database while (icc.add_fml_lit(parse_literal(lx)).is_valid()) {}; lx.eol(); } else { // Parse formula clauses to main database db.start_clause(); while (db.add_lit(parse_literal(lx)).is_valid()) {}; lx.eol(); // Sort and reduce db.commit_clause(true,true); } } // Check match of implicit IDs if ((size_t)db.cur_id() != prf_first_id) { error("Current ID after parsing formula ("+to_string((size_t)db.cur_id())+") " + "does not match start ID declared in proof header ("+to_string(prf_first_id)+")"); } } inline auto parse_delid() { bool del = plx.peek()=='d'; if (del) plx.next(); return make_pair(ClauseDB::ClauseId(plx.unsafe_id_int()), del); } void parse_proof() { while (!plx.is_eof() && !db.contains_empty()) { if (plx.peek() == '0') { // Initial cube plx.unsafe_id_int(); // Skip the zero if (!sat_mode) error("Initial cube step in SAT mode"); // Read cube, and add all its literals to cube checker. // NOTE we must add all literals. Some of them may be lost after reduction upon commit_clause. db.start_clause(); while (true) { Literal l = Literal(plx.lit_int()); if (!l.is_valid()) break; db.add_lit(l); icc.add_cube_lit(l); } plx.eol(); // Commit cube to cube checker icc.commit_cube(); // Commit cube to DB (sorts and reduces) db.commit_clause(true,true); } else { // Resolution step auto [cid1,del1] = parse_delid(); auto [cid2,del2] = parse_delid(); plx.eol(); db.resolution(cid1,cid2); if (del1) db.remove(cid1); if (del2) db.remove(cid2); } } if (sat_mode) icc.flush_checks(); if (!db.contains_empty()) error("Found no empty clause/cube"); if (!plx.is_eof()) log("Proof file contains additional content after empty clause/cube was produced"); } public: void do_check() { parse_prf_header(); parse_formula(); parse_proof(); verified=true; } void print_stats() { db.print_stats(); if (sat_mode) icc.print_stats(); } }; int main(int argc, char **argv) { try { if (argc != 3) error("Usage: verify <qdimacs-file> <proof-file>"); Verifier vrf(argv[1],argv[2]); vrf.do_check(); if (vrf.is_sat()) cout<<"s SAT"<<endl; else cout<<"s UNSAT"<<endl; vrf.print_stats(); return 0; } catch (exception &e) { cout<<"s ERROR"<<endl; cerr<<e.what()<<endl; return 1; }; }
[ "plammich@gmail.com" ]
plammich@gmail.com
5ce8041808ab76ce0c7e43affd14b93962080908
fa55d8ed32564195f2687d1e18b99f80c5683073
/lbc_lintcodeII/212-space-replacement.cc
1baf76fe728c8e0ed2dc4a403d1258550ea8e484
[]
no_license
TenFifteen/SummerCamp
1841bf1bd212938cee818540658185cd3e429f0c
383b9321eee9e0721772f93a897c890f737f2eff
refs/heads/master
2020-04-05T23:48:01.393256
2018-03-11T12:37:38
2018-03-11T12:37:38
38,595,086
9
4
null
2016-07-18T14:21:15
2015-07-06T03:15:55
C++
UTF-8
C++
false
false
902
cc
/* 题目大意: 给定一个字符串,将其中的空格替换成20%,原地替换。 解题思路: 见代码。 遇到的问题: 没有。 */ class Solution { public: /** * @param string: An array of Char * @param length: The true length of the string * @return: The true length of new string */ int replaceBlank(char string[], int length) { // Write your code here int len = length; for (int i = 0; i < length; ++i) { if (string[i] == ' ') len += 2; } int index = len-1; for (int i = length-1; i >= 0; --i) { if (string[i] == ' ') { string[index--] = '0'; string[index--] = '2'; string[index--] = '%'; } else { string[index--] = string[i]; } } return len; } };
[ "libenchao@gmail.com" ]
libenchao@gmail.com
83af50aa01d6d4f6082ef28c710a6cc2212d5b16
28f43281141abdaebe57909cfe59897dc256ede4
/cpp_module_02/ex00/main.cpp
9fbeaa838383f32e7246ca4e1017efcb86c1c193
[]
no_license
benjaminmerchin/piscine_CPP
d4476f05da9891c2e5c0eab5f1c46a44c3391a36
4a507669b3877662badb230d807d7f2ad19ce05d
refs/heads/main
2023-07-16T14:12:35.460993
2021-08-30T10:50:32
2021-08-30T10:50:32
383,801,709
4
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
#include "Fixed.hpp" int main(void) { Fixed a; Fixed b(a); Fixed c; c = b; std::cout << a.getRawBits() << std::endl; std::cout << b.getRawBits() << std::endl; std::cout << c.getRawBits() << std::endl; return 0; }
[ "benjaminmerchin@gmail.com" ]
benjaminmerchin@gmail.com
0fcbc76674961ba16fd3e6349be4230e9f9fb33c
d4da977bb5f060d6b4edebfdf32b98ee91561b16
/Note/集训队作业/2014/作业1/试题泛做/ytl13508111107/ytl/题目与程序/D6545. Bee Breeding/ran/bc.cpp
863bb228172e2060129223673c106dccc7874f3d
[]
no_license
lychees/ACM-Training
37f9087f636d9e4eead6c82c7570e743d82cf68e
29fb126ad987c21fa204c56f41632e65151c6c23
refs/heads/master
2023-08-05T11:21:22.362564
2023-07-21T17:49:53
2023-07-21T17:49:53
42,499,880
100
22
null
null
null
null
UTF-8
C++
false
false
1,069
cpp
e2 5406 0 R >> endobj 5236 0 obj [ 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000 1000
[ "lychees67@gmail.com" ]
lychees67@gmail.com
8d25b9e69968738c10b05071cde8178b1ddc2ac6
1bd9e3cda029e15d43a2e537663495ff27e317e2
/buoyantPimpleFoam_timevaryingBC/timevaryingCavityFoam/58/uniform/cumulativeContErr
a7fd54fe5635b3c993fbec8012e1fd58acb2d7b2
[]
no_license
tsam1307/OpenFoam_heatTrf
810b81164d3b67001bfce5ab9311d9b3d45b5c9d
799753d24862607a3383aa582a6d9e23840c3b15
refs/heads/main
2023-08-10T23:27:40.420639
2021-09-18T12:46:01
2021-09-18T12:46:01
382,377,763
1
0
null
null
null
null
UTF-8
C++
false
false
956
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2006 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class uniformDimensionedScalarField; location "58/uniform"; object cumulativeContErr; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; value -1.62605e-13; // ************************************************************************* //
[ "tsinghsamant@gmail.com" ]
tsinghsamant@gmail.com
5c63bcca69e8a9c1f8b64bbae196c5d7ea4d7e77
cd746ef05caa7bfc71aff7076179e8bb46f0f9f4
/Chapter10cpp/wci/backend/interpreter/executors/IfExecutor.h
aee8fb30311d454b64df28d3173ffec087f4095c
[]
no_license
NikkiR97/complex
93c722ef020d2046faf628228dd09670de67d9b0
6789376c082dc7c6a6391de1a64c045300ab569a
refs/heads/master
2020-04-27T15:35:14.695973
2019-03-08T04:02:30
2019-03-08T04:02:30
174,451,846
1
0
null
null
null
null
UTF-8
C++
false
false
993
h
/** * <h1>IfExecutor</h1> * * <p>Execute an IF statement.</p> * * <p>Copyright (c) 2017 by Ronald Mak</p> * <p>For instructional purposes only. No warranties.</p> */ #ifndef IFEXECUTOR_H_ #define IFEXECUTOR_H_ #include "StatementExecutor.h" #include "../../../Object.h" #include "../../../intermediate/ICodeNode.h" namespace wci { namespace backend { namespace interpreter { namespace executors { using namespace std; using namespace wci; using namespace wci::backend::interpreter; using namespace wci::intermediate; class IfExecutor : public StatementExecutor { public: /** * Constructor. * @param the parent executor. */ IfExecutor(Executor *parent); /** * Execute a compound statement. * @param node the root node of the compound statement. * @return nullptr. */ Object execute(ICodeNode *node); }; }}}} // namespace wci::backend::interpreter::executors #endif /* IFEXECUTOR_H_ */
[ "jhjuchau@gmail.com" ]
jhjuchau@gmail.com
9044dc69514ec1956be70e06a24bf66991c2bd0e
2885e54c807bd70b8eb0cd2bc3ffd5ce51bd66cc
/2007-PIR-Drone Trirotor acrobate/Projet/Informatique/CNES/marmottes-9.8/src/ModeleCine.cpp
15611290d96643a49f9bd615b0dfcb7081cccd65
[]
no_license
crubier/my-personal-projects
622b09ce6d9c846b905fe135892a178c1a0c554b
8cd26b212b0c61f3d5bbe2de82d49891f3f3602a
refs/heads/master
2021-09-12T23:09:14.097634
2018-04-22T07:45:42
2018-04-22T07:45:42
130,488,289
1
0
null
null
null
null
ISO-8859-1
C++
false
false
6,949
cpp
/////////////////////////////////////////////////////////////////////////////// //$<AM-V1.0> // //$Type // DEF // //$Projet // Marmottes // //$Application // Marmottes // //$Nom //> ModeleCine.cpp // //$Resume // fichier d'implantation de la classe ModeleCine // //$Description // Module de définition de la classe // //$Contenu //> class ModeleCine //> ModeleCine() //> operator =() //> prendConsignesEnCompte() //> miseAJourOmegaMax() //> attitude() // //$Historique // $Log: ModeleCine.cpp,v $ // Revision 1.20 2003/02/04 16:30:30 marmottes // DM-ID 17 Mise à jour de l'extension du fichier dans le bandeau // // Revision 1.19 2002/01/17 09:22:41 marmottes // (prendConsignesEnCompte): génération de l'erreur consignes_gyro_elevees (FA 0001) // // Revision 1.18 2001/01/25 16:29:20 luc // modification de la valeur par défaut de la vitesse maximale de // rotation de 2 radians par seconde à 0.4 radian par seconde // // Revision 1.17 2000/06/07 16:43:40 filaire // correction d'une erreur de signe // // Revision 1.16 2000/06/07 14:08:04 luc // correction d'une erreur de valeur absolue // // Revision 1.15 2000/03/30 17:01:19 luc // ajout du copyright CNES // // Revision 1.14 2000/03/14 17:16:50 luc // correction d'une discontinuité du modèle pour les spins faibles mais // non nuls (introduction d'un développement limité du sinus cardinal) // // Revision 1.13 1999/08/06 13:32:13 filaire // Passage à la gestion des erreurs par les exceptions // // Revision 1.12 1999/07/29 12:15:17 filaire // Modification de la signature de la fonction prendConsignesEnCompte // // Revision 1.12 1999/07/02 07:23:07 geraldine // modification de la signature de prendConsignesEnCompte // utilisation des exceptions // // Revision 1.11 1998/10/05 15:24:56 luc // élimination de DBL_EPSILON pour éviter des problèmes de portabilité // contournement d'un bug du compilateur Sun // // Revision 1.10 1998/08/04 06:59:10 luc // réduction de l'intervalle de validité de la variable libre // de [-1 ; +1] à [0 ; 1] // // Revision 1.9 1998/06/24 19:58:40 luc // élimination des variables statiques RCS // modification du format des en-têtes // // Revision 1.8 1998/04/26 18:25:08 luc // inversion de la convention de nommage des attributs // // Revision 1.7 1998/02/19 16:19:02 luc // déplacement d'un constructeur inline dans le .cc // pour contourner un problème d'optimiseur avec g++ 2.8.0 // // Revision 1.6 1997/09/23 09:28:10 luc // utilisation de la consigne indépendante des unités de sortie // pour la modélisation interne // // Revision 1.5 1997/08/20 08:27:17 luc // ajout d'un en-tête de fichier // utilisation du valeurConsigne () commun à tous les senseurs à la place // du omega () spécifique aux senseurs cinématiques qui disparaît // // Revision 1.4 1997/04/27 19:35:50 luc // inversion des codes de retour // changement des règles de nommage // passage de SCCS à RCS // // Revision 1.3 1996/10/03 14:39:58 luc // correction du modèle des consignes en spin // // Revision 1.2 1995/01/27 16:59:56 mercator // propagation du spin dans tous les calculs depuis la modelisation // jusqu'a la sauvegarde de la solution finale dans l'etat // // Revision 1.1 1995/01/27 10:48:27 mercator // Initial revision // //$Version // $Id: ModeleCine.cpp,v 1.20 2003/02/04 16:30:30 marmottes Exp $ // //$Auteur // L. Maisonobe CNES // Copyright (C) 2000 CNES //$<> /////////////////////////////////////////////////////////////////////////////// #include "marmottes/ModeleCine.h" #include "marmottes/SenseurCinematique.h" ModeleCine::ModeleCine () : omegaMax_ (0.4) {} ModeleCine& ModeleCine::operator = (const ModeleCine& m) { if (&m != this) // protection contre x = x { u_ = m.u_; v_ = m.v_; thetaMax_ = m.thetaMax_; omegaMax_ = m.omegaMax_; } return *this; } void ModeleCine::prendConsignesEnCompte () throw (MarmottesErreurs) { SenseurCinematique* s1 = (SenseurCinematique *) senseur1 (); SenseurCinematique* s2 = (SenseurCinematique *) senseur2 (); double scal = s1->sensible () | s2->sensible (); double denominateur = 1.0 - scal * scal; if ((denominateur >= -1.0e-12) && (denominateur <= 1.0e-12)) throw MarmottesErreurs (MarmottesErreurs::gyros_coaxiaux); u_ = VecDBLVD1 ((s1->sensible () * (s1->omega () - s2->omega () * scal) + s2->sensible () * (s2->omega () - s1->omega () * scal) ) / denominateur); v_ = VecDBLVD1 (s1->sensible () ^ s2->sensible ()); double theta2V2 = omegaMax_ * omegaMax_ - (u_ | u_).f0 (); if (theta2V2 <= 0.0) throw MarmottesErreurs (MarmottesErreurs::consignes_gyro_elevees, s1->nom ().c_str (), s2->nom ().c_str (), degres (omegaMax_)); thetaMax_ = sqrt (theta2V2 / (v_ | v_).f0 ()); } void ModeleCine::miseAJourOmegaMax (double omega) throw (MarmottesErreurs) { if (omega <= 0.0) throw MarmottesErreurs (MarmottesErreurs::omega_neg, omega); omegaMax_ = omega; } void ModeleCine::attitude (const Etat& etatPrecedent, double date, const ValeurDerivee1& t, int famille, RotVD1* ptrAtt, VecVD1* ptrSpin) const { // modélisation de la rotation autour des gyros 1 et 2 double dtSur2 = 43200.0 * (date - etatPrecedent.date ()); ValeurDerivee1 theta ((t * 2.0 - 1.0) * thetaMax_); *ptrSpin = u_ + v_ * theta; ValeurDerivee1 vitesse (ptrSpin->norme ()); ValeurDerivee1 demiAngle = vitesse * dtSur2; ValeurDerivee1 sinCardinal; if (fabs (demiAngle.f0 ()) < 4.0e-4) { // si l'angle est trop petit, on utilise un développement limité // pour calculer sin (alpha) / alpha. En se limitant à l'ordre 4, // on obtient les erreurs relatives suivantes : 8.1e-25 sur // la valeur, 9.1e-17 pour la dérivée (pour des demi-angles // inférieurs à 4e-4) ValeurDerivee1 alpha2 = demiAngle * demiAngle; sinCardinal = (120.0 - alpha2 * (20.0 - alpha2)) / 120.0; } else sinCardinal = sin (demiAngle) / demiAngle; // rotation autour de l'axe de spin depuis la date de l'attitude précédente ValeurDerivee1 q0 = cos (demiAngle); VecVD1 q = *ptrSpin * (sinCardinal * dtSur2); RotVD1 evolution (q0, q.x (), q.y (), q.z ()); // calcul de l'attitude après évolution *ptrAtt = evolution (etatPrecedent.attitudeVD1 ()); }
[ "vincent.lecrubier@gmail.com" ]
vincent.lecrubier@gmail.com
097a3e358def8251e2084cdf4d2755e737d5bbed
d2c3b5de367707f5049a478044e2e9bb1eafd7ea
/components/hub-wifi/wifi.cpp
ab3ac684c1227b0d6da552a031c2761a82b73ce3
[]
no_license
kazuph/home-iot-hub
56d871cc7f52d0ec7e48cc6458c85ba6f3e9523d
108ff4fc4973d1b0ef95be4861557a8dfab5777c
refs/heads/main
2023-08-28T19:34:57.932493
2021-10-21T06:15:15
2021-10-21T06:15:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,719
cpp
#include "wifi/wifi.hpp" #include <cstring> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/event_groups.h" #include "esp_system.h" #include "esp_netif.h" #include "esp_event.h" #include "esp_log.h" #include "nvs.h" #include "nvs_flash.h" #include "lwip/err.h" #include "lwip/sys.h" namespace hub::wifi { constexpr const char* TAG { "hub::wifi" }; constexpr EventBits_t WIFI_CONNECTED_BIT { BIT0 }; static EventGroupHandle_t wifi_event_group; static void event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { esp_err_t result = ESP_OK; if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) { result = esp_wifi_connect(); if (result != ESP_OK) { ESP_LOGE(TAG, "WiFi connection failed with error code %x [%s].", result, esp_err_to_name(result)); } } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) { result = esp_wifi_connect(); if (result != ESP_OK) { ESP_LOGE(TAG, "WiFi connection failed with error code %x [%s].", result, esp_err_to_name(result)); } ESP_LOGI(TAG, "Disconnected, retrying..."); } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) { ip_event_got_ip_t* event = reinterpret_cast<ip_event_got_ip_t*>(event_data); ESP_LOGI(TAG, "Connected. IP: " IPSTR, IP2STR(&event->ip_info.ip)); if (wifi_event_group != nullptr) { xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT); } } } tl::expected<void, esp_err_t> connect(std::string_view ssid, std::string_view password, timing::duration_t timeout) noexcept { esp_err_t result = ESP_OK; wifi_init_config_t wifi_init_config = WIFI_INIT_CONFIG_DEFAULT(); if (result = nvs_flash_init(); result != ESP_OK) { ESP_LOGE(TAG, "NVS flash initialization failed."); tl::expected<void, esp_err_t>(tl::unexpect, result); } if (result = esp_event_loop_create_default(); result != ESP_OK) { ESP_LOGE(TAG, "Default event loop creation failed."); goto cleanup_nvs; } if (wifi_event_group = xEventGroupCreate(); wifi_event_group == nullptr) { ESP_LOGE(TAG, "Could not create event group."); result = ESP_FAIL; goto cleanup_event_loop; } esp_netif_init(); esp_netif_create_default_wifi_sta(); if (result = esp_wifi_init(&wifi_init_config); result != ESP_OK) { ESP_LOGE(TAG, "Wi-Fi initialization failed with error code %x [%s].", result, esp_err_to_name(result)); return tl::expected<void, esp_err_t>(tl::unexpect, result); } if (result = esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_START, &event_handler, nullptr); result != ESP_OK) { ESP_LOGE(TAG, "Event initialization failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_wifi_init; } if (result = esp_event_handler_register(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &event_handler, nullptr); result != ESP_OK) { ESP_LOGE(TAG, "Event initialization failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } if (result = esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, nullptr); result != ESP_OK) { ESP_LOGE(TAG, "Event initialization failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } if (result = esp_wifi_set_mode(WIFI_MODE_STA); result != ESP_OK) { ESP_LOGE(TAG, "Setting WiFi mode failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } { wifi_config_t config{}; std::strcpy(reinterpret_cast<char*>(config.sta.ssid), ssid.data()); std::strcpy(reinterpret_cast<char*>(config.sta.password), password.data()); if (result = esp_wifi_set_config(static_cast<wifi_interface_t>(ESP_IF_WIFI_STA), &config); result != ESP_OK) { ESP_LOGE(TAG, "Setting WiFi configuration failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } } if (result = esp_wifi_start(); result != ESP_OK) { ESP_LOGE(TAG, "WiFi start failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_event_handler_register; } { EventBits_t bits = xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, pdTRUE, pdFALSE, static_cast<TickType_t>(timeout)); if (bits & WIFI_CONNECTED_BIT) { ESP_LOGI(TAG, "WiFi connected."); } else { result = ESP_ERR_TIMEOUT; ESP_LOGE(TAG, "WiFi connection failed with error code %x [%s].", result, esp_err_to_name(result)); goto cleanup_wifi_start; } } return tl::expected<void, esp_err_t>(); cleanup_wifi_start: esp_wifi_stop(); cleanup_event_handler_register: esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_START, &event_handler); cleanup_wifi_init: esp_wifi_deinit(); cleanup_event_loop: esp_event_loop_delete_default(); cleanup_nvs: nvs_flash_deinit(); return tl::expected<void, esp_err_t>(tl::unexpect, result); } tl::expected<void, esp_err_t> disconnect() noexcept { esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_DISCONNECTED, &event_handler); esp_event_handler_unregister(WIFI_EVENT, WIFI_EVENT_STA_START, &event_handler); esp_wifi_disconnect(); esp_wifi_stop(); esp_wifi_deinit(); vEventGroupDelete(wifi_event_group); esp_event_loop_delete_default(); nvs_flash_deinit(); return tl::expected<void, esp_err_t>(); } }
[ "borchy97@gmail.com" ]
borchy97@gmail.com
8f4ab6ac9f8073f243cae1c7ebbdac292fcd98c2
e1cd579c8dcd952cc338ce3684397eddb0920760
/archive/1/wloska_czekolada.cpp
2a59db69f6866c10d1d8c6c261ea1049ce081fea
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Aleshkev/algoritmika
0b5de063870cb8a87654613241a204b534037079
fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189
refs/heads/master
2021-06-05T10:46:59.313945
2020-02-02T12:39:47
2020-02-02T12:39:47
148,994,588
3
0
null
null
null
null
UTF-8
C++
false
false
829
cpp
#include <iostream> #include <algorithm> using namespace std; typedef long long int I; int main() { I n; cin >> n; I *t = new I[n]; for(I i = 0; i < n; ++i) { cin >> t[i]; --t[i]; } I max_a = *max_element(t, t + n); I *u = new I[max_a]; fill(u, u + max_a, -1); for(I i = 0; i < n; ++i) { u[t[i]] = i; } for(I i = 0; i < n; ++i) { cout << t[i] << " "; } cout << endl; for(I i = 0; i < max_a; ++i) { if(u[i] != -1) { cout << i << ": " << u[i] << endl; } } I c = 0; I b = 0, e = 0; while(b < n) { do { ++b; e = max(e, u[t[b]]); } while(b < e) cout << "found " << b << ":" << e << endl; ++c; } cout << c << endl; return 0; }
[ "j.aleszkiewicz@gmail.com" ]
j.aleszkiewicz@gmail.com
428be9e5a38ec5cd79b1901360613480d9f6f32e
0fa5fc9365c65eb5ac7c48c16e9feee199d1ff0a
/arduino/cocktailmaschine/cocktailmaschine.ino
2190ead73f234d8d8ce7318693f6552031c9abc4
[]
no_license
tobiwe/cocktailmachine
51f6d9d484d2844da603169304be42a939a2a5d4
0881025acffd6275b4ad3eea1c8ebd5556e54f67
refs/heads/main
2023-07-13T23:29:47.614353
2021-08-26T12:22:11
2021-08-26T12:22:11
332,493,284
1
0
null
null
null
null
UTF-8
C++
false
false
11,696
ino
#include "Waage.hpp" #include "pumpe.hpp" #include "Luftpumpe.hpp" #include "Led.hpp" #include "Ventil.hpp" #include "Drucksensor.hpp" #include "config.hpp" int peristalicLed[6] = { 5, 4, 3, 2, 1, 0}; int airLed[4] = { 13, 12, 15, 14}; int bottleLed[6] = {6, 7, 8, 9, 10, 11}; int glasLed = 16; char newCommand[20]; char command[20]; int program = 0; int old = 0; char oldCommand[20]; int zaehler = 0; bool newSerialEvent = false; bool switchtoOldProgram = false; Waage waage; Led ledstripe; Ventil ventile[4] = { Ventil(VENTIL1), Ventil(VENTIL2), Ventil(VENTIL3), Ventil(VENTIL4) }; Drucksensor sensoren[4] = { Drucksensor(DRUCK1), Drucksensor(DRUCK2), Drucksensor(DRUCK3), Drucksensor(DRUCK4), }; Pumpe p1(PERISTALIC, MOTOR1_In1, MOTOR1_In2, MOTOR1_En, peristalicLed[0], bottleLed[0], false); Pumpe p2(PERISTALIC, MOTOR2_In1, MOTOR2_In2, MOTOR2_En, peristalicLed[1], bottleLed[1], false); Pumpe p3(PERISTALIC, MOTOR3_In1, MOTOR3_In2, MOTOR3_En, peristalicLed[2], bottleLed[2], true); Pumpe p4(PERISTALIC, MOTOR4_In1, MOTOR4_In2, MOTOR4_En, peristalicLed[3], bottleLed[3], true); Pumpe p5(PERISTALIC, MOTOR5_In1, MOTOR5_In2, MOTOR5_En, peristalicLed[4], bottleLed[4], false); Pumpe p6(PERISTALIC, MOTOR6_In1, MOTOR6_In2, MOTOR6_En, peristalicLed[5], bottleLed[5], true); Luftpumpe a1(AIR, MOTOR7_In1, MOTOR7_In2, MOTOR7_En, airLed[0], airLed[0], ventile[0], &(sensoren[0]), false); Luftpumpe a2(AIR, MOTOR8_In1, MOTOR8_In2, MOTOR8_En, airLed[1], airLed[1], ventile[1], &(sensoren[1]), false); Luftpumpe a3(AIR, MOTOR9_In1, MOTOR9_In2, MOTOR9_En, airLed[2], airLed[2], ventile[2], &(sensoren[2]), false); Luftpumpe a4(AIR, MOTOR10_In1, MOTOR10_In2, MOTOR10_En, airLed[3], airLed[3], ventile[3], &(sensoren[3]), false); Pumpe *pumpen[10] = {&p1, &p2, &p3, &p4, &p5, &p6, &a1, &a2, &a3, &a4}; void setup() { Serial.begin(BAUDRATE); waage.setup(); for (Pumpe *p : pumpen) { p->setup(); if (p->getType() == PERISTALIC) { p->setSpeed(255); } } a1.setSpeed(150); a2.setSpeed(150); a3.setSpeed(150); a4.setSpeed(150); for (Ventil v : ventile) { v.setup(); v.open(); } delay(1000); for (Ventil v : ventile) { v.setup(); v.close(); } for (int i = 0; i < 4; i++) { sensoren[i].update(); sensoren[i].setDefaultPressure(sensoren[i].getValue()); } ledstripe.setup(); } void loop() { for (int i = 0; i < 4; i++) { sensoren[i].update(); } waage.update(); checkForSerialEvent(); if (newSerialEvent) { old = program; memcpy(oldCommand, command, sizeof(command)); memcpy(command, newCommand, sizeof(newCommand)); program = getValue(command, ' ', 0); newSerialEvent = false; /** Debug Serial.print("Old: "); Serial.print(old); Serial.print(", "); Serial.print("Buffer"); Serial.println(oldCommand); Serial.print("New: "); Serial.print(program); Serial.print(", "); Serial.print("Buffer"); Serial.println(command);*/ } float amount, mass; int motor, motorSpeed, ventil, state, pumpe, ledShow, wait, r, g, b, sub, cmd, pressure; switch (program) { case 1: cmd = getValue(command, ' ', 1); if (cmd == 1) { ledstripe.setLed(getValue(command, ' ', 2), strip.Color(getValue(command, ' ', 3), getValue(command, ' ', 4), getValue(command, ' ', 5))); } else if (cmd == 2) { ledstripe.fillLed(strip.Color(getValue(command, ' ', 2), getValue(command, ' ', 3), getValue(command, ' ', 4))); } program = 0; break; case 2: motor = getValue(command, ' ', 1); motorSpeed = getValue(command, ' ', 2); if (motorSpeed == 0) { pumpen[motor]->stop(); } else if (motorSpeed > 0) { pumpen[motor]->setSpeed(motorSpeed); pumpen[motor]->forward(); } else if (motorSpeed < 0) { pumpen[motor]->setSpeed(-1 * motorSpeed); pumpen[motor]->backward(); } program = 0; break; case 3: ventil = getValue(command, ' ', 1); state = getValue(command, ' ', 2); if (state == 1)ventile[ventil].open(); else if (state == 0) ventile[ventil].close(); program = 0; break; case 4: pumpe = getValue(command, ' ', 1); amount = getValue(command, ' ', 2); fillGlas(pumpen[pumpe - 1], amount); program = 0; break; case 5: sub = getValue(command, ' ', 1); if (sub == 1) { Serial.write(0x02); Serial.print(waage.getValue()); Serial.write(0x03); } else if (sub == 2) { waage.tare(); } else if (sub == 3) { mass = getValue(command, ' ', 2); waage.calibrate(mass); } else if (sub == 4) { waage.calibrate(); } switchtoOldProgram = true; break; case 6: ledShow = getValue(command, ' ', 1); if (ledShow == 1) { wait = getValue(command, ' ', 2); ledstripe.fasterRainbow(wait); } else if (ledShow == 2) { wait = getValue(command, ' ', 2); ledstripe.fasterTheaterChaseRainbow(wait); } else if (ledShow == 3) { wait = getValue(command, ' ', 2); r = getValue(command, ' ', 3); g = getValue(command, ' ', 4); b = getValue(command, ' ', 5); ledstripe.theaterChase(strip.Color(r, g, b), wait); } else if (ledShow == 4) { wait = getValue(command, ' ', 2); r = getValue(command, ' ', 3); g = getValue(command, ' ', 4); b = getValue(command, ' ', 5); ledstripe.colorWipe(strip.Color(r, g, b), wait); } else if (ledShow == 5) { wait = getValue(command, ' ', 2); r = getValue(command, ' ', 3); g = getValue(command, ' ', 4); b = getValue(command, ' ', 5); ledstripe.fasterBlinkOnOff(strip.Color(r, g, b), wait); } break; case 7: pressure = getValue(command, ' ', 1); Serial.write(0x02); Serial.print(sensoren[pressure].getValue()); Serial.write(0x03); program = 0; break; default: //do nothing break; } if (program != 6) { delay(50); } else { delay(1); } if (switchtoOldProgram) { //Toggle Program int tmp = old; old = program; program = tmp; //Toggle Commands char tmpCommand[20];; memcpy(tmpCommand, command, sizeof(command)); memcpy(command, oldCommand, sizeof(oldCommand)); memcpy(oldCommand, tmpCommand, sizeof(tmpCommand)); switchtoOldProgram = false; } } float getValue(String data, char separator, int index) { int found = 0; int strIndex[] = { 0, -1 }; int maxIndex = data.length() - 1; for (int i = 0; i <= maxIndex && found <= index; i++) { if (data.charAt(i) == separator || i == maxIndex) { found++; strIndex[0] = strIndex[1] + 1; strIndex[1] = (i == maxIndex) ? i + 1 : i; } } String sub = data.substring(strIndex[0], strIndex[1]); return found > index ? sub.toFloat() : 0; } void fillGlas(Pumpe *pumpe, float amount) { delay(100); long startTime = millis(); long lastTime = startTime; long lastSpeedCheck = startTime; float loadCell = waage.getValue(); float oldSpeedWeight = loadCell; float oldValue = loadCell; float oldPressure = 0; bool finished = false; bool refill = false; float startValue = loadCell; float goalValue = startValue + amount; bool interrupt = false; Drucksensor *sensor = nullptr; if (pumpe->getType() == AIR) { sensor = ((Luftpumpe*)pumpe)->sensor; oldPressure = sensor->getValue(); } int interval = 6000; int maxInterval = 10000; while (loadCell < goalValue) { ledstripe.fillLed(strip.Color(0, 0, 0)); waage.update(); if (pumpe->getType() == AIR) { sensor->update(); }; loadCell = waage.getValue(); pumpe->forward(); ledstripe.setLed(pumpe->bottleLed, strip.Color(0, 0, 255)); ledstripe.setLed(glasLed, strip.Color(0, 0, 255)); long actualTime = millis(); bool updateInterval = false; if (actualTime - lastTime >= interval) { if (pumpe->getType() == AIR) { if (oldPressure + 0.2 > sensor->getValue() && oldValue + 1 > loadCell) { refill = true; } } else if (oldValue + 1 > loadCell) { refill = true; } lastTime = actualTime; interval = 1000; oldValue = loadCell; oldPressure = sensor->getValue(); } // Flow per time check for speed optimization if (pumpe->getType() == AIR) { if (actualTime - lastSpeedCheck >= 1000 && loadCell > oldValue) { int actualSpeed = pumpe->getSpeed(); int change = loadCell - oldSpeedWeight; //Check for 10g if (change < 15 && actualSpeed < 200) { pumpe->setSpeed(actualSpeed += 5); } else if (change > 5 && actualSpeed > 100) { pumpe->setSpeed(actualSpeed -= 5); } lastSpeedCheck = actualTime; oldSpeedWeight = loadCell; } } if (refill) { pumpe->stop(false); ledstripe.setLed(pumpe->bottleLed, strip.Color(0, 0, 0)); ledstripe.setLed(glasLed, strip.Color(0, 0, 0)); Serial.write(0x02); Serial.print("refill"); Serial.write(0x03); interval = 5000; while (refill) { //Blink here ledstripe.setLed(pumpe->bottleLed, strip.Color(255, 0, 0)); for (int i : peristalicLed) { ledstripe.setLed(i, strip.Color(255, 0, 0)); } delay(250); ledstripe.setLed(pumpe->bottleLed, strip.Color(0, 0, 0)); for (int i : peristalicLed) { ledstripe.setLed(i, strip.Color(0, 0, 0)); } delay(250); if (Serial.available()) { String test = Serial.readString(); if (test == "done\n") { refill = false; } } } startTime = millis(); lastTime = startTime; } if (loadCell >= goalValue) { finished = true; } if (Serial.available()) { String test = Serial.readString(); if (test == "interrupt\n") { finished = true; break; } } } if (finished) { pumpe->stop(false); if (pumpe->getType() == AIR) { Luftpumpe* air = (Luftpumpe*)pumpe; air->ventil.open(); } ledstripe.fillLed(strip.Color(255, 255, 255)); //Wait till weight stays the same bool valueChange = true; float first, second; while (valueChange) { first = waage.getValue(); long startTime = millis(); while (millis() - startTime < 2000) { waage.update(); delay(10); } second = waage.getValue(); if ((second - first) < 0.1) { valueChange = false; if (pumpe->getType() == AIR) { Luftpumpe* air = (Luftpumpe*)pumpe; air->ventil.close(); } } } Serial.write(0x02); Serial.print("finish"); Serial.write(0x03); finished = false; delay(100); } } void checkForSerialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); if (inChar == 0x02) { zaehler = 0; } else if (inChar == 0x03) { newSerialEvent = true; newCommand[zaehler] = '\0'; break; } else { newCommand[zaehler] = inChar; zaehler++; } } }
[ "pebble@towan.de" ]
pebble@towan.de
35b1f8bc6243426c5f5110180ff44e7d17ac7b2a
56b847482dd3cd1b55bc19e1ff3ec1dfcbd6a0bd
/Adafruit_SGP30.cpp
0068231945f927a5a76d156ed8f0624a72f4644c
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
winkj/Adafruit_SGP30
431645284ca12f175940013170e4510ef5239a71
729ddf4e3c43e22643b1ae9dabb97a8affc0a297
refs/heads/master
2021-05-10T14:30:42.551946
2018-01-17T18:26:17
2018-01-17T18:26:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,321
cpp
/*! * @file Adafruit_SGP30.cpp * * @mainpage Adafruit SGP30 gas sensor driver * * @section intro_sec Introduction * * This is the documentation for Adafruit's SGP30 driver for the * Arduino platform. It is designed specifically to work with the * Adafruit SGP30 breakout: http://www.adafruit.com/products/3709 * * These sensors use I2C to communicate, 2 pins (SCL+SDA) are required * to interface with the breakout. * * Adafruit invests time and resources providing this open source code, * please support Adafruit and open-source hardware by purchasing * products from Adafruit! * * * @section author Author * Written by Ladyada for Adafruit Industries. * * @section license License * BSD license, all text here must be included in any redistribution. * */ #if ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "Adafruit_SGP30.h" //#define I2C_DEBUG /**************************************************************************/ /*! @brief Instantiates a new SGP30 class */ /**************************************************************************/ Adafruit_SGP30::Adafruit_SGP30() { } /**************************************************************************/ /*! @brief Setups the hardware and detects a valid SGP30. Initializes I2C then reads the serialnumber and checks that we are talking to an SGP30 @param theWire Optional pointer to I2C interface, otherwise use Wire @returns True if SGP30 found on I2C, False if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::begin(TwoWire *theWire) { _i2caddr = SGP30_I2CADDR_DEFAULT; if (theWire == NULL) { _i2c = &Wire; } else { _i2c = theWire; } _i2c->begin(); uint8_t command[2]; command[0] = 0x36; command[1] = 0x82; if (! readWordFromCommand(command, 2, 10, serialnumber, 3)) return false; uint16_t featureset; command[0] = 0x20; command[1] = 0x2F; if (! readWordFromCommand(command, 2, 10, &featureset, 1)) return false; //Serial.print("Featureset 0x"); Serial.println(featureset, HEX); if (featureset != SGP30_FEATURESET) return false; if (! IAQinit()) return false; return true; } /**************************************************************************/ /*! @brief Commands the sensor to begin the IAQ algorithm. Must be called after startup. @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::IAQinit(void) { uint8_t command[2]; command[0] = 0x20; command[1] = 0x03; return readWordFromCommand(command, 2, 10); } /**************************************************************************/ /*! @brief Commands the sensor to take a single eCO2/VOC measurement. Places results in {@link TVOC} and {@link eCO2} @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::IAQmeasure(void) { uint8_t command[2]; command[0] = 0x20; command[1] = 0x08; uint16_t reply[2]; if (! readWordFromCommand(command, 2, 10, reply, 2)) return false; TVOC = reply[1]; eCO2 = reply[0]; return true; } /**************************************************************************/ /*! @brief Request baseline calibration values for both CO2 and TVOC IAQ calculations. Places results in parameter memory locaitons. @param eco2_base A pointer to a uint16_t which we will save the calibration value to @param tvoc_base A pointer to a uint16_t which we will save the calibration value to @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::getIAQBaseline(uint16_t *eco2_base, uint16_t *tvoc_base) { uint8_t command[2]; command[0] = 0x20; command[1] = 0x15; uint16_t reply[2]; if (! readWordFromCommand(command, 2, 10, reply, 2)) return false; *eco2_base = reply[0]; *tvoc_base = reply[1]; return true; } /**************************************************************************/ /*! @brief Assign baseline calibration values for both CO2 and TVOC IAQ calculations. @param eco2_base A uint16_t which we will save the calibration value from @param tvoc_base A uint16_t which we will save the calibration value from @returns True if command completed successfully, false if something went wrong! */ /**************************************************************************/ boolean Adafruit_SGP30::setIAQBaseline(uint16_t eco2_base, uint16_t tvoc_base) { uint8_t command[8]; command[0] = 0x20; command[1] = 0x1e; command[2] = tvoc_base >> 8; command[3] = tvoc_base & 0xFF; command[4] = generateCRC(command+2, 2); command[5] = eco2_base >> 8; command[6] = eco2_base & 0xFF; command[7] = generateCRC(command+5, 2); uint16_t reply[2]; if (! readWordFromCommand(command, 8, 10, reply, 0)) return false; return true; } /**************************************************************************/ /*! @brief I2C low level interfacing */ /**************************************************************************/ boolean Adafruit_SGP30::readWordFromCommand(uint8_t command[], uint8_t commandLength, uint16_t delayms, uint16_t *readdata, uint8_t readlen) { uint8_t data; _i2c->beginTransmission(_i2caddr); #ifdef I2C_DEBUG Serial.print("\t\t-> "); #endif for (uint8_t i=0; i<commandLength; i++) { _i2c->write(command[i]); #ifdef I2C_DEBUG Serial.print("0x"); Serial.print(command[i], HEX); Serial.print(", "); #endif } #ifdef I2C_DEBUG Serial.println(); #endif _i2c->endTransmission(); delay(delayms); if (readlen == 0) return true; uint8_t replylen = readlen * (SGP30_WORD_LEN +1); if (_i2c->requestFrom(_i2caddr, replylen) != replylen) return false; uint8_t replybuffer[replylen]; #ifdef I2C_DEBUG Serial.print("\t\t<- "); #endif for (uint8_t i=0; i<replylen; i++) { replybuffer[i] = _i2c->read(); #ifdef I2C_DEBUG Serial.print("0x"); Serial.print(replybuffer[i], HEX); Serial.print(", "); #endif } #ifdef I2C_DEBUG Serial.println(); #endif for (uint8_t i=0; i<readlen; i++) { uint8_t crc = generateCRC(replybuffer+i*3, 2); #ifdef I2C_DEBUG Serial.print("\t\tCRC calced: 0x"); Serial.print(crc, HEX); Serial.print(" vs. 0x"); Serial.println(replybuffer[i * 3 + 2], HEX); #endif if (crc != replybuffer[i * 3 + 2]) return false; // success! store it readdata[i] = replybuffer[i*3]; readdata[i] <<= 8; readdata[i] |= replybuffer[i*3 + 1]; #ifdef I2C_DEBUG Serial.print("\t\tRead: 0x"); Serial.println(readdata[i], HEX); #endif } return true; } uint8_t Adafruit_SGP30::generateCRC(uint8_t *data, uint8_t datalen) { // calculates 8-Bit checksum with given polynomial uint8_t crc = SGP30_CRC8_INIT; for (uint8_t i=0; i<datalen; i++) { crc ^= data[i]; for (uint8_t b=0; b<8; b++) { if (crc & 0x80) crc = (crc << 1) ^ SGP30_CRC8_POLYNOMIAL; else crc <<= 1; } } return crc; }
[ "limor@ladyada.net" ]
limor@ladyada.net
6abef3013c1b31aa18b5593f15a3738819df5168
17af777718e66d1735632c171e5286ff04c42665
/BOJ1236.cpp
5efecf26d8195006c4ff9ea3be089a08b2a50654
[]
no_license
girinssh/BOJ
4ddff350e309d85a153232062426f660e1144498
0964033e66081ecc81da6db421812ffb7f2eeacd
refs/heads/master
2023-07-14T19:08:52.364347
2021-08-17T09:11:24
2021-08-17T09:11:24
284,575,573
0
0
null
null
null
null
UTF-8
C++
false
false
914
cpp
#include <iostream> using namespace std; int main(void) { cin.tie(NULL); cin.sync_with_stdio(false); char arr[50][50] = { 0 }; int a, b; int n = 0, m = 0; cin >> a >> b; for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { cin >> arr[i][j]; } } for (int i = 0; i < a; i++) { for (int j = 0; j < b; j++) { if (arr[i][j] == 'X') { n++; break; } } } for (int i = 0; i < b; i++) { for (int j = 0; j < a; j++) { if (arr[j][i] == 'X') { m++; break; } } } cout << (a - n > b - m ? a - n : b - m); return 0; } /* XXXXXXXXXXXXXXXXXXXX .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... .................... */
[ "tngus5851@naver.com" ]
tngus5851@naver.com
9615bbd1404b28e543a3d82d69d5efdda71028c9
06e3a51780fe6906a8713b7e274a35c0d89d2506
/qtmdsrv/ui/ringbufferform.cpp
d1747adf391cf8b30fffc927844d205b265e9c8a
[]
no_license
ssh352/qtctp-1
d91fc8d432cd93019b23e7e29f40b41b1493aceb
248d09e629b09cbe1adbf7cd818679721bf156d0
refs/heads/master
2020-04-01T16:55:31.012740
2015-10-27T15:56:02
2015-10-27T15:56:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,065
cpp
#include "ringbufferform.h" #include "ui_ringbufferform.h" #include "mdsm.h" #include "ApiStruct.h" #include "ringbuffer.h" #include "servicemgr.h" #include "ctpmgr.h" #include "datapump.h" #include "historyform.h" RingBufferForm::RingBufferForm(QWidget* parent) : QWidget(parent) , ui(new Ui::RingBufferForm) { ui->setupUi(this); //设置列= instruments_col_ = { "TradingDay", "UpdateTime", "UpdateMillisec", "LastPrice", "Volume", "OpenInterest", "BidPrice1", "BidVolume1", "AskPrice1", "AskVolume1" }; this->ui->tableWidget->setColumnCount(instruments_col_.length()); for (int i = 0; i < instruments_col_.length(); i++) { ui->tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(instruments_col_.at(i))); } } RingBufferForm::~RingBufferForm() { delete ui; } void RingBufferForm::init(QString id) { id_ = id; this->setWindowTitle(QString("ringbuffer-")+id); scanTicks(); } void RingBufferForm::scanTicks() { DataPump* datapump = g_sm->dataPump(); if(!datapump){ return; } ui->tableWidget->clearContents(); ui->tableWidget->setRowCount(0); RingBuffer* rb = datapump->getRingBuffer(id_); int head = rb->head(); if (head < 0) { return; } for (int i = 0; i < rb->count() / 2; i++) { void* p = rb->get(head); if (p == nullptr) { return; } onGotTick(p); head -= 1; if (head == -1) { head += rb->count(); } } } void RingBufferForm::onGotTick(void* tick) { auto mdf = (DepthMarketDataField*)tick; QVariantMap mdItem; mdItem.insert("TradingDay", mdf->TradingDay); mdItem.insert("UpdateTime", mdf->UpdateTime); mdItem.insert("UpdateMillisec", mdf->UpdateMillisec); mdItem.insert("LastPrice", mdf->LastPrice); mdItem.insert("Volume", mdf->Volume); mdItem.insert("OpenInterest", mdf->OpenInterest); mdItem.insert("BidPrice1", mdf->BidPrice1); mdItem.insert("BidVolume1", mdf->BidVolume1); mdItem.insert("AskPrice1", mdf->AskPrice1); mdItem.insert("AskVolume1", mdf->AskVolume1); //根据id找到对应的行,然后用列的text来在map里面取值设置到item里面= int row = ui->tableWidget->rowCount(); ui->tableWidget->insertRow(row); for (int i = 0; i < instruments_col_.count(); i++) { QVariant raw_val = mdItem.value(instruments_col_.at(i)); QString str_val = raw_val.toString(); if (raw_val.type() == QMetaType::Double || raw_val.type() == QMetaType::Float) { str_val = QString().sprintf("%6.1f", raw_val.toDouble()); } QTableWidgetItem* item = new QTableWidgetItem(str_val); ui->tableWidget->setItem(row, i, item); } } void RingBufferForm::on_historyButton_clicked() { HistoryForm* form = new HistoryForm(); form->setWindowFlags(Qt::Window); form->init(id_,g_sm->dataPump()->getTodayDB(),false); form->show(); } void RingBufferForm::on_refreshButton_clicked() { scanTicks(); }
[ "sunwangme@gmail.com" ]
sunwangme@gmail.com
4490353c42541fc5da6555ac1f7b6a1d374656e2
7f7ebd4118d60a08e4988f95a846d6f1c5fd8eda
/wxWidgets-2.9.1/include/wx/palmos/stattext.h
00ff0e28866adbc5da2d973d774bf75a2c65208f
[]
no_license
esrrhs/fuck-music-player
58656fc49d5d3ea6c34459630c42072bceac9570
97f5c541a8295644837ad864f4f47419fce91e5d
refs/heads/master
2021-05-16T02:34:59.827709
2021-05-10T09:48:22
2021-05-10T09:48:22
39,882,495
2
0
null
null
null
null
UTF-8
C++
false
false
1,730
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/palmos/stattext.h // Purpose: wxStaticText class // Author: William Osborne - minimal working wxPalmOS port // Modified by: Wlodzimierz ABX Skiba - native wxStaticText implementation // Created: 10/13/04 // RCS-ID: $Id$ // Copyright: (c) William Osborne, Wlodzimierz Skiba // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_STATTEXT_H_ #define _WX_STATTEXT_H_ class WXDLLIMPEXP_CORE wxStaticText : public wxStaticTextBase { public: wxStaticText() { } wxStaticText(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxStaticTextNameStr) { Create(parent, id, label, pos, size, style, name); } bool Create(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxString& name = wxStaticTextNameStr); // override some methods to resize the window properly virtual bool SetFont( const wxFont &font ); protected: // implement/override some base class virtuals virtual wxBorder GetDefaultBorder() const; virtual wxSize DoGetBestSize() const; DECLARE_DYNAMIC_CLASS_NO_COPY(wxStaticText) }; #endif // _WX_STATTEXT_H_
[ "esrrhs@esrrhs-PC" ]
esrrhs@esrrhs-PC
80039d48587c48ed44914c9a44b423385c59d8c2
1a29e2f587d88dac68dcdddac38ce9d7d450d058
/cs4499/midtern/bunny_generator.hpp
d1837d6f47dbd84f11e084e884a9139494e76e4a
[]
no_license
TheNumberOne/school_code
a41395e64dcc9089fb251fb2da0fa721161b5897
42d4aa7dc4bb1f23331382dc5875f261dc9e31c7
refs/heads/master
2020-08-08T11:52:50.008711
2019-10-09T05:07:47
2019-10-09T05:07:47
213,825,898
0
0
null
null
null
null
UTF-8
C++
false
false
690
hpp
#pragma once #include "bunny.hpp" #include <utility> #include <memory> /** * Randomly generates rabbits using the passed random number generator. */ class random_bunny_generator { public: explicit random_bunny_generator(std::shared_ptr<std::default_random_engine> rng) : _rng(std::move(rng)) { } /** * Creates a randomly generated bunny. */ bunny operator()(); /** * Creates a randomly generated bunny using the specified colors. Mostly used for when two rabbits have a child. */ bunny operator()(const std::vector<std::string> &colors); private: /** * Rng used */ std::shared_ptr<std::default_random_engine> _rng; };
[ "robepea2@isu.edu" ]
robepea2@isu.edu
c8fecf042797381cee307bb72ecefb44336b5726
05bd8b96db62137f8487e602a7b8a88f2a2c0fe4
/算法初步/二分/1085 Perfect Sequence (25分).cpp
5770e674459516978f3ddfd4c50050443cbf02e0
[]
no_license
PeiLeizzz/Algorithm-PAT-A
a8b71abeb26c4127f6ee6de166b3bfa5d0b3fb61
d1d58adb0b90e7a0fdd480e8e6d11a5de4272282
refs/heads/master
2022-12-23T14:47:50.912282
2020-08-28T12:31:57
2020-08-28T12:31:57
291,039,897
1
0
null
null
null
null
GB18030
C++
false
false
940
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; vector<ll> numble; int main() { int n; ll p; scanf("%d %lld", &n, &p); for (int i = 0; i < n; i++) { ll a; scanf("%lld", &a); numble.push_back(a); } sort(numble.begin(), numble.end()); int len = 1; for (int i = 0; i < n && i + len < n; i++) { int left = i + 1; int right = n; // 查找区间 [left, right] // right 取 n 的原因:可能整个序列都满足条件,那么left 最多可以到 n // 即 len = n 符合条件 // 如果取 right = n - 1 需要单独判断 numble[n-1] > cmpNum ll cmpNum = numble[i] * p; // 寻找第一个 mid 使 numble[mid] > cmpNum while (left < right) { int mid = (left + right) / 2; if (numble[mid] > cmpNum) { // 区间:[left, mid] right = mid; } else { // 区间:[mid+1, right] left = mid + 1; } } len = max(len, left - i); } printf("%d", len); return 0; }
[ "714838284@qq.com" ]
714838284@qq.com
650419388cf51f37f453b09d92170a02d5325a07
9fad4848e43f4487730185e4f50e05a044f865ab
/src/ash/wm/window_state.h
2c0bb5ca61be87b01d3ceb2e16d44b920375a22b
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
14,982
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_WM_WINDOW_STATE_H_ #define ASH_WM_WINDOW_STATE_H_ #include <memory> #include "ash/ash_export.h" #include "ash/wm/drag_details.h" #include "ash/wm/wm_types.h" #include "base/gtest_prod_util.h" #include "base/macros.h" #include "base/observer_list.h" #include "ui/aura/window_observer.h" #include "ui/base/ui_base_types.h" namespace aura { class Window; } namespace gfx { class Rect; } namespace ash { class WorkspaceLayoutManager; class LockWindowState; class MaximizeModeWindowState; namespace wm { class WindowStateDelegate; class WindowStateObserver; class WMEvent; // WindowState manages and defines ash specific window state and // behavior. Ash specific per-window state (such as ones that controls // window manager behavior) and ash specific window behavior (such as // maximize, minimize, snap sizing etc) should be added here instead // of defining separate functions (like |MaximizeWindow(aura::Window* // window)|) or using aura Window property. // The WindowState gets created when first accessed by // |wm::GetWindowState|, and deleted when the window is deleted. // Prefer using this class instead of passing aura::Window* around in // ash code as this is often what you need to interact with, and // accessing the window using |window()| is cheap. class ASH_EXPORT WindowState : public aura::WindowObserver { public: // A subclass of State class represents one of the window's states // that corresponds to WindowStateType in Ash environment, e.g. // maximized, minimized or side snapped, as subclass. // Each subclass defines its own behavior and transition for each WMEvent. class State { public: State() {} virtual ~State() {} // Update WindowState based on |event|. virtual void OnWMEvent(WindowState* window_state, const WMEvent* event) = 0; virtual WindowStateType GetType() const = 0; // Gets called when the state object became active and the managed window // needs to be adjusted to the State's requirement. // The passed |previous_state| may be used to properly implement state // transitions such as bound animations from the previous state. // Note: This only gets called when the state object gets changed. virtual void AttachState(WindowState* window_state, State* previous_state) = 0; // Gets called before the state objects gets deactivated / detached from the // window, so that it can save the various states it is interested in. // Note: This only gets called when the state object gets changed. virtual void DetachState(WindowState* window_state) = 0; private: DISALLOW_COPY_AND_ASSIGN(State); }; // Call GetWindowState() to instantiate this class. ~WindowState() override; aura::Window* window() { return window_; } const aura::Window* window() const { return window_; } bool HasDelegate() const; void SetDelegate(std::unique_ptr<WindowStateDelegate> delegate); // Returns the window's current ash state type. // Refer to WindowStateType definition in wm_types.h as for why Ash // has its own state type. WindowStateType GetStateType() const; // Predicates to check window state. bool IsMinimized() const; bool IsMaximized() const; bool IsFullscreen() const; bool IsMaximizedOrFullscreen() const; bool IsSnapped() const; // True if the window's state type is WINDOW_STATE_TYPE_NORMAL or // WINDOW_STATE_TYPE_DEFAULT. bool IsNormalStateType() const; bool IsNormalOrSnapped() const; bool IsActive() const; bool IsDocked() const; // Returns true if the window's location can be controlled by the user. bool IsUserPositionable() const; // Checks if the window can change its state accordingly. bool CanMaximize() const; bool CanMinimize() const; bool CanResize() const; bool CanSnap() const; bool CanActivate() const; // Returns true if the window has restore bounds. bool HasRestoreBounds() const; // These methods use aura::WindowProperty to change the window's state // instead of using WMEvent directly. This is to use the same mechanism as // what views::Widget is using. void Maximize(); void Minimize(); void Unminimize(); void Activate(); void Deactivate(); // Set the window state to normal. // TODO(oshima): Change to use RESTORE event. void Restore(); // Caches, then disables always on top state and then stacks |window_| below // |window_on_top| if a |window_| is currently in always on top state. void DisableAlwaysOnTop(aura::Window* window_on_top); // Restores always on top state that a window might have cached. void RestoreAlwaysOnTop(); // Invoked when a WMevent occurs, which drives the internal // state machine. void OnWMEvent(const WMEvent* event); // TODO(oshima): Try hiding these methods and making them accessible only to // state impl. State changes should happen through events (as much // as possible). // Saves the current bounds to be used as a restore bounds. void SaveCurrentBoundsForRestore(); // Same as |GetRestoreBoundsInScreen| except that it returns the // bounds in the parent's coordinates. gfx::Rect GetRestoreBoundsInParent() const; // Returns the restore bounds property on the window in the virtual screen // coordinates. The bounds can be NULL if the bounds property does not // exist for the window. The window owns the bounds object. gfx::Rect GetRestoreBoundsInScreen() const; // Same as |SetRestoreBoundsInScreen| except that the bounds is in the // parent's coordinates. void SetRestoreBoundsInParent(const gfx::Rect& bounds_in_parent); // Sets the restore bounds property on the window in the virtual screen // coordinates. Deletes existing bounds value if exists. void SetRestoreBoundsInScreen(const gfx::Rect& bounds_in_screen); // Deletes and clears the restore bounds property on the window. void ClearRestoreBounds(); // Replace the State object of a window with a state handler which can // implement a new window manager type. The passed object will be owned // by this object and the returned object will be owned by the caller. std::unique_ptr<State> SetStateObject(std::unique_ptr<State> new_state); // True if the window should be unminimized to the restore bounds, as // opposed to the window's current bounds. |unminimized_to_restore_bounds_| is // reset to the default value after the window is unminimized. bool unminimize_to_restore_bounds() const { return unminimize_to_restore_bounds_; } void set_unminimize_to_restore_bounds(bool value) { unminimize_to_restore_bounds_ = value; } // Gets/sets whether the shelf should be hidden when this window is // fullscreen. bool hide_shelf_when_fullscreen() const { return hide_shelf_when_fullscreen_; } void set_hide_shelf_when_fullscreen(bool value) { hide_shelf_when_fullscreen_ = value; } // If the minimum visibility is true, ash will try to keep a // minimum amount of the window is always visible on the work area // when shown. // TODO(oshima): Consolidate this and window_position_managed // into single parameter to control the window placement. bool minimum_visibility() const { return minimum_visibility_; } void set_minimum_visibility(bool minimum_visibility) { minimum_visibility_ = minimum_visibility; } // Specifies if the window can be dragged by the user via the caption or not. bool can_be_dragged() const { return can_be_dragged_; } void set_can_be_dragged(bool can_be_dragged) { can_be_dragged_ = can_be_dragged; } // Gets/Sets the bounds of the window before it was moved by the auto window // management. As long as it was not auto-managed, it will return NULL. const gfx::Rect* pre_auto_manage_window_bounds() const { return pre_auto_manage_window_bounds_.get(); } void SetPreAutoManageWindowBounds(const gfx::Rect& bounds); // Layout related properties void AddObserver(WindowStateObserver* observer); void RemoveObserver(WindowStateObserver* observer); // Whether the window is being dragged. bool is_dragged() const { return !!drag_details_; } // Whether or not the window's position can be managed by the // auto management logic. bool window_position_managed() const { return window_position_managed_; } void set_window_position_managed(bool window_position_managed) { window_position_managed_ = window_position_managed; } // Whether or not the window's position or size was changed by a user. bool bounds_changed_by_user() const { return bounds_changed_by_user_; } void set_bounds_changed_by_user(bool bounds_changed_by_user); // True if this window is an attached panel. bool panel_attached() const { return panel_attached_; } void set_panel_attached(bool panel_attached) { panel_attached_ = panel_attached; } // True if the window is ignored by the shelf layout manager for // purposes of darkening the shelf. bool ignored_by_shelf() const { return ignored_by_shelf_; } void set_ignored_by_shelf(bool ignored_by_shelf) { ignored_by_shelf_ = ignored_by_shelf; } // True if the window should be offered a chance to consume special system // keys such as brightness, volume, etc. that are usually handled by the // shell. bool can_consume_system_keys() const { return can_consume_system_keys_; } void set_can_consume_system_keys(bool can_consume_system_keys) { can_consume_system_keys_ = can_consume_system_keys; } // True if this window has requested that the top-row keys (back, forward, // brightness, volume) should be treated as function keys. bool top_row_keys_are_function_keys() const { return top_row_keys_are_function_keys_; } void set_top_row_keys_are_function_keys(bool value) { top_row_keys_are_function_keys_ = value; } // True if the window is in "immersive full screen mode" which is slightly // different from the normal fullscreen mode by allowing the user to reveal // the top portion of the window through a touch / mouse gesture. It might // also allow the shelf to be shown in some situations. bool in_immersive_fullscreen() const { return in_immersive_fullscreen_; } void set_in_immersive_fullscreen(bool enable) { in_immersive_fullscreen_ = enable; } // Creates and takes ownership of a pointer to DragDetails when resizing is // active. This should be done before a resizer gets created. void CreateDragDetails(aura::Window* window, const gfx::Point& point_in_parent, int window_component, aura::client::WindowMoveSource source); // Deletes and clears a pointer to DragDetails. This should be done when the // resizer gets destroyed. void DeleteDragDetails(); // Sets the currently stored restore bounds and clears the restore bounds. void SetAndClearRestoreBounds(); // Returns a pointer to DragDetails during drag operations. const DragDetails* drag_details() const { return drag_details_.get(); } DragDetails* drag_details() { return drag_details_.get(); } // aura::WindowObserver overrides: void OnWindowPropertyChanged(aura::Window* window, const void* key, intptr_t old) override; private: friend class DefaultState; friend class ash::LockWindowState; friend class ash::MaximizeModeWindowState; friend ASH_EXPORT WindowState* GetWindowState(aura::Window*); FRIEND_TEST_ALL_PREFIXES(WindowAnimationsTest, CrossFadeToBounds); FRIEND_TEST_ALL_PREFIXES(WindowAnimationsTest, CrossFadeToBoundsFromTransform); explicit WindowState(aura::Window* window); WindowStateDelegate* delegate() { return delegate_.get(); } // Returns the window's current always_on_top state. bool GetAlwaysOnTop() const; // Returns the window's current show state. ui::WindowShowState GetShowState() const; // Sets the window's bounds in screen coordinates. void SetBoundsInScreen(const gfx::Rect& bounds_in_screen); // Adjusts the |bounds| so that they are flush with the edge of the // workspace if the window represented by |window_state| is side snapped. void AdjustSnappedBounds(gfx::Rect* bounds); // Updates the window show state according to the current window state type. // Note that this does not update the window bounds. void UpdateWindowShowStateFromStateType(); void NotifyPreStateTypeChange(WindowStateType old_window_state_type); void NotifyPostStateTypeChange(WindowStateType old_window_state_type); // Sets |bounds| as is and ensure the layer is aligned with pixel boundary. void SetBoundsDirect(const gfx::Rect& bounds); // Sets the window's |bounds| with constraint where the size of the // new bounds will not exceeds the size of the work area. void SetBoundsConstrained(const gfx::Rect& bounds); // Sets the wndow's |bounds| and transitions to the new bounds with // a scale animation. void SetBoundsDirectAnimated(const gfx::Rect& bounds); // Sets the window's |bounds| and transition to the new bounds with // a cross fade animation. void SetBoundsDirectCrossFade(const gfx::Rect& bounds); // The owner of this window settings. aura::Window* window_; std::unique_ptr<WindowStateDelegate> delegate_; bool window_position_managed_; bool bounds_changed_by_user_; bool panel_attached_; bool ignored_by_shelf_; bool can_consume_system_keys_; bool top_row_keys_are_function_keys_; std::unique_ptr<DragDetails> drag_details_; bool unminimize_to_restore_bounds_; bool in_immersive_fullscreen_; bool hide_shelf_when_fullscreen_; bool minimum_visibility_; bool can_be_dragged_; bool cached_always_on_top_; // A property to remember the window position which was set before the // auto window position manager changed the window bounds, so that it can get // restored when only this one window gets shown. std::unique_ptr<gfx::Rect> pre_auto_manage_window_bounds_; base::ObserverList<WindowStateObserver> observer_list_; // True to ignore a property change event to avoid reentrance in // UpdateWindowStateType() bool ignore_property_change_; std::unique_ptr<State> current_state_; DISALLOW_COPY_AND_ASSIGN(WindowState); }; // Returns the WindowState for active window. Returns |NULL| // if there is no active window. ASH_EXPORT WindowState* GetActiveWindowState(); // Returns the WindowState for |window|. Creates WindowState // if it didn't exist. The settings object is owned by |window|. ASH_EXPORT WindowState* GetWindowState(aura::Window* window); // const version of GetWindowState. ASH_EXPORT const WindowState* GetWindowState(const aura::Window* window); } // namespace wm } // namespace ash #endif // ASH_WM_WINDOW_STATE_H_
[ "dummas@163.com" ]
dummas@163.com
434dd7416e82d5993450e88accdf19927bd427bf
8845158756cddf7368896a659fe13423d244c9a1
/Functions_Of_C/Exercises/multiple.cpp
50baec3de450bead4f217c9611c1051ca859c9b1
[]
no_license
Verg84/COOP
e0ef2cd478d0b669a95acdbf4b13f2e6dac20c3d
8cd1ec842ebc6729fc349e82f3f8ee3b87bac07a
refs/heads/main
2023-07-18T19:21:18.595563
2021-09-24T16:26:03
2021-09-24T16:26:03
405,047,236
0
0
null
2021-09-10T15:36:42
2021-09-10T10:47:56
C++
UTF-8
C++
false
false
533
cpp
// Multiple - Check if a pair of numbers // are multiple together #include<stdio.h> int multiple(int a,int b); int main(){ int a,b; printf("* Enter first value :"); scanf("%d",&a); printf("* Enter second value :"); scanf("%d",&b); if(multiple(a,b)) printf("\n\t\t * Multiples"); else printf("\n\t\t * Not multiples"); printf("\n\n"); return 0; } int multiple(int a,int b){ if(a%b==0) return 1; else return 0; }
[ "50481854+Verg84@users.noreply.github.com" ]
50481854+Verg84@users.noreply.github.com
640f9115446c596ca507fe9aba2d705540971961
efb3753829a06413a4411a4753c547eec11e4c40
/src/libzerocoin/Params.h
1a0ea842c8d7c8e706365160d613f03588b48ac0
[ "MIT" ]
permissive
BitHostCoin/BitHost
69c6471b150104fc1147ca7541274bba546647c8
cd83067acbe16cffa16ab0f752e6da05136c783a
refs/heads/master
2020-04-01T19:55:33.954484
2019-02-22T15:43:29
2019-02-22T15:43:29
153,578,694
4
6
MIT
2019-05-21T21:23:34
2018-10-18T07:06:13
C++
UTF-8
C++
false
false
6,097
h
/** * @file Params.h * * @brief Parameter classes for Zerocoin. * * @author Ian Miers, Christina Garman and Matthew Green * @date June 2013 * * @copyright Copyright 2013 Ian Miers, Christina Garman and Matthew Green * @license This project is released under the MIT license. **/ // Copyright (c) 2017 The Bithost developers #ifndef PARAMS_H_ #define PARAMS_H_ #include "bignum.h" #include "ZerocoinDefines.h" namespace libzerocoin { class IntegerGroupParams { public: /** @brief Integer group class, default constructor * * Allocates an empty (uninitialized) set of parameters. **/ IntegerGroupParams(); /** * Generates a random group element * @return a random element in the group. */ CBigNum randomElement() const; bool initialized; /** * A generator for the group. */ CBigNum g; /** * A second generator for the group. * Note log_g(h) and log_h(g) must * be unknown. */ CBigNum h; /** * The modulus for the group. */ CBigNum modulus; /** * The order of the group */ CBigNum groupOrder; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(initialized); READWRITE(g); READWRITE(h); READWRITE(modulus); READWRITE(groupOrder); } }; class AccumulatorAndProofParams { public: /** @brief Construct a set of Zerocoin parameters from a modulus "N". * @param N A trusted RSA modulus * @param securityLevel A security level expressed in symmetric bits (default 80) * * Allocates and derives a set of Zerocoin parameters from * a trustworthy RSA modulus "N". This routine calculates all * of the remaining parameters (group descriptions etc.) from N * using a verifiable, deterministic procedure. * * Note: this constructor makes the fundamental assumption that "N" * encodes a valid RSA-style modulus of the form "e1 * e2" where * "e1" and "e2" are safe primes. The factors "e1", "e2" MUST NOT * be known to any party, or the security of Zerocoin is * compromised. The integer "N" must be a MINIMUM of 1024 * in length. 3072 bits is strongly recommended. **/ AccumulatorAndProofParams(); //AccumulatorAndProofParams(CBigNum accumulatorModulus); bool initialized; /** * Modulus used for the accumulator. * Product of two safe primes who's factorization is unknown. */ CBigNum accumulatorModulus; /** * The initial value for the accumulator * A random Quadratic residue mod n thats not 1 */ CBigNum accumulatorBase; /** * Lower bound on the value for committed coin. * Required by the accumulator proof. */ CBigNum minCoinValue; /** * Upper bound on the value for a comitted coin. * Required by the accumulator proof. */ CBigNum maxCoinValue; /** * The second of two groups used to form a commitment to * a coin (which it self is a commitment to a serial number). * This one differs from serialNumberSokCommitment due to * restrictions from Camenisch and Lysyanskaya's paper. */ IntegerGroupParams accumulatorPoKCommitmentGroup; /** * Hidden order quadratic residue group mod N. * Used in the accumulator proof. */ IntegerGroupParams accumulatorQRNCommitmentGroup; /** * Security parameter. * Bit length of the challenges used in the accumulator proof. */ uint32_t k_prime; /** * Security parameter. * The statistical zero-knowledgeness of the accumulator proof. */ uint32_t k_dprime; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(initialized); READWRITE(accumulatorModulus); READWRITE(accumulatorBase); READWRITE(accumulatorPoKCommitmentGroup); READWRITE(accumulatorQRNCommitmentGroup); READWRITE(minCoinValue); READWRITE(maxCoinValue); READWRITE(k_prime); READWRITE(k_dprime); } }; class ZerocoinParams { public: /** @brief Construct a set of Zerocoin parameters from a modulus "N". * @param N A trusted RSA modulus * @param securityLevel A security level expressed in symmetric bits (default 80) * * Allocates and derives a set of Zerocoin parameters from * a trustworthy RSA modulus "N". This routine calculates all * of the remaining parameters (group descriptions etc.) from N * using a verifiable, deterministic procedure. * * Note: this constructor makes the fundamental assumption that "N" * encodes a valid RSA-style modulus of the form "e1 * e2" where * "e1" and "e2" are safe primes. The factors "e1", "e2" MUST NOT * be known to any party, or the security of Zerocoin is * compromised. The integer "N" must be a MINIMUM of 1024 * in length. 3072 bits is strongly recommended. **/ ZerocoinParams(CBigNum accumulatorModulus, uint32_t securityLevel = ZEROCOIN_DEFAULT_SECURITYLEVEL); bool initialized; AccumulatorAndProofParams accumulatorParams; /** * The Quadratic Residue group from which we form * a coin as a commitment to a serial number. */ IntegerGroupParams coinCommitmentGroup; /** * One of two groups used to form a commitment to * a coin (which it self is a commitment to a serial number). * This is the one used in the serial number poof. * It's order must be equal to the modulus of coinCommitmentGroup. */ IntegerGroupParams serialNumberSoKCommitmentGroup; /** * The number of iterations to use in the serial * number proof. */ uint32_t zkp_iterations; /** * The amount of the hash function we use for * proofs. */ uint32_t zkp_hash_len; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(initialized); READWRITE(accumulatorParams); READWRITE(coinCommitmentGroup); READWRITE(serialNumberSoKCommitmentGroup); READWRITE(zkp_iterations); READWRITE(zkp_hash_len); } }; } /* namespace libzerocoin */ #endif /* PARAMS_H_ */
[ "44026210+BitHostCoin@users.noreply.github.com" ]
44026210+BitHostCoin@users.noreply.github.com
e34850a83c2a437b0050b2ed8021b5a8d7f3474f
d23d36fd5b4e6851fef68940b15ed625677a576b
/作业6-3/作业6-3/作业6-3Doc.cpp
969c9abd145439c48a9d8fe1f7a6e72f9907f682
[]
no_license
DJQ0926/test
0d5fd731edef513e08b1169578e70fe9139d7d05
e9a755ac66750e14bbb870d211531d91a92fc2ee
refs/heads/master
2021-02-15T23:03:21.681207
2020-07-05T09:51:20
2020-07-05T09:51:20
244,942,227
0
0
null
null
null
null
GB18030
C++
false
false
2,576
cpp
// 作业6-3Doc.cpp : C作业63Doc 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "作业6-3.h" #endif #include "作业6-3Doc.h" #include <propkey.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // C作业63Doc IMPLEMENT_DYNCREATE(C作业63Doc, CDocument) BEGIN_MESSAGE_MAP(C作业63Doc, CDocument) END_MESSAGE_MAP() // C作业63Doc 构造/析构 C作业63Doc::C作业63Doc() { // TODO: 在此添加一次性构造代码 } C作业63Doc::~C作业63Doc() { } BOOL C作业63Doc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // C作业63Doc 序列化 void C作业63Doc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: 在此添加存储代码 } else { // TODO: 在此添加加载代码 } } #ifdef SHARED_HANDLERS // 缩略图的支持 void C作业63Doc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // 修改此代码以绘制文档数据 dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // 搜索处理程序的支持 void C作业63Doc::InitializeSearchContent() { CString strSearchContent; // 从文档数据设置搜索内容。 // 内容部分应由“;”分隔 // 例如: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void C作业63Doc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // C作业63Doc 诊断 #ifdef _DEBUG void C作业63Doc::AssertValid() const { CDocument::AssertValid(); } void C作业63Doc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // C作业63Doc 命令
[ "964158009@qq.com" ]
964158009@qq.com
d78eea6fdad2b5d91a548e8b035a361769309fb2
aa78ede78f08eecde9a78fe1066b81e47ae19390
/Server/Network/MessageProcessing/getstatisticsrequestprocessorobject.h
b62e2d3321221c0310d0f136d0e0ed39c9aa351c
[]
no_license
MafiaMakers/Backend-server
51c342d6e202194b47e183310e348643cbff5d31
1fdc213e841d78aca3b5f70bca45684664e32435
refs/heads/master
2023-01-12T04:57:25.511124
2020-11-02T12:53:50
2020-11-02T12:53:50
254,849,281
0
0
null
null
null
null
UTF-8
C++
false
false
725
h
#ifndef GETSTATISTICSREQUESTPROCESSOROBJECT_H #define GETSTATISTICSREQUESTPROCESSOROBJECT_H #include "processorobject.h" namespace Mafia { namespace Network { namespace MessageProcessing { class GetStatisticsRequestProcessorObject : public ProcessorObject { public: GetStatisticsRequestProcessorObject(Message_t message); /*! * \brief id, которые используются: * userId (int) : id пользователя, статистику которого мы хотим посмотреть */ void process() override; }; } } } #endif // GETSTATISTICSREQUESTPROCESSOROBJECT_H
[ "andrusov.n@gmail.com" ]
andrusov.n@gmail.com
05050db2ee33635a1609b87ea8f76da4e6d43966
67fc9e51437e351579fe9d2d349040c25936472a
/wrappers/8.1.1/vtkBiQuadraticQuadWrap.h
f55ab11479c289095c16f2d45ff02e9f75c00238
[]
permissive
axkibe/node-vtk
51b3207c7a7d3b59a4dd46a51e754984c3302dec
900ad7b5500f672519da5aa24c99aa5a96466ef3
refs/heads/master
2023-03-05T07:45:45.577220
2020-03-30T09:31:07
2020-03-30T09:31:07
48,490,707
6
0
BSD-3-Clause
2022-12-07T20:41:45
2015-12-23T12:58:43
C++
UTF-8
C++
false
false
2,057
h
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKBIQUADRATICQUADWRAP_H #define NATIVE_EXTENSION_VTK_VTKBIQUADRATICQUADWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkBiQuadraticQuad.h> #include "vtkNonLinearCellWrap.h" #include "../../plus/plus.h" class VtkBiQuadraticQuadWrap : public VtkNonLinearCellWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkBiQuadraticQuadWrap(vtkSmartPointer<vtkBiQuadraticQuad>); VtkBiQuadraticQuadWrap(); ~VtkBiQuadraticQuadWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void CellBoundary(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCellDimension(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetCellType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetEdge(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetFace(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNumberOfEdges(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetNumberOfFaces(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetParametricCenter(const Nan::FunctionCallbackInfo<v8::Value>& info); static void InterpolateDerivs(const Nan::FunctionCallbackInfo<v8::Value>& info); static void InterpolateFunctions(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void Triangulate(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKBIQUADRATICQUADWRAP_CLASSDEF VTK_NODE_PLUS_VTKBIQUADRATICQUADWRAP_CLASSDEF #endif }; #endif
[ "axkibe@gmail.com" ]
axkibe@gmail.com
ee299c6fc322467f474d0050b3b484d7dcabe082
aefb8cde419ab4c59383ffe10ca655e9333f149b
/MechanicsTest/Source/MechanicsTest/ProjectileClass.h
2715f1ed5f9f5f958570ba925fcf20f6d22addb6
[]
no_license
DavidBrando/ARGP_Tests
a0837af63bc3605bda5edd6f9be2f1f4169d5ae3
d157df226eb5a5c11226e36239812c6ddd42da58
refs/heads/main
2023-02-21T13:45:41.590497
2021-01-24T14:07:06
2021-01-24T14:07:06
331,369,725
0
0
null
null
null
null
UTF-8
C++
false
false
2,107
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "ProjectileClass.generated.h" class USphereComponent; class UParticleSystemComponent; class USceneComponent; class UProjectileMovementComponent; class UParticleSystem; class UCapsuleComponent; UCLASS() class MECHANICSTEST_API AProjectileClass : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties AProjectileClass(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; //For colision purposes UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UCapsuleComponent* capsule; //root component of the projectile UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) USceneComponent* root; //VFX UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UParticleSystemComponent* bullet; //Component for movement with the logic implemented UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UProjectileMovementComponent* projectileMovement; //More VFX for cool explosions UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) UParticleSystem* explosion = nullptr; //Damage of the projectile UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = ProjectilComp, meta = (AllowPrivateAccess = "true")) float damage = 0.0f; public: // Called every frame virtual void Tick(float DeltaTime) override; UFUNCTION() virtual void OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult); void SetDamage(float nDamage); //seeting a new damage if we want more powerful shoots void MakeProjectileHoming(USceneComponent* target); };
[ "davidtbs@hotmail.es" ]
davidtbs@hotmail.es
f3ce73026cd2e9fd5514aae711e7cc7def61c8a7
2ab8b69d144b242552f65738140ffe93f68ccf2b
/chrome/browser/ui/views/profiles/profile_menu_view_base.cc
862f0c5e976b66fcd1fb3e06a08cb52d1f8615da
[ "BSD-3-Clause" ]
permissive
user-lab/chromium
45c41be02fad35e396e3acc12cc2003ae29ac207
f90402556cc8107ed19e5663ed1e7a4e80ff3e94
refs/heads/master
2023-03-03T23:23:08.506668
2019-10-02T18:21:44
2019-10-02T18:21:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,732
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/profiles/profile_menu_view_base.h" #include <algorithm> #include <memory> #include <utility> #include "base/feature_list.h" #include "base/macros.h" #include "base/metrics/user_metrics.h" #include "build/build_config.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_avatar_icon_util.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/ui_features.h" #include "chrome/browser/ui/views/chrome_layout_provider.h" #include "chrome/browser/ui/views/chrome_typography.h" #include "chrome/browser/ui/views/hover_button.h" #include "chrome/browser/ui/views/profiles/incognito_menu_view.h" #include "chrome/grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/gfx/image/canvas_image_source.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/md_text_button.h" #include "ui/views/controls/link.h" #include "ui/views/controls/scroll_view.h" #include "ui/views/controls/separator.h" #include "ui/views/controls/styled_label.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/view_class_properties.h" #if !defined(OS_CHROMEOS) #include "chrome/browser/ui/views/profiles/profile_menu_view.h" #include "chrome/browser/ui/views/sync/dice_signin_button_view.h" #endif namespace { ProfileMenuViewBase* g_profile_bubble_ = nullptr; // Helpers -------------------------------------------------------------------- constexpr int kMenuWidth = 288; constexpr int kIconSize = 16; constexpr int kIdentityImageSize = 64; constexpr int kMaxImageSize = kIdentityImageSize; // If the bubble is too large to fit on the screen, it still needs to be at // least this tall to show one row. constexpr int kMinimumScrollableContentHeight = 40; // Spacing between the edge of the user menu and the top/bottom or left/right of // the menu items. constexpr int kMenuEdgeMargin = 16; SkColor GetDefaultIconColor() { return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( ui::NativeTheme::kColorId_DefaultIconColor); } SkColor GetDefaultSeparatorColor() { return ui::NativeTheme::GetInstanceForNativeUi()->GetSystemColor( ui::NativeTheme::kColorId_MenuSeparatorColor); } gfx::ImageSkia SizeImage(const gfx::ImageSkia& image, int size) { return gfx::ImageSkiaOperations::CreateResizedImage( image, skia::ImageOperations::RESIZE_BEST, gfx::Size(size, size)); } gfx::ImageSkia ColorImage(const gfx::ImageSkia& image, SkColor color) { return gfx::ImageSkiaOperations::CreateColorMask(image, color); } class CircleImageSource : public gfx::CanvasImageSource { public: CircleImageSource(int size, SkColor color) : gfx::CanvasImageSource(gfx::Size(size, size)), color_(color) {} ~CircleImageSource() override = default; void Draw(gfx::Canvas* canvas) override; private: SkColor color_; DISALLOW_COPY_AND_ASSIGN(CircleImageSource); }; void CircleImageSource::Draw(gfx::Canvas* canvas) { float radius = size().width() / 2.0f; cc::PaintFlags flags; flags.setStyle(cc::PaintFlags::kFill_Style); flags.setAntiAlias(true); flags.setColor(color_); canvas->DrawCircle(gfx::PointF(radius, radius), radius, flags); } gfx::ImageSkia CreateCircle(int size, SkColor color = SK_ColorWHITE) { return gfx::CanvasImageSource::MakeImageSkia<CircleImageSource>(size, color); } gfx::ImageSkia CropCircle(const gfx::ImageSkia& image) { DCHECK_EQ(image.width(), image.height()); return gfx::ImageSkiaOperations::CreateMaskedImage( image, CreateCircle(image.width())); } gfx::ImageSkia AddCircularBackground(const gfx::ImageSkia& image, SkColor bg_color, int size) { if (image.isNull()) return gfx::ImageSkia(); return gfx::ImageSkiaOperations::CreateSuperimposedImage( CreateCircle(size, bg_color), image); } std::unique_ptr<views::BoxLayout> CreateBoxLayout( views::BoxLayout::Orientation orientation, views::BoxLayout::CrossAxisAlignment cross_axis_alignment, gfx::Insets insets = gfx::Insets()) { auto layout = std::make_unique<views::BoxLayout>(orientation, insets); layout->set_cross_axis_alignment(cross_axis_alignment); return layout; } std::unique_ptr<views::View> CreateBorderedBoxView() { constexpr int kBorderThickness = 1; auto bordered_box = std::make_unique<views::View>(); bordered_box->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); bordered_box->SetBorder(views::CreateRoundedRectBorder( kBorderThickness, views::LayoutProvider::Get()->GetCornerRadiusMetric(views::EMPHASIS_HIGH), GetDefaultSeparatorColor())); bordered_box->SetProperty(views::kMarginsKey, gfx::Insets(kMenuEdgeMargin)); return bordered_box; } std::unique_ptr<views::Button> CreateCircularImageButton( views::ButtonListener* listener, const gfx::ImageSkia& image, const base::string16& text, bool show_border = false) { constexpr int kImageSize = 28; const int kBorderThickness = show_border ? 1 : 0; const SkScalar kButtonRadius = (kImageSize + 2 * kBorderThickness) / 2.0; auto button = std::make_unique<views::ImageButton>(listener); button->SetImage(views::Button::STATE_NORMAL, SizeImage(image, kImageSize)); button->SetTooltipText(text); button->SetInkDropMode(views::Button::InkDropMode::ON); button->SetFocusForPlatform(); button->set_ink_drop_base_color(GetDefaultIconColor()); if (show_border) { button->SetBorder(views::CreateRoundedRectBorder( kBorderThickness, kButtonRadius, GetDefaultSeparatorColor())); } // Set circular highlight path. auto path = std::make_unique<SkPath>(); path->addCircle(kButtonRadius, kButtonRadius, kButtonRadius); button->SetProperty(views::kHighlightPathKey, path.release()); return button; } } // namespace // MenuItems-------------------------------------------------------------------- ProfileMenuViewBase::MenuItems::MenuItems() : first_item_type(ProfileMenuViewBase::MenuItems::kNone), last_item_type(ProfileMenuViewBase::MenuItems::kNone), different_item_types(false) {} ProfileMenuViewBase::MenuItems::MenuItems(MenuItems&&) = default; ProfileMenuViewBase::MenuItems::~MenuItems() = default; // ProfileMenuViewBase --------------------------------------------------------- // static void ProfileMenuViewBase::ShowBubble( profiles::BubbleViewMode view_mode, signin_metrics::AccessPoint access_point, views::Button* anchor_button, Browser* browser, bool is_source_keyboard) { if (IsShowing()) return; base::RecordAction(base::UserMetricsAction("ProfileMenu_Opened")); ProfileMenuViewBase* bubble; if (base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) { #if !defined(OS_CHROMEOS) // On Desktop, all modes(regular, guest, incognito) are handled within // ProfileMenuView. bubble = new ProfileMenuView(anchor_button, browser, access_point); #else // On ChromeOS, only the incognito menu is implemented. DCHECK(browser->profile()->IsIncognitoProfile()); bubble = new IncognitoMenuView(anchor_button, browser); #endif } else { if (view_mode == profiles::BUBBLE_VIEW_MODE_INCOGNITO) { DCHECK(browser->profile()->IsIncognitoProfile()); bubble = new IncognitoMenuView(anchor_button, browser); } else { DCHECK_EQ(profiles::BUBBLE_VIEW_MODE_PROFILE_CHOOSER, view_mode); #if !defined(OS_CHROMEOS) bubble = new ProfileMenuView(anchor_button, browser, access_point); #else NOTREACHED(); return; #endif } } views::BubbleDialogDelegateView::CreateBubble(bubble)->Show(); if (is_source_keyboard) bubble->FocusButtonOnKeyboardOpen(); } // static bool ProfileMenuViewBase::IsShowing() { return g_profile_bubble_ != nullptr; } // static void ProfileMenuViewBase::Hide() { if (g_profile_bubble_) g_profile_bubble_->GetWidget()->Close(); } // static ProfileMenuViewBase* ProfileMenuViewBase::GetBubbleForTesting() { return g_profile_bubble_; } ProfileMenuViewBase::ProfileMenuViewBase(views::Button* anchor_button, Browser* browser) : BubbleDialogDelegateView(anchor_button, views::BubbleBorder::TOP_RIGHT), browser_(browser), anchor_button_(anchor_button), close_bubble_helper_(this, browser) { DCHECK(!g_profile_bubble_); g_profile_bubble_ = this; // TODO(sajadm): Remove when fixing https://crbug.com/822075 // The sign in webview will be clipped on the bottom corners without these // margins, see related bug <http://crbug.com/593203>. set_margins(gfx::Insets(2, 0)); DCHECK(anchor_button); anchor_button->AnimateInkDrop(views::InkDropState::ACTIVATED, nullptr); EnableUpDownKeyboardAccelerators(); GetViewAccessibility().OverrideRole(ax::mojom::Role::kMenu); } ProfileMenuViewBase::~ProfileMenuViewBase() { // Items stored for menu generation are removed after menu is finalized, hence // it's not expected to have while destroying the object. DCHECK(g_profile_bubble_ != this); DCHECK(menu_item_groups_.empty()); } void ProfileMenuViewBase::SetIdentityInfo(const gfx::ImageSkia& image, const gfx::ImageSkia& badge, const base::string16& title, const base::string16& subtitle) { constexpr int kTopMargin = 16; constexpr int kBottomMargin = 8; constexpr int kImageToLabelSpacing = 4; constexpr int kBadgeSize = 16; constexpr int kBadgePadding = 1; identity_info_container_->RemoveAllChildViews(/*delete_children=*/true); identity_info_container_->SetLayoutManager( CreateBoxLayout(views::BoxLayout::Orientation::kVertical, views::BoxLayout::CrossAxisAlignment::kCenter, gfx::Insets(kTopMargin, 0, kBottomMargin, 0))); views::ImageView* image_view = identity_info_container_->AddChildView( std::make_unique<views::ImageView>()); // Fall back on |kUserAccountAvatarIcon| if |image| is empty. This can happen // in tests and when the account image hasn't been fetched yet. gfx::ImageSkia sized_image = image.isNull() ? gfx::CreateVectorIcon(kUserAccountAvatarIcon, kIdentityImageSize, kIdentityImageSize) : CropCircle(SizeImage(image, kIdentityImageSize)); gfx::ImageSkia sized_badge = AddCircularBackground(SizeImage(badge, kBadgeSize), SK_ColorWHITE, kBadgeSize + 2 * kBadgePadding); gfx::ImageSkia badged_image = gfx::ImageSkiaOperations::CreateIconWithBadge(sized_image, sized_badge); image_view->SetImage(badged_image); views::View* title_label = identity_info_container_->AddChildView(std::make_unique<views::Label>( title, views::style::CONTEXT_DIALOG_TITLE)); title_label->SetBorder( views::CreateEmptyBorder(kImageToLabelSpacing, 0, 0, 0)); if (!subtitle.empty()) { identity_info_container_->AddChildView(std::make_unique<views::Label>( subtitle, views::style::CONTEXT_LABEL, views::style::STYLE_SECONDARY)); } } void ProfileMenuViewBase::SetSyncInfo(const base::string16& description, const base::string16& link_text, base::RepeatingClosure action) { constexpr int kVerticalPadding = 8; sync_info_container_->RemoveAllChildViews(/*delete_children=*/true); sync_info_container_->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); views::View* separator = sync_info_container_->AddChildView(std::make_unique<views::Separator>()); separator->SetBorder( views::CreateEmptyBorder(0, 0, /*bottom=*/kVerticalPadding, 0)); if (!description.empty()) { views::Label* label = sync_info_container_->AddChildView( std::make_unique<views::Label>(description)); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::ALIGN_CENTER); label->SetHandlesTooltips(false); label->SetBorder(views::CreateEmptyBorder(gfx::Insets(0, kMenuEdgeMargin))); } views::Link* link = sync_info_container_->AddChildView( std::make_unique<views::Link>(link_text)); link->SetHorizontalAlignment(gfx::ALIGN_CENTER); link->set_listener(this); link->SetBorder(views::CreateEmptyBorder(/*top=*/0, /*left=*/kMenuEdgeMargin, /*bottom=*/kVerticalPadding, /*right=*/kMenuEdgeMargin)); RegisterClickAction(link, std::move(action)); } void ProfileMenuViewBase::AddShortcutFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kBottomMargin = 8; constexpr int kButtonSpacing = 6; // Initialize layout if this is the first time a button is added. if (!shortcut_features_container_->GetLayoutManager()) { views::BoxLayout* layout = shortcut_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal, gfx::Insets(0, 0, kBottomMargin, 0), kButtonSpacing)); layout->set_main_axis_alignment( views::BoxLayout::MainAxisAlignment::kCenter); } views::Button* button = shortcut_features_container_->AddChildView( CreateCircularImageButton(this, icon, text, /*show_border=*/true)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddAccountFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kIconSize = 16; // Initialize layout if this is the first time a button is added. if (!account_features_container_->GetLayoutManager()) { account_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); } account_features_container_->AddChildView( std::make_unique<views::Separator>()); views::Button* button = account_features_container_->AddChildView(std::make_unique<HoverButton>( this, SizeImage(ColorImage(icon, GetDefaultIconColor()), kIconSize), text)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::SetProfileHeading(const base::string16& heading) { profile_heading_container_->RemoveAllChildViews(/*delete_children=*/true); profile_heading_container_->SetLayoutManager( std::make_unique<views::FillLayout>()); views::Label* label = profile_heading_container_->AddChildView(std::make_unique<views::Label>( heading, views::style::CONTEXT_LABEL, STYLE_HINT)); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetHandlesTooltips(false); label->SetBorder(views::CreateEmptyBorder(gfx::Insets(0, kMenuEdgeMargin))); } void ProfileMenuViewBase::AddSelectableProfile(const gfx::ImageSkia& image, const base::string16& name, base::RepeatingClosure action) { constexpr int kTopMargin = 8; constexpr int kImageSize = 22; // Initialize layout if this is the first time a button is added. if (!selectable_profiles_container_->GetLayoutManager()) { selectable_profiles_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(kTopMargin, 0, 0, 0))); } gfx::ImageSkia sized_image = CropCircle(SizeImage(image, kImageSize)); views::Button* button = selectable_profiles_container_->AddChildView( std::make_unique<HoverButton>(this, sized_image, name)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddProfileShortcutFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { // Initialize layout if this is the first time a button is added. if (!profile_shortcut_features_container_->GetLayoutManager()) { profile_shortcut_features_container_->SetLayoutManager( CreateBoxLayout(views::BoxLayout::Orientation::kHorizontal, views::BoxLayout::CrossAxisAlignment::kCenter, gfx::Insets(0, 0, 0, /*right=*/kMenuEdgeMargin))); } views::Button* button = profile_shortcut_features_container_->AddChildView( CreateCircularImageButton(this, icon, text)); RegisterClickAction(button, std::move(action)); } void ProfileMenuViewBase::AddProfileFeatureButton( const gfx::ImageSkia& icon, const base::string16& text, base::RepeatingClosure action) { constexpr int kIconSize = 22; // Initialize layout if this is the first time a button is added. if (!profile_features_container_->GetLayoutManager()) { profile_features_container_->SetLayoutManager( std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); } views::Button* button = profile_features_container_->AddChildView( std::make_unique<HoverButton>(this, SizeImage(icon, kIconSize), text)); RegisterClickAction(button, std::move(action)); } gfx::ImageSkia ProfileMenuViewBase::ImageForMenu(const gfx::VectorIcon& icon, float icon_to_image_ratio) { const int padding = static_cast<int>(kMaxImageSize * (1.0 - icon_to_image_ratio) / 2.0); auto sized_icon = gfx::CreateVectorIcon(icon, kMaxImageSize - 2 * padding, GetDefaultIconColor()); return gfx::CanvasImageSource::CreatePadded(sized_icon, gfx::Insets(padding)); } gfx::ImageSkia ProfileMenuViewBase::ColoredImageForMenu( const gfx::VectorIcon& icon, SkColor color) { return gfx::CreateVectorIcon(icon, kMaxImageSize, color); } ax::mojom::Role ProfileMenuViewBase::GetAccessibleWindowRole() { // Return |ax::mojom::Role::kDialog| which will make screen readers announce // the following in the listed order: // the title of the dialog, labels (if any), the focused View within the // dialog (if any) return ax::mojom::Role::kDialog; } void ProfileMenuViewBase::OnThemeChanged() { views::BubbleDialogDelegateView::OnThemeChanged(); SetBackground(views::CreateSolidBackground(GetNativeTheme()->GetSystemColor( ui::NativeTheme::kColorId_DialogBackground))); } int ProfileMenuViewBase::GetDialogButtons() const { return ui::DIALOG_BUTTON_NONE; } bool ProfileMenuViewBase::HandleContextMenu( content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) { // Suppresses the context menu because some features, such as inspecting // elements, are not appropriate in a bubble. return true; } void ProfileMenuViewBase::Init() { Reset(); BuildMenu(); if (!base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) RepopulateViewFromMenuItems(); } void ProfileMenuViewBase::WindowClosing() { DCHECK_EQ(g_profile_bubble_, this); if (anchor_button()) anchor_button()->AnimateInkDrop(views::InkDropState::DEACTIVATED, nullptr); g_profile_bubble_ = nullptr; } void ProfileMenuViewBase::ButtonPressed(views::Button* button, const ui::Event& event) { OnClick(button); } void ProfileMenuViewBase::LinkClicked(views::Link* link, int event_flags) { OnClick(link); } void ProfileMenuViewBase::StyledLabelLinkClicked(views::StyledLabel* link, const gfx::Range& range, int event_flags) { OnClick(link); } void ProfileMenuViewBase::OnClick(views::View* clickable_view) { DCHECK(!click_actions_[clickable_view].is_null()); base::RecordAction( base::UserMetricsAction("ProfileMenu_ActionableItemClicked")); click_actions_[clickable_view].Run(); } int ProfileMenuViewBase::GetMaxHeight() const { gfx::Rect anchor_rect = GetAnchorRect(); gfx::Rect screen_space = display::Screen::GetScreen() ->GetDisplayNearestPoint(anchor_rect.CenterPoint()) .work_area(); int available_space = screen_space.bottom() - anchor_rect.bottom(); #if defined(OS_WIN) // On Windows the bubble can also be show to the top of the anchor. available_space = std::max(available_space, anchor_rect.y() - screen_space.y()); #endif return std::max(kMinimumScrollableContentHeight, available_space); } void ProfileMenuViewBase::Reset() { if (!base::FeatureList::IsEnabled(features::kProfileMenuRevamp)) { menu_item_groups_.clear(); return; } click_actions_.clear(); RemoveAllChildViews(/*delete_childen=*/true); auto components = std::make_unique<views::View>(); components->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical)); // Create and add new component containers in the correct order. // First, add the bordered box with the identity and feature buttons. views::View* bordered_box = components->AddChildView(CreateBorderedBoxView()); identity_info_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); shortcut_features_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); sync_info_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); account_features_container_ = bordered_box->AddChildView(std::make_unique<views::View>()); // Second, add the profile header. auto profile_header = std::make_unique<views::View>(); views::BoxLayout* profile_header_layout = profile_header->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kHorizontal)); profile_heading_container_ = profile_header->AddChildView(std::make_unique<views::View>()); profile_header_layout->SetFlexForView(profile_heading_container_, 1); profile_shortcut_features_container_ = profile_header->AddChildView(std::make_unique<views::View>()); profile_header_layout->SetFlexForView(profile_shortcut_features_container_, 0); components->AddChildView(std::move(profile_header)); // Third, add the profile buttons at the bottom. selectable_profiles_container_ = components->AddChildView(std::make_unique<views::View>()); profile_features_container_ = components->AddChildView(std::make_unique<views::View>()); // Create a scroll view to hold the components. auto scroll_view = std::make_unique<views::ScrollView>(); scroll_view->SetHideHorizontalScrollBar(true); // TODO(https://crbug.com/871762): it's a workaround for the crash. scroll_view->SetDrawOverflowIndicator(false); scroll_view->ClipHeightTo(0, GetMaxHeight()); scroll_view->SetContents(std::move(components)); // Create a grid layout to set the menu width. views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>()); views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, kMenuWidth, kMenuWidth); layout->StartRow(1.0, 0); layout->AddView(std::move(scroll_view)); } int ProfileMenuViewBase::GetMarginSize(GroupMarginSize margin_size) const { switch (margin_size) { case kNone: return 0; case kTiny: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_CONTENT_LIST_VERTICAL_SINGLE); case kSmall: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_RELATED_CONTROL_VERTICAL_SMALL); case kLarge: return ChromeLayoutProvider::Get()->GetDistanceMetric( DISTANCE_UNRELATED_CONTROL_VERTICAL_LARGE); } } void ProfileMenuViewBase::AddMenuGroup(bool add_separator) { if (add_separator && !menu_item_groups_.empty()) { DCHECK(!menu_item_groups_.back().items.empty()); menu_item_groups_.emplace_back(); } menu_item_groups_.emplace_back(); } void ProfileMenuViewBase::AddMenuItemInternal(std::unique_ptr<views::View> view, MenuItems::ItemType item_type) { DCHECK(!menu_item_groups_.empty()); auto& current_group = menu_item_groups_.back(); current_group.items.push_back(std::move(view)); if (current_group.items.size() == 1) { current_group.first_item_type = item_type; current_group.last_item_type = item_type; } else { current_group.different_item_types |= current_group.last_item_type != item_type; current_group.last_item_type = item_type; } } views::Button* ProfileMenuViewBase::CreateAndAddTitleCard( std::unique_ptr<views::View> icon_view, const base::string16& title, const base::string16& subtitle, base::RepeatingClosure action) { std::unique_ptr<HoverButton> title_card = std::make_unique<HoverButton>( this, std::move(icon_view), title, subtitle); if (action.is_null()) title_card->SetEnabled(false); views::Button* button_ptr = title_card.get(); RegisterClickAction(button_ptr, std::move(action)); AddMenuItemInternal(std::move(title_card), MenuItems::kTitleCard); return button_ptr; } views::Button* ProfileMenuViewBase::CreateAndAddButton( const gfx::ImageSkia& icon, const base::string16& title, base::RepeatingClosure action) { std::unique_ptr<HoverButton> button = std::make_unique<HoverButton>(this, icon, title); views::Button* pointer = button.get(); RegisterClickAction(pointer, std::move(action)); AddMenuItemInternal(std::move(button), MenuItems::kButton); return pointer; } views::Button* ProfileMenuViewBase::CreateAndAddBlueButton( const base::string16& text, bool md_style, base::RepeatingClosure action) { std::unique_ptr<views::LabelButton> button = md_style ? views::MdTextButton::CreateSecondaryUiBlueButton(this, text) : views::MdTextButton::Create(this, text); views::Button* pointer = button.get(); RegisterClickAction(pointer, std::move(action)); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(button)); AddMenuItemInternal(std::move(margined_view), MenuItems::kStyledButton); return pointer; } #if !defined(OS_CHROMEOS) DiceSigninButtonView* ProfileMenuViewBase::CreateAndAddDiceSigninButton( AccountInfo* account_info, gfx::Image* account_icon, base::RepeatingClosure action) { std::unique_ptr<DiceSigninButtonView> button = account_info ? std::make_unique<DiceSigninButtonView>(*account_info, *account_icon, this) : std::make_unique<DiceSigninButtonView>(this); DiceSigninButtonView* pointer = button.get(); RegisterClickAction(pointer->signin_button(), std::move(action)); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(GetMarginSize(kSmall), kMenuEdgeMargin))); margined_view->AddChildView(std::move(button)); AddMenuItemInternal(std::move(margined_view), MenuItems::kStyledButton); return pointer; } #endif views::Label* ProfileMenuViewBase::CreateAndAddLabel(const base::string16& text, int text_context) { std::unique_ptr<views::Label> label = std::make_unique<views::Label>(text, text_context); label->SetMultiLine(true); label->SetHorizontalAlignment(gfx::ALIGN_LEFT); label->SetMaximumWidth(kMenuWidth - 2 * kMenuEdgeMargin); views::Label* pointer = label.get(); // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(label)); AddMenuItemInternal(std::move(margined_view), MenuItems::kLabel); return pointer; } views::StyledLabel* ProfileMenuViewBase::CreateAndAddLabelWithLink( const base::string16& text, gfx::Range link_range, base::RepeatingClosure action) { auto label_with_link = std::make_unique<views::StyledLabel>(text, this); label_with_link->SetDefaultTextStyle(views::style::STYLE_SECONDARY); label_with_link->AddStyleRange( link_range, views::StyledLabel::RangeStyleInfo::CreateForLink()); views::StyledLabel* pointer = label_with_link.get(); RegisterClickAction(pointer, std::move(action)); AddViewItem(std::move(label_with_link)); return pointer; } void ProfileMenuViewBase::AddViewItem(std::unique_ptr<views::View> view) { // Add margins. std::unique_ptr<views::View> margined_view = std::make_unique<views::View>(); margined_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(0, kMenuEdgeMargin))); margined_view->AddChildView(std::move(view)); AddMenuItemInternal(std::move(margined_view), MenuItems::kGeneral); } void ProfileMenuViewBase::RegisterClickAction(views::View* clickable_view, base::RepeatingClosure action) { DCHECK(click_actions_.count(clickable_view) == 0); click_actions_[clickable_view] = std::move(action); } void ProfileMenuViewBase::RepopulateViewFromMenuItems() { RemoveAllChildViews(true); // Create a view to keep menu contents. auto contents_view = std::make_unique<views::View>(); contents_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets())); for (unsigned group_index = 0; group_index < menu_item_groups_.size(); group_index++) { MenuItems& group = menu_item_groups_[group_index]; if (group.items.empty()) { // An empty group represents a separator. contents_view->AddChildView(new views::Separator()); } else { views::View* sub_view = new views::View(); GroupMarginSize top_margin; GroupMarginSize bottom_margin; GroupMarginSize child_spacing; if (group.first_item_type == MenuItems::kTitleCard || group.first_item_type == MenuItems::kLabel) { top_margin = kTiny; } else { top_margin = kSmall; } if (group.last_item_type == MenuItems::kTitleCard) { bottom_margin = kTiny; } else if (group.last_item_type == MenuItems::kButton) { bottom_margin = kSmall; } else { bottom_margin = kLarge; } if (!group.different_item_types) { child_spacing = kNone; } else if (group.items.size() == 2 && group.first_item_type == MenuItems::kTitleCard && group.last_item_type == MenuItems::kButton) { child_spacing = kNone; } else { child_spacing = kLarge; } // Reduce margins if previous/next group is not a separator. if (group_index + 1 < menu_item_groups_.size() && !menu_item_groups_[group_index + 1].items.empty()) { bottom_margin = kTiny; } if (group_index > 0 && !menu_item_groups_[group_index - 1].items.empty()) { top_margin = kTiny; } sub_view->SetLayoutManager(std::make_unique<views::BoxLayout>( views::BoxLayout::Orientation::kVertical, gfx::Insets(GetMarginSize(top_margin), 0, GetMarginSize(bottom_margin), 0), GetMarginSize(child_spacing))); for (std::unique_ptr<views::View>& item : group.items) sub_view->AddChildView(std::move(item)); contents_view->AddChildView(sub_view); } } menu_item_groups_.clear(); // Create a scroll view to hold contents view. auto scroll_view = std::make_unique<views::ScrollView>(); scroll_view->SetHideHorizontalScrollBar(true); // TODO(https://crbug.com/871762): it's a workaround for the crash. scroll_view->SetDrawOverflowIndicator(false); scroll_view->ClipHeightTo(0, GetMaxHeight()); scroll_view->SetContents(std::move(contents_view)); // Create a grid layout to set the menu width. views::GridLayout* layout = SetLayoutManager(std::make_unique<views::GridLayout>()); views::ColumnSet* columns = layout->AddColumnSet(0); columns->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, views::GridLayout::kFixedSize, views::GridLayout::FIXED, kMenuWidth, kMenuWidth); layout->StartRow(1.0, 0); layout->AddView(std::move(scroll_view)); if (GetBubbleFrameView()) { SizeToContents(); // SizeToContents() will perform a layout, but only if the size changed. Layout(); } } gfx::ImageSkia ProfileMenuViewBase::CreateVectorIcon( const gfx::VectorIcon& icon) { return gfx::CreateVectorIcon(icon, kIconSize, GetDefaultIconColor()); } int ProfileMenuViewBase::GetDefaultIconSize() { return kIconSize; }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1822abed2252e2145fff8d699f6bf926725acda8
3f3095dbf94522e37fe897381d9c76ceb67c8e4f
/Current/Tutorial_Hint_Escort_BoscoOilShale.hpp
c457a0ce7c16462ae8dca5d8bb425633baca970b
[]
no_license
DRG-Modding/Header-Dumps
763c7195b9fb24a108d7d933193838d736f9f494
84932dc1491811e9872b1de4f92759616f9fa565
refs/heads/main
2023-06-25T11:11:10.298500
2023-06-20T13:52:18
2023-06-20T13:52:18
399,652,576
8
7
null
null
null
null
UTF-8
C++
false
false
467
hpp
#ifndef UE4SS_SDK_Tutorial_Hint_Escort_BoscoOilShale_HPP #define UE4SS_SDK_Tutorial_Hint_Escort_BoscoOilShale_HPP class UTutorial_Hint_Escort_BoscoOilShale_C : public UTutorialHintComponent { FPointerToUberGraphFrame UberGraphFrame; void ReceiveOnInitialized(); void OnBoscoChanged(class ABosco* Bosco); void OnObjectiveUpdated(class UObjective* Objective); void ExecuteUbergraph_Tutorial_Hint_Escort_BoscoOilShale(int32 EntryPoint); }; #endif
[ "bobby45900@gmail.com" ]
bobby45900@gmail.com
bc1822abe4f0e880e932005c5f2d365cab479d51
d2ba0389accde0370662b9df282ef1f8df8d69c7
/frameworks/cocos2d-x/cocos/renderer/scene/assembler/SimpleSprite2D.hpp
01ee7031c8426da5d0a7034a5c3c73104621d72c
[]
no_license
Kuovane/LearnOpenGLES
6a42438db05eecf5c877504013e9ac7682bc291c
8458b9c87d1bf333b8679e90a8a47bc27ebe9ccd
refs/heads/master
2022-07-27T00:28:02.066179
2020-05-14T10:34:46
2020-05-14T10:34:46
262,535,484
0
0
null
null
null
null
UTF-8
C++
false
false
1,600
hpp
/**************************************************************************** Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #pragma once #include "AssemblerSprite.hpp" RENDERER_BEGIN class SimpleSprite2D: public AssemblerSprite { public: SimpleSprite2D(); virtual ~SimpleSprite2D(); virtual void fillBuffers(NodeProxy* node, MeshBuffer* buffer, std::size_t index) override; }; RENDERER_END
[ "811408414@qq.com" ]
811408414@qq.com
52e25b03e075ccdc306265ca26eeb151a8055f50
bdfca7d4bd6e1baf2c43e593de66fcba80afadeb
/prog-verf/assignment1/sketch-1.7.5/sketch-frontend/test/sk/seq/miniTestb475.cpp
5820e9526009cba0d8b432a3231ee597f62cef58
[]
no_license
wanghanxiao123/Semester4
efa82fc435542809d6c1fbed46ed5fea1540787e
c37ecda8b471685b0b6350070b939d01122f5e7f
refs/heads/master
2023-03-22T06:47:16.823584
2021-03-15T10:46:53
2021-03-15T10:46:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
687
cpp
#include <cstdio> #include <assert.h> #include <iostream> using namespace std; #include "vops.h" #include "miniTestb475.h" namespace ANONYMOUS{ void main__Wrapper(int i, int j) { _main(i, j); } void main__WrapperNospec(int i, int j) {} void _main(int i, int j) { int x_s1=0; foo(i, x_s1); int y_s3=0; foo(j, y_s3); if ((i) == (j)) { assert ((x_s1) == (y_s3));; } if ((i) > (j)) { assert ((x_s1) >= (j));; } assert ((x_s1) > (10));; assert ((y_s3) > (10));; } void foo(int i, int& _out) { int rv_s5=0; moo(i, rv_s5); _out = rv_s5; assert ((rv_s5) > (10));; assert ((rv_s5) >= (i));; return; } void moo(int i, int& _out) { _out = i + 11; } }
[ "akshatgoyalak23@gmail.com" ]
akshatgoyalak23@gmail.com
f0d413b81ee182cdb6206fb1b665f0c013fd0e16
f2339e85157027dada17fadd67c163ecb8627909
/Server/EffectServer/Src/EffectAttackEntityAddBuff.h
2950b143e08d127f166f0f3691e3a9f93388e418
[]
no_license
fynbntl/Titan
7ed8869377676b4c5b96df953570d9b4c4b9b102
b069b7a2d90f4d67c072e7c96fe341a18fedcfe7
refs/heads/master
2021-09-01T22:52:37.516407
2017-12-29T01:59:29
2017-12-29T01:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,586
h
/******************************************************************* ** 文件名: EffectAttackEntityAddBuff.h ** 版 权: (C) 深圳冰川网络技术有限公司 2008 - All Rights Reserved ** 创建人: 彭政林 ** 日 期: 3/04/2016 ** 版 本: 1.0 ** 描 述: 效果-攻击实体增加Buff http://172.16.0.120/redmine/issues/1660 ********************************************************************/ #pragma once #include "IEffect.h" #include "EffectDef.h" #include "IEntity.h" using namespace EFFECT_SERVER; #include "IEventEngine.h" #include "IEntityEvent.h" class CEffectAttackEntityAddBuff : public IEffectEx,public IEventExecuteSink { public: typedef EffectServer_AttackEntityAddBuff SCHEME_DATA; CEffectAttackEntityAddBuff( SCHEME_DATA &data ) : m_data(data),m_pEntity(0),m_dwLastTick(0) { } // 获取效果ID virtual int GetID() { return m_data.nID; } // 效果启用 virtual bool Start( EFFECT_CONTEXT * context,CONDITION_CONTEXT *pConditionContext ) { if ( context==0 || context->pEntity==0 ) return false; m_pEntity = context->pEntity; g_EHelper.Subscibe(m_pEntity, this, EVENT_ENTITY_ATTACK, "CEffectAttackEntityAddBuff"); return true; } // 效果停止 virtual void Stop() { if (m_pEntity != 0) { g_EHelper.UnSubscibe(m_pEntity, this, EVENT_ENTITY_ATTACK); m_pEntity = 0; } } // 克隆一个新效果 virtual IEffect * Clone() { return new CEffectAttackEntityAddBuff(m_data); } // 释放 virtual void Release() { Stop(); delete this; } /////////////////////////////////////////IEventExecuteSink///////////////////////////////////////// /** @param wEventID :事件ID @param bSrcType :发送源类型 @param dwSrcID : 发送源标识(实体为UID中"序列号"部份,非实体就为0) @param pszContext : 上下文 @param nLen : 上下文长度 @return @note @warning @retval buffer */ virtual void OnExecute(WORD wEventID, BYTE bSrcType, DWORD dwSrcID, LPCSTR pszContext, int nLen) { switch (wEventID) { case EVENT_ENTITY_ATTACK: { if (m_pEntity == NULL) { break; } UID uidSelf = m_pEntity->getUID(); DWORD dwTick = getTickCountEx(); if (dwTick < m_dwLastTick + m_data.nInterval) { break; } __IBuffPart *pBuffPart = (__IBuffPart *)m_pEntity->getEntityPart(PART_BUFF); if (pBuffPart == NULL) { break; } if (pszContext == NULL || nLen != sizeof(event_entity_attack)) { break; } event_entity_attack *pAttck = (event_entity_attack*)pszContext; UID uidTarget = pAttck->uidTarget; if (isInvalidUID(uidTarget)) { break; } int nType = UID_2_TYPE(uidTarget); switch (nType) { case TYPE_PLAYER_ROLE: { // 检测死亡目标 if (!g_EHelper.chooseTarget(m_pEntity, m_data.nValue, uidTarget)) { return; } } break; case TYPE_MONSTER: { // 取得怪物ID int nMonsterID = getProperty_Integer(uidTarget, PROPERTY_ID); if (nMonsterID == 0) { return; } if (nMonsterID != m_data.nValue) { return; } } break; default: { return; } break; } if (m_data.nBuffID > 0 && m_data.nBuffLevel > 0) { pBuffPart->Add(m_data.nBuffID, m_data.nBuffLevel, uidSelf); m_dwLastTick = dwTick; } } break; default: break; } } private: SCHEME_DATA m_data; // 实体指针 __IEntity *m_pEntity; // 上次时间 DWORD m_dwLastTick; };
[ "85789685@qq.com" ]
85789685@qq.com
52bbb597c8c8f98cd62105b33a12a1372127acfd
1ffb0d73aed05458f75936360948d6964de387af
/src/solver/pibt.h
a95a42b97ddbf3e04292ad313929b67ac3b4f596
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Kei18/pibt
2a05011129cc760395f5c5eabba03a83bf4e53c4
2ad94bc7e9a817d93acef9849b743b6357b8e510
refs/heads/master
2021-12-10T04:22:36.826941
2021-11-23T02:46:06
2021-11-23T02:46:06
187,332,062
24
8
MIT
2020-10-02T12:30:04
2019-05-18T08:14:33
C++
UTF-8
C++
false
false
1,427
h
#pragma once #include "solver.h" class PIBT : public Solver { protected: std::vector<float> epsilon; // tie-breaker std::vector<int> eta; // usually increment every step std::vector<float> priority; // eta + epsilon void init(); void allocate(); virtual void updatePriority(); Nodes createCandidates(Agent* a, Nodes CLOSE_NODE); Nodes createCandidates(Agent* a, Nodes CLOSE_NODE, Node* tmp); bool priorityInheritance(Agent* a, Nodes& CLOSE_NODE, Agents& OPEN_AGENT, std::vector<float>& PL); bool priorityInheritance(Agent* a, Agent* aFrom, Nodes& CLOSE_NODE, Agents& OPEN_AGENT, std::vector<float>& PL); virtual bool priorityInheritance(Agent* a, Nodes C, Nodes& CLOSE_NODE, Agents& OPEN_AGENT, std::vector<float>& PL); virtual Node* chooseNode(Agent* a, Nodes C); void updateC(Nodes& C, Node* target, Nodes CLOSE_NODE); float getDensity(Agent* a); // density can be used as effective prioritization public: PIBT(Problem* _P); PIBT(Problem* _P, std::mt19937* _MT); ~PIBT(); bool solve(); virtual void update(); virtual std::string logStr(); };
[ "keisuke.oku18@gmail.com" ]
keisuke.oku18@gmail.com
a2856338366b452cb3013205add7fb77d387fe03
5a6ff800792bf62756fe9750bf8a4d94e7abc3a4
/Project X/Space.cpp
fb37b64d5fee20916e30c95d23c32ef073037009
[]
no_license
Barsegyans/ProjectX
8cc85d8ed8e9da365e55c077d12039af86c8f5c9
1aa2808ba93b34565488edee60667592a8b57a51
refs/heads/master
2021-01-13T09:02:47.337835
2016-12-02T12:03:16
2016-12-02T12:03:16
72,372,142
0
0
null
2016-12-02T11:58:32
2016-10-30T19:59:35
C++
UTF-8
C++
false
false
206
cpp
#include"Space.h" Space::Space(float x, float y): Box2D(Point2D(0,0),Point2D(x, y)) {}; Space::Space(Point2D const & a, Point2D const & b): Box2D(a,b) {}; Space::Space(Box2D const & b): Box2D(b){};
[ "Serbarmephi@gmail.com" ]
Serbarmephi@gmail.com
441764aedd755eec87ae91579180957396c752da
09e5294e6019b13f8bdfd9daf1b6ce358062ce34
/src/main.cpp
efe364abc6732a48176ec7081761b43c0bc752ef
[]
no_license
soarchorale/interview
2f84801ac994a41e3c2e8436b8f350859396353e
433181772aa37ca6b195a42ff38d7b93c6684d44
refs/heads/main
2023-02-19T21:53:39.470325
2021-01-24T12:10:51
2021-01-24T12:10:51
332,129,412
1
0
null
null
null
null
UTF-8
C++
false
false
417
cpp
#include "complexAdd.h" #include <iostream> #include <thread> int main() { ComplexAdd* complex_add = new ComplexAdd(); std::thread A(&ComplexAdd::ProducerInt, complex_add); std::thread B(&ComplexAdd::ProducerDouble, complex_add); std::thread C(&ComplexAdd::Comsumer, complex_add); std::thread D(&ComplexAdd::Print, complex_add); A.join(); B.join(); C.join(); D.join(); delete complex_add; return 0; }
[ "463052596@qq.com" ]
463052596@qq.com